import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { api } from '../api.js';

/**
 * InvSelect — multi-select with checkboxes + inline "Add item"
 * Generic replacement for CategorySelect, works with categories_inv / secteurs_inv.
 *
 * Props:
 *   items          : { id, nom, is_global }[]  — liste complète fournie par le parent
 *   selected       : number[]                   — ids sélectionnés
 *   onChange       : (ids: number[]) => void
 *   addApiPath     : string                     — ex. '/categories-inv' | '/secteurs-inv'
 *   onItemAdded    : ({ id, nom, is_global }) => void  — appelé après création inline
 *   emptyLabel     : string                     — texte si rien de sélectionné
 *   addLabel       : string                     — texte du bouton "Ajouter"
 *   inputPlaceholder : string                   — placeholder du champ de création
 */
export default function InvSelect({
  items = [],
  selected = [],
  onChange,
  addApiPath,
  onItemAdded,
  emptyLabel      = 'Aucun élément sélectionné',
  addLabel        = 'Ajouter un élément',
  inputPlaceholder = 'Nom…',
  inheritedIds    = [],
}) {
  const [open, setOpen]     = useState(false);
  const [adding, setAdding] = useState(false);
  const [newName, setNewName] = useState('');
  const [err, setErr]       = useState(null);
  const [busy, setBusy]     = useState(false);
  const [dropPos, setDropPos] = useState({ top: 0, left: 0, width: 0 });

  const wrapRef    = useRef(null);
  const triggerRef = useRef(null);

  useLayoutEffect(() => {
    if (!open || !triggerRef.current) return;
    const rect = triggerRef.current.getBoundingClientRect();
    setDropPos({ top: rect.bottom + 4, left: rect.left, width: rect.width });
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const close = (e) => {
      if (wrapRef.current?.contains(e.target)) return;
      const drop = document.getElementById('inv-select-dropdown-portal');
      if (drop?.contains(e.target)) return;
      setOpen(false);
    };
    const closeOnScroll = (e) => {
      const drop = document.getElementById('inv-select-dropdown-portal');
      if (drop?.contains(e.target)) return; // scroll dans le dropdown — on garde ouvert
      setOpen(false);
    };
    document.addEventListener('mousedown', close);
    window.addEventListener('scroll', closeOnScroll, true);
    window.addEventListener('resize', closeOnScroll);
    return () => {
      document.removeEventListener('mousedown', close);
      window.removeEventListener('scroll', closeOnScroll, true);
      window.removeEventListener('resize', closeOnScroll);
    };
  }, [open]);

  const toggle = (id) => {
    if (inheritedIds.includes(id)) return; // tag hérité du référentiel, non modifiable
    onChange(selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id]);
  };

  const addItem = async (e) => {
    e.preventDefault();
    if (!newName.trim()) return;
    setBusy(true); setErr(null);
    try {
      const item = await api.post(addApiPath, { nom: newName.trim() });
      onItemAdded?.(item);
      onChange([...selected, item.id]);
      setNewName('');
      setAdding(false);
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  };

  const triggerLabel = (() => {
    if (selected.length === 0) return emptyLabel;
    const names = items.filter(c => selected.includes(c.id)).map(c => c.nom);
    if (names.length <= 2) return names.join(', ');
    return `${names.length} éléments sélectionnés`;
  })();

  const dropdown = open ? (
    <div
      id="inv-select-dropdown-portal"
      className="cat-select-dropdown"
      role="listbox"
      aria-multiselectable="true"
      style={{ position: 'fixed', top: dropPos.top, left: dropPos.left, width: dropPos.width, zIndex: 9999 }}
    >
      {items.length === 0 && (
        <div className="cat-select-empty">{emptyLabel}</div>
      )}
      {items.map(item => {
        const checked = selected.includes(item.id);
        const inherited = inheritedIds.includes(item.id);
        return (
          <label key={item.id} className={`cat-select-item${checked ? ' checked' : ''}${inherited ? ' inherited' : ''}`}
            title={inherited ? 'Hérité du référentiel — non modifiable' : undefined}>
            <input type="checkbox" checked={checked || inherited} disabled={inherited} onChange={() => toggle(item.id)} />
            <span>{item.nom}</span>
            {inherited
              ? <span style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 600, padding: '1px 5px',
                  borderRadius: 3, background: 'var(--accent)', color: '#fff', opacity: .85 }}>Réf</span>
              : checked && (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                  style={{ marginLeft: 'auto', color: 'var(--accent)' }} aria-hidden="true">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              )
            }
          </label>
        );
      })}

      {addApiPath && (
        <>
          <div className="cat-select-sep" />
          {!adding ? (
            <button type="button" className="cat-select-add-btn"
              onClick={() => { setAdding(true); setErr(null); }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                aria-hidden="true">
                <line x1="12" y1="5" x2="12" y2="19"/>
                <line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              {addLabel}
            </button>
          ) : (
            <form onSubmit={addItem} className="cat-select-new-form">
              <input
                autoFocus
                value={newName}
                onChange={e => setNewName(e.target.value)}
                placeholder={inputPlaceholder}
                maxLength={200}
              />
              <div className="cat-select-new-actions">
                <button type="submit" className="primary" disabled={busy || !newName.trim()}>
                  {busy ? '…' : 'Créer'}
                </button>
                <button type="button" className="ghost"
                  onClick={() => { setAdding(false); setNewName(''); setErr(null); }}>
                  Annuler
                </button>
              </div>
              {err && <div className="cat-select-err">{err}</div>}
            </form>
          )}
        </>
      )}
    </div>
  ) : null;

  return (
    <>
      <div ref={wrapRef} className="cat-select-wrap">
        <button
          ref={triggerRef}
          type="button"
          className={`cat-select-trigger${open ? ' open' : ''}`}
          onClick={() => { setOpen(o => !o); setAdding(false); setErr(null); }}
          aria-haspopup="listbox"
          aria-expanded={open}
        >
          <span className="cat-select-label">{triggerLabel}</span>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
            style={{ flexShrink: 0, transition: 'transform .15s', transform: open ? 'rotate(0deg)' : 'rotate(180deg)' }}
            aria-hidden="true">
            <path d="M18 15l-6-6-6 6"/>
          </svg>
        </button>
      </div>

      {dropdown}
    </>
  );
}
