import { useState } from 'react';
import { Button } from '../../Atoms/Button/Button';
import { ModalCatalogoPuestos } from './ModalCatalogoPuestos';
import { MODAL_CATALOGO_PUESTOS_DEFAULT_ITEMS } from './modalCatalogoPuestosDefaults';

export default {
  title: 'Layout/ModalCatalogoPuestos',
  component: ModalCatalogoPuestos,
  tags: ['autodocs'],
  parameters: { layout: 'fullscreen' },
};

export const Default = {
  render: function CatalogoPuestosStory() {
    const [open, setOpen] = useState(true);
    const [items, setItems] = useState(MODAL_CATALOGO_PUESTOS_DEFAULT_ITEMS);
    const [newItemValue, setNewItemValue] = useState('');
    const [editingItemId, setEditingItemId] = useState(null);
    const [editingItemValue, setEditingItemValue] = useState('');

    const handleCreate = (label) => {
      const trimmed = String(label ?? '').trim();
      if (!trimmed) return;
      setItems((prev) => [...prev, { id: `puesto-${Date.now()}`, label: trimmed }]);
      setNewItemValue('');
    };

    return (
      <div style={{ minHeight: '100vh', padding: 24 }}>
        <Button onClick={() => setOpen(true)}>Abrir catálogo de puestos</Button>
        <ModalCatalogoPuestos
          isOpen={open}
          onClose={() => setOpen(false)}
          items={items}
          newItemValue={newItemValue}
          onNewItemChange={setNewItemValue}
          onCreate={handleCreate}
          editingItemId={editingItemId}
          editingItemValue={editingItemValue}
          onEditStart={(item) => {
            setEditingItemId(item.id);
            setEditingItemValue(item.label ?? '');
          }}
          onEditingItemChange={(value) => setEditingItemValue(value)}
          onEditSave={(item) => {
            const trimmed = String(editingItemValue ?? '').trim();
            if (!trimmed) return;
            setItems((prev) =>
              prev.map((entry) => (entry.id === item.id ? { ...entry, label: trimmed } : entry)),
            );
            setEditingItemId(null);
            setEditingItemValue('');
          }}
          onEditCancel={() => {
            setEditingItemId(null);
            setEditingItemValue('');
          }}
          onDelete={(item) => {
            setItems((prev) => prev.filter((entry) => entry.id !== item.id));
            if (editingItemId === item.id) {
              setEditingItemId(null);
              setEditingItemValue('');
            }
          }}
        />
      </div>
    );
  },
};

export const Abierto = {
  args: {
    isOpen: true,
    onClose: () => undefined,
  },
};
