// PrepCatalog.jsx — Master list of all prep items.
// Owner maintains this once; daily templates pick from this list.

const CATALOG_KEY = 'snap-portal-prep-catalog-v1';
const CATEGORIES_C = ['Meat', 'Vegetable', 'Sauce', 'Other', 'Cleaning & Fixing'];

// Seed catalog from sample data — every prep item from sampleData.js becomes
// a catalog entry (with its default target/priority/comment).
const seedCatalog = () => {
  return (window.SAMPLE_PREP_ITEMS || []).map(item => ({
    id: item.id,
    name: item.name,
    category: item.category,
    unit: item.unit || '',
    archived: false,
  }));
};

const PrepCatalog = () => {
  const [catalog, setCatalog] = usePersistent(CATALOG_KEY, seedCatalog());
  const [search, setSearch] = useState('');
  const [filterCat, setFilterCat] = useState('all');
  const [showArchived, setShowArchived] = useState(false);
  const [editing, setEditing] = useState(null); // item or 'new'
  const [toast, setToast] = useState('');

  const visible = catalog
    .filter(i => showArchived ? i.archived : !i.archived)
    .filter(i => filterCat === 'all' || i.category === filterCat)
    .filter(i => !search || i.name.toLowerCase().includes(search.toLowerCase()));

  // Group visible by category
  const grouped = {};
  CATEGORIES_C.forEach(c => { grouped[c] = []; });
  visible.forEach(i => { (grouped[i.category] = grouped[i.category] || []).push(i); });

  const save = (item) => {
    if (item.id && catalog.some(c => c.id === item.id)) {
      setCatalog(cs => cs.map(c => c.id === item.id ? item : c));
      setToast('Item updated');
    } else {
      const id = 'p-' + Date.now();
      setCatalog(cs => [...cs, { ...item, id, archived: false }]);
      setToast('Item added to catalog');
    }
    setEditing(null);
  };

  const archive = (id) => {
    setCatalog(cs => cs.map(c => c.id === id ? { ...c, archived: true } : c));
    setToast('Archived — won\'t appear in templates');
  };

  const restore = (id) => {
    setCatalog(cs => cs.map(c => c.id === id ? { ...c, archived: false } : c));
    setToast('Restored to catalog');
  };

  const remove = (id) => {
    if (!confirm('Delete this item permanently? Past templates that reference it stay intact.')) return;
    setCatalog(cs => cs.filter(c => c.id !== id));
    setToast('Item deleted');
  };

  const totalActive = catalog.filter(c => !c.archived).length;
  const totalArchived = catalog.filter(c => c.archived).length;

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1280 }}>
      <div className="portal-page-header">
        <div>
          <h1 className="portal-page-title">Prep Catalog</h1>
          <div className="portal-page-subtitle">
            Master list of every prep item. Daily templates pick from here — staff never type free text.
          </div>
        </div>
        <PBtn variant="primary" icon="plus" onClick={() => setEditing('new')}>Add item</PBtn>
      </div>

      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 16 }}>
        <div style={{ position: 'relative', flex: 1, maxWidth: 280 }}>
          <PIcon name="search" size={14} color="var(--fg-3)" style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)' }} />
          <input className="portal-input" placeholder="Search items…" value={search} onChange={e => setSearch(e.target.value)} style={{ paddingLeft: 32, height: 34 }} />
        </div>
        <select className="portal-input" value={filterCat} onChange={e => setFilterCat(e.target.value)} style={{ height: 34, width: 180 }}>
          <option value="all">All categories</option>
          {CATEGORIES_C.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
        <div style={{ flex: 1 }} />
        <button onClick={() => setShowArchived(s => !s)} style={{
          fontSize: 12.5, color: showArchived ? 'var(--fg-1)' : 'var(--fg-3)',
          padding: '6px 10px', borderRadius: 8,
          background: showArchived ? 'var(--bg-sunken)' : 'transparent',
        }}>
          {showArchived ? `Showing archived (${totalArchived})` : `Show archived (${totalArchived})`}
        </button>
      </div>

      <div className="portal-card" style={{ padding: 0 }}>
        <table className="portal-table">
          <thead>
            <tr>
              <th>Item</th>
              <th style={{ width: 200 }}>Category</th>
              <th style={{ width: 100 }}></th>
            </tr>
          </thead>
          <tbody>
            {CATEGORIES_C.map(cat => {
              const items = grouped[cat] || [];
              if (items.length === 0) return null;
              return (
                <React.Fragment key={cat}>
                  <tr style={{ background: 'var(--bg-sunken)' }}>
                    <td colSpan={3} style={{ padding: '6px 12px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <PCategoryChip category={cat} />
                        <span style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500 }}>{items.length}</span>
                      </div>
                    </td>
                  </tr>
                  {items.map(item => (
                    <tr key={item.id} onClick={() => setEditing(item)} style={{ cursor: 'pointer' }}>
                      <td style={{ fontWeight: 500 }}>{item.name}</td>
                      <td style={{ fontSize: 12.5, color: 'var(--fg-2)' }}>{item.category}</td>
                      <td onClick={e => e.stopPropagation()}>
                        <div className="row-actions">
                          <button onClick={() => setEditing(item)} title="Edit"><PIcon name="edit" size={13} /></button>
                          {item.archived ? (
                            <>
                              <button onClick={() => restore(item.id)} title="Restore">
                                <PIcon name="check" size={13} />
                              </button>
                              <button onClick={() => remove(item.id)} title="Delete forever">
                                <PIcon name="trash" size={13} />
                              </button>
                            </>
                          ) : (
                            <button onClick={() => archive(item.id)} title="Archive">
                              <PIcon name="archive" size={13} />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </React.Fragment>
              );
            })}
            {visible.length === 0 && (
              <tr>
                <td colSpan={3} style={{ padding: 40, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
                  {showArchived ? 'No archived items.' : (search || filterCat !== 'all' ? 'No items match your filter.' : 'Catalog is empty. Add your first item.')}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div style={{ marginTop: 18, padding: 14, background: 'var(--bg-sunken)', borderRadius: 10, fontSize: 12.5, color: 'var(--fg-2)', lineHeight: 1.5 }}>
        <strong style={{ color: 'var(--fg-1)' }}>{totalActive} active items</strong> · pick from this list when building today's assignment. Target, priority, and comments are set per day.
      </div>

      {editing && (
        <CatalogEditor
          initial={editing === 'new' ? null : editing}
          onClose={() => setEditing(null)}
          onSave={save}
        />
      )}

      <PToast message={toast} open={!!toast} onClose={() => setToast('')} />
    </div>
  );
};

const CatalogEditor = ({ initial, onClose, onSave }) => {
  const [name, setName]         = useState(initial?.name || '');
  const [category, setCategory] = useState(initial?.category || 'Meat');

  const canSave = name.trim();

  return (
    <PModal open onClose={onClose} title={initial ? `Edit — ${initial.name}` : 'New catalog item'} width={500}>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <CatLabel>Name</CatLabel>
          <input className="portal-input" placeholder="e.g. Basic Sauce" value={name} onChange={e => setName(e.target.value)} autoFocus style={{ height: 36 }} />
        </div>

        <div>
          <CatLabel>Category</CatLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {CATEGORIES_C.map(c => (
              <button key={c} onClick={() => setCategory(c)} style={{
                padding: '6px 12px', borderRadius: 999,
                fontSize: 12.5, fontWeight: 500,
                background: category === c ? 'var(--fg-1)' : 'var(--bg-sunken)',
                color: category === c ? '#fff' : 'var(--fg-1)',
              }}>{c}</button>
            ))}
          </div>
        </div>

        <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>
          Target, priority, and comments are set per day on the Prep Assignment page.
        </div>
      </div>
      <div style={{ padding: '12px 18px', borderTop: '1px solid var(--border-2)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <PBtn variant="ghost" onClick={onClose}>Cancel</PBtn>
        <PBtn variant="primary" disabled={!canSave} onClick={() => onSave({
          ...(initial || {}),
          id: initial?.id,
          name: name.trim(),
          category,
        })}>{initial ? 'Save changes' : 'Add to catalog'}</PBtn>
      </div>
    </PModal>
  );
};

const CatLabel = ({ children }) => (
  <div style={{ fontSize: 11.5, fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 6 }}>{children}</div>
);

window.PrepCatalog = PrepCatalog;
window.CATALOG_KEY = CATALOG_KEY;
window.SEED_CATALOG = seedCatalog;
