import { useRef } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { ModalShell } from '../ModalShell/ModalShell';
import {
  MODAL_SHELL_FOOTER_BUTTON_BASE_STYLE,
  MODAL_SHELL_FOOTER_BUTTON_TEXT_STYLE,
} from '../ModalShell/modalShellStyles';
import { GreenScrollbar } from '../VistaDatos/GreenScrollbar';
import { MODAL_CATALOGO_PUESTOS_DEFAULT_ITEMS } from './modalCatalogoPuestosDefaults';
import {
  MODAL_CATALOGO_PUESTOS_HEIGHT_PX,
  MODAL_CATALOGO_PUESTOS_ICON_BTN_STYLE,
  MODAL_CATALOGO_PUESTOS_ITEM_LABEL_STYLE,
  MODAL_CATALOGO_PUESTOS_ITEM_STYLE,
  MODAL_CATALOGO_PUESTOS_SAVE_BTN_STYLE,
  MODAL_CATALOGO_PUESTOS_WIDTH_PX,
} from './modalCatalogoPuestosStyles';

const LIST_SCROLLBAR_GUTTER_PX = 16;

function resolveItemLabel(item) {
  if (!item) return '';
  return item.label ?? item.nombre ?? item.name ?? String(item.id ?? '');
}

function resolveItemId(item, index) {
  return item?.id ?? item?.key ?? `item-${index}`;
}

/**
 * Modal «Catálogo de puestos»: alta, edición inline y eliminación de ítems.
 * Datos y callbacks los controla el consumidor.
 *
 * @param {boolean} [isOpen]
 * @param {function} [onClose]
 * @param {string} [title]
 * @param {Array<{id?: string, label?: string, nombre?: string}>} [items]
 * @param {string} [newItemValue]
 * @param {function} [onNewItemChange]
 * @param {function} [onCreate]
 * @param {string|null} [editingItemId]
 * @param {string} [editingItemValue]
 * @param {function} [onEditingItemChange]
 * @param {function} [onEditStart] — `(item, index) => void`
 * @param {function} [onEditSave] — `(item, index) => void`
 * @param {function} [onEditCancel]
 * @param {function} [onDelete] — `(item, index) => void`
 * @param {string} [newItemPlaceholder]
 * @param {string} [createButtonLabel]
 * @param {string} [closeButtonLabel]
 * @param {string} [emptyMessage]
 * @param {boolean} [disableCreate]
 * @param {React.ReactNode} [footer]
 */
export const ModalCatalogoPuestos = ({
  isOpen = false,
  onClose,
  title = 'Catálogo de puestos',
  items = MODAL_CATALOGO_PUESTOS_DEFAULT_ITEMS,
  newItemValue = '',
  onNewItemChange,
  onCreate,
  editingItemId = null,
  editingItemValue = '',
  onEditingItemChange,
  onEditStart,
  onEditSave,
  onEditCancel,
  onDelete,
  newItemPlaceholder = 'Nombre del puesto...',
  createButtonLabel = '+ Crear',
  closeButtonLabel = 'Cerrar',
  emptyMessage = 'No hay puestos cargados.',
  disableCreate = false,
  footer,
  width = MODAL_CATALOGO_PUESTOS_WIDTH_PX,
  height = MODAL_CATALOGO_PUESTOS_HEIGHT_PX,
  closeOnOverlayClick = true,
  zIndex = 1500,
  className = '',
  panelStyle,
  ...props
}) => {
  const listRef = useRef(null);
  const list = Array.isArray(items) ? items : [];
  const trimmedNew = String(newItemValue ?? '').trim();
  const canCreate = !disableCreate && trimmedNew.length > 0;

  const defaultFooter = (
    <PrimaryActionButton
      variant="outline"
      text={closeButtonLabel}
      onClick={() => onClose?.()}
      textStyle={MODAL_SHELL_FOOTER_BUTTON_TEXT_STYLE}
      style={MODAL_SHELL_FOOTER_BUTTON_BASE_STYLE}
    />
  );

  return (
    <ModalShell
      isOpen={isOpen}
      onClose={onClose}
      title={title}
      width={width}
      height={height}
      closeOnOverlayClick={closeOnOverlayClick}
      zIndex={zIndex}
      className={className}
      panelStyle={panelStyle}
      footer={footer ?? defaultFooter}
      {...props}
    >
      <div
        className="anima-modal-catalogo-puestos"
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          minHeight: 0,
          padding: '16px',
          boxSizing: 'border-box',
          gap: 16,
        }}
      >
        <div
          className="anima-modal-catalogo-puestos__create"
          style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flexShrink: 0 }}
        >
          <div style={{ flex: 1, minWidth: 0 }}>
            <PrimaryInput
              id="modal-catalogo-puestos-nuevo"
              name="modalCatalogoPuestosNuevo"
              placeholder={newItemPlaceholder}
              value={newItemValue}
              onChange={(event) => onNewItemChange?.(event?.target?.value ?? '', event)}
              onKeyDown={(event) => {
                if (event.key === 'Enter' && canCreate) {
                  event.preventDefault();
                  onCreate?.(trimmedNew, event);
                }
              }}
            />
          </div>
          <PrimaryActionButton
            variant="primary"
            text={createButtonLabel}
            disabled={!canCreate}
            onClick={() => onCreate?.(trimmedNew)}
            style={{ height: 42, minWidth: 0, padding: '8px 14px', flexShrink: 0 }}
            textStyle={{ fontSize: '16px', lineHeight: '24px' }}
          />
        </div>

        <div
          className="anima-modal-catalogo-puestos__list-wrap"
          style={{ position: 'relative', flex: '1 1 auto', minHeight: 0 }}
        >
          <div
            ref={listRef}
            className="anima-modal-catalogo-puestos__list"
            style={{
              height: '100%',
              overflowY: 'auto',
              overflowX: 'hidden',
              paddingRight: LIST_SCROLLBAR_GUTTER_PX,
              boxSizing: 'border-box',
              scrollbarWidth: 'none',
              msOverflowStyle: 'none',
              WebkitOverflowScrolling: 'touch',
            }}
          >
            <style>{`
              .anima-modal-catalogo-puestos__list::-webkit-scrollbar {
                display: none;
                width: 0;
                height: 0;
              }
            `}</style>

            {list.length === 0 ? (
              <p
                style={{
                  fontFamily: 'IBM Plex Sans, sans-serif',
                  fontSize: 14,
                  lineHeight: '21px',
                  color: '#6B7280',
                  margin: 0,
                  padding: '8px 0',
                }}
              >
                {emptyMessage}
              </p>
            ) : (
              <ul
                style={{
                  listStyle: 'none',
                  margin: 0,
                  padding: 0,
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 8,
                }}
              >
                {list.map((item, index) => {
                  const itemId = resolveItemId(item, index);
                  const isEditing = editingItemId != null && String(editingItemId) === String(itemId);

                  return (
                    <li key={itemId}>
                      {isEditing ? (
                        <div style={MODAL_CATALOGO_PUESTOS_ITEM_STYLE}>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <PrimaryInput
                              id={`modal-catalogo-puestos-edit-${itemId}`}
                              value={editingItemValue}
                              onChange={(event) =>
                                onEditingItemChange?.(event?.target?.value ?? '', item, index, event)
                              }
                              onKeyDown={(event) => {
                                if (event.key === 'Enter') {
                                  event.preventDefault();
                                  onEditSave?.(item, index, event);
                                }
                                if (event.key === 'Escape') {
                                  event.preventDefault();
                                  onEditCancel?.(item, index, event);
                                }
                              }}
                              style={{ height: 42 }}
                            />
                          </div>
                          <button
                            type="button"
                            aria-label="Guardar puesto"
                            style={MODAL_CATALOGO_PUESTOS_SAVE_BTN_STYLE}
                            onClick={() => onEditSave?.(item, index)}
                          >
                            <Icon
                              name="CheckIcon"
                              variant="24-outline"
                              size={20}
                              style={{ color: '#FFFFFF' }}
                            />
                          </button>
                          <button
                            type="button"
                            aria-label="Eliminar puesto"
                            style={MODAL_CATALOGO_PUESTOS_ICON_BTN_STYLE}
                            onClick={() => onDelete?.(item, index)}
                          >
                            <Icon
                              name="TrashIcon"
                              variant="24-outline"
                              size={22}
                              style={{ color: '#B30808' }}
                            />
                          </button>
                        </div>
                      ) : (
                        <div style={MODAL_CATALOGO_PUESTOS_ITEM_STYLE}>
                          <p style={MODAL_CATALOGO_PUESTOS_ITEM_LABEL_STYLE}>{resolveItemLabel(item)}</p>
                          <button
                            type="button"
                            aria-label="Editar puesto"
                            style={MODAL_CATALOGO_PUESTOS_ICON_BTN_STYLE}
                            onClick={() => onEditStart?.(item, index)}
                          >
                            <Icon
                              name="PencilSquareIcon"
                              variant="24-outline"
                              size={22}
                              style={{ color: '#29474C' }}
                            />
                          </button>
                          <button
                            type="button"
                            aria-label="Eliminar puesto"
                            style={MODAL_CATALOGO_PUESTOS_ICON_BTN_STYLE}
                            onClick={() => onDelete?.(item, index)}
                          >
                            <Icon
                              name="TrashIcon"
                              variant="24-outline"
                              size={22}
                              style={{ color: '#B30808' }}
                            />
                          </button>
                        </div>
                      )}
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
          <GreenScrollbar scrollRef={listRef} insetRight={0} />
        </div>
      </div>
    </ModalShell>
  );
};

export { MODAL_CATALOGO_PUESTOS_DEFAULT_ITEMS } from './modalCatalogoPuestosDefaults';
export default ModalCatalogoPuestos;
