// TruckOrderSettings.jsx — par config + active toggle for each inventory item.
//
// Defines, per inventory item:
//   active     — does it appear on truck-order count sheets?
//   threshold  — order trigger (optional). If on-hand > threshold, don't order.
//                If null, trigger = max (order any time below max).
//   max        — target stock level after ordering.
//
// Auto-order math:  if onHand <= trigger → order ceil(max - onHand)
//
// Pars are stored as { [itemId]: { active, threshold, max } }.

const { useState: usePS, useMemo: useMemoPS } = React;

const ParSettings = ({ pars, setPars }) => {
  const allItems      = window.SAMPLE_INVENTORY_ITEMS      || [];
  const allCategories = window.SAMPLE_INVENTORY_CATEGORIES || [];
  const allVendors    = window.SAMPLE_VENDORS              || [];

  const catById    = useMemoPS(() => Object.fromEntries(allCategories.map(c => [c.id, c])), [allCategories]);
  const vendorById = useMemoPS(() => Object.fromEntries(allVendors.map(v => [v.id, v])), [allVendors]);

  const [search, setSearch]       = usePS('');
  const [catFilter, setCatFilter] = usePS('all');
  const [activeOnly, setActiveOnly] = usePS(false);

  const filtered = useMemoPS(() => {
    const q = search.trim().toLowerCase();
    return allItems.filter(item => {
      const par = pars[item.id] || {};
      if (activeOnly && par.active === false) return false;
      if (catFilter !== 'all' && item.categoryId !== catFilter) return false;
      if (!q) return true;
      const hay = [item.name, vendorById[item.vendorId]?.name].filter(Boolean).join(' ').toLowerCase();
      return hay.includes(q);
    });
  }, [allItems, pars, search, catFilter, activeOnly, vendorById]);

  const update = (itemId, patch) => {
    setPars(prev => ({ ...prev, [itemId]: { ...(prev[itemId] || { active: true, max: 1, threshold: null }), ...patch } }));
  };

  const catCounts = useMemoPS(() => {
    const m = { all: allItems.length };
    allCategories.forEach(c => m[c.id] = 0);
    allItems.forEach(i => { if (m.hasOwnProperty(i.categoryId)) m[i.categoryId] += 1; });
    return m;
  }, [allItems, allCategories]);

  // Bulk actions
  const setAllActive = (val) => {
    setPars(prev => {
      const next = { ...prev };
      filtered.forEach(item => {
        next[item.id] = { ...(next[item.id] || { max: 1, threshold: null }), active: val };
      });
      return next;
    });
  };

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5, marginBottom: 14 }}>
        Configure which inventory items appear on truck-order count sheets and what their target levels are.
        <span style={{ color: 'var(--fg-3)' }}> Threshold is optional — when set, an order only triggers if on-hand ≤ threshold.</span>
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
        <div style={{
          flex: '0 0 auto', width: 280,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 12px',
          background: 'var(--bg-sunken)',
          borderRadius: 8,
        }}>
          <PIcon name="search" size={14} color="var(--fg-3)" />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search items"
            style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 13 }} />
        </div>
        <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--fg-2)', cursor: 'pointer' }}>
          <input type="checkbox" checked={activeOnly} onChange={e => setActiveOnly(e.target.checked)} />
          Active only
        </label>
        <div style={{ flex: 1 }} />
        <PBtn variant="ghost" onClick={() => setAllActive(true)}>Activate all (filtered)</PBtn>
        <PBtn variant="ghost" onClick={() => setAllActive(false)}>Deactivate all (filtered)</PBtn>
      </div>

      {/* Category filter chips */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
        <FilterPill active={catFilter === 'all'} onClick={() => setCatFilter('all')} count={catCounts.all}>All</FilterPill>
        {allCategories.map(c => (
          <FilterPill key={c.id} active={catFilter === c.id} onClick={() => setCatFilter(c.id)} color={c.color} count={catCounts[c.id] || 0}>
            {c.name}
          </FilterPill>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="portal-empty">
          <div style={{ fontSize: 14, color: 'var(--fg-2)' }}>No items match.</div>
        </div>
      ) : (
        <div style={{
          background: '#FFFFFF',
          border: '1px solid var(--border-2)',
          borderRadius: 10,
          overflow: 'hidden',
        }}>
          <table style={{ borderCollapse: 'collapse', width: '100%' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border-2)', background: '#FAFAF9' }}>
                <th style={parTh}>Active</th>
                <th style={parTh}>Item</th>
                <th style={parTh}>Category</th>
                <th style={{ ...parTh, textAlign: 'right' }}>Threshold</th>
                <th style={{ ...parTh, textAlign: 'right' }}>Max</th>
                <th style={parTh}>Rule preview</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(item => {
                const par = pars[item.id] || { active: false, max: 1, threshold: null };
                const cat = catById[item.categoryId];
                const isActive = par.active !== false;
                return (
                  <tr key={item.id} style={{
                    borderBottom: '1px solid var(--border-2)',
                    opacity: isActive ? 1 : 0.55,
                    transition: 'opacity 120ms',
                  }}>
                    <td style={{ padding: '12px 14px' }}>
                      <ToggleSwitch
                        checked={isActive}
                        onChange={(v) => update(item.id, { active: v })}
                      />
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)' }}>{item.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                        per <span style={{ color: 'var(--fg-2)' }}>{item.purchaseUnit}</span>
                      </div>
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      {cat ? (
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          fontSize: 11.5, color: cat.color, fontWeight: 600,
                        }}>
                          <span style={{ width: 6, height: 6, borderRadius: 999, background: cat.color }} />
                          {cat.name}
                        </span>
                      ) : <span style={{ color: 'var(--fg-3)' }}>—</span>}
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'right' }}>
                      <ParNumInput
                        value={par.threshold === null || par.threshold === undefined ? '' : par.threshold}
                        onChange={(v) => {
                          if (v === '') update(item.id, { threshold: null });
                          else update(item.id, { threshold: Number(v) });
                        }}
                        placeholder="opt."
                        disabled={!isActive}
                      />
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'right' }}>
                      <ParNumInput
                        value={par.max}
                        onChange={(v) => update(item.id, { max: Number(v) || 0 })}
                        disabled={!isActive}
                        required
                      />
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      <RulePreview par={par} item={item} active={isActive} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// Inline number cell — small, neat
const ParNumInput = ({ value, onChange, placeholder, disabled, required }) => (
  <input type="number" step="0.5" min="0"
    value={value}
    onChange={e => onChange(e.target.value)}
    placeholder={placeholder}
    disabled={disabled}
    style={{
      width: 64, height: 30,
      border: '1px solid ' + (required && (value === '' || value === null) ? '#BE123C' : 'var(--border-2)'),
      borderRadius: 6,
      padding: '0 6px',
      fontFamily: 'var(--font-num)',
      fontSize: 13, fontWeight: 600,
      textAlign: 'center',
      background: disabled ? 'var(--bg-sunken)' : '#FFFFFF',
      color: disabled ? 'var(--fg-3)' : 'var(--fg-1)',
    }}
  />
);

// Plain English: "Order if ≤ 1, up to 4 case"
const RulePreview = ({ par, item, active }) => {
  if (!active) {
    return <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>Not on count sheet</span>;
  }
  if (!par.max) {
    return <span style={{ fontSize: 11.5, color: '#BE123C' }}>Max required</span>;
  }
  const unit = item.purchaseUnit;
  if (par.threshold === null || par.threshold === undefined) {
    return (
      <span style={{ fontSize: 11.5, color: 'var(--fg-2)' }}>
        Order any time below <b style={{ fontFamily: 'var(--font-num)' }}>{par.max}</b> {unit}
      </span>
    );
  }
  return (
    <span style={{ fontSize: 11.5, color: 'var(--fg-2)' }}>
      If on-hand ≤ <b style={{ fontFamily: 'var(--font-num)' }}>{par.threshold}</b>, order up to <b style={{ fontFamily: 'var(--font-num)' }}>{par.max}</b> {unit}
    </span>
  );
};

// Toggle switch
const ToggleSwitch = ({ checked, onChange }) => (
  <button
    type="button"
    onClick={() => onChange(!checked)}
    style={{
      width: 36, height: 20,
      background: checked ? '#2D6A2A' : 'var(--border-1)',
      border: 'none', borderRadius: 999,
      cursor: 'pointer',
      position: 'relative',
      transition: 'background 160ms ease',
      padding: 0,
    }}
  >
    <span style={{
      position: 'absolute',
      top: 2, left: checked ? 18 : 2,
      width: 16, height: 16,
      background: '#FFFFFF',
      borderRadius: 999,
      boxShadow: '0 1px 2px rgba(0,0,0,0.2)',
      transition: 'left 160ms ease',
    }} />
  </button>
);

const FilterPill = ({ active, onClick, children, color, count }) => (
  <button onClick={onClick} style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: '5px 11px',
    background: active ? 'var(--fg-1)' : '#FFFFFF',
    color: active ? '#FFFFFF' : 'var(--fg-2)',
    border: '1px solid ' + (active ? 'var(--fg-1)' : 'var(--border-2)'),
    borderRadius: 999,
    fontSize: 12, fontWeight: 500,
    cursor: 'pointer',
  }}>
    {color && <span style={{ width: 7, height: 7, borderRadius: 999, background: color }} />}
    {children}
    {typeof count === 'number' && (
      <span style={{
        fontSize: 11, fontWeight: 600,
        color: active ? 'rgba(255,255,255,0.7)' : 'var(--fg-3)',
        fontFamily: 'var(--font-num)',
      }}>{count}</span>
    )}
  </button>
);

const parTh = {
  textAlign: 'left',
  padding: '10px 14px',
  fontSize: 11, fontWeight: 600, color: 'var(--fg-2)',
  textTransform: 'uppercase', letterSpacing: '0.06em',
  whiteSpace: 'nowrap',
};

Object.assign(window, { ParSettings });
