import { useState, useRef, useEffect } from 'react';

import { AddFilterMenu, FilterPill } from '@/Components/ui/filter-pill';
import { PHONE_FILTER_GRID } from '@/Components/Table';

// Filter controls for the Budget & Target (BNT) list + Approval PM queue.
// Prop contract: { filter, onChange, onReset, shown, total, options }.
//   filter  = { bnt: '', status: [], periode: [], division: [], creator: [], sales: [], company: [], principal: [] }
//   options = { STATUSES, PERIODES, DIVISIONS, PEOPLE, COMPANIES, PRINCIPALS, SALES, CREATORS }
//
// Values are whatever the option list is keyed by: NAMES on the client-side tier lists (options
// derived from the loaded rows), and FK IDS on the six server-driven queues (options come from
// the controller as {id, name}). FilterPill normalises both — see @/lib/filterOptions.mjs.
// SALES/CREATORS are separate lists on the queues, where they are two different sets of people;
// they fall back to the shared PEOPLE list everywhere else.

export function BudgetFilterBar({ filter, onChange, onReset, options = {}, trailing = null, middleActions = null, searchItems = [], searchPlaceholder = 'Search BNT No. or product...' }) {
  const set = (key, value) => onChange({ ...filter, [key]: value });
  const {
    STATUSES = [], PERIODES = [], DIVISIONS = [],
    PEOPLE = [], COMPANIES = [], PRINCIPALS = [],
    SALES = PEOPLE, CREATORS = PEOPLE,
  } = options;

  const calIcon = <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></svg>;
  const sortIcon = <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m7 15 5 5 5-5" /><path d="m7 9 5-5 5 5" /></svg>;
  const allFields = [
    { key: 'periode', label: 'Period', opts: PERIODES, icon: calIcon },
    { key: 'principal', label: 'Principal', opts: PRINCIPALS },
    { key: 'sales', label: 'Sales', opts: SALES },
    { key: 'company', label: 'Company', opts: COMPANIES },
    { key: 'division', label: 'Division', opts: DIVISIONS, icon: sortIcon },
    { key: 'creator', label: 'Creator', opts: CREATORS },
  ];
  // Core filters are always shown; the rest sit behind "+ Add filter" until added
  // (or auto-shown when they carry a value).
  const CORE = ['periode', 'principal', 'company', 'sales'];
  const coreFields = allFields.filter(f => CORE.includes(f.key));
  const extraFields = allFields.filter(f => !CORE.includes(f.key));

  const [extras, setExtras] = useState([]);
  const visibleExtras = extraFields.filter(f => extras.includes(f.key) || (filter[f.key]?.length));
  const hiddenExtras = extraFields.filter(f => !visibleExtras.some(v => v.key === f.key));

  const activeCount = Object.entries(filter).reduce(
    (n, [k, v]) => n + (k === 'bnt' ? (v ? 1 : 0) : (Array.isArray(v) && v.length ? 1 : 0)),
    0,
  );

  const reset = () => { setExtras([]); onReset(); };
  const handleRemoveExtra = (key) => {
    setExtras(e => e.filter(x => x !== key));
    set(key, []);
  };

  const [searchOpen, setSearchOpen] = useState(false);
  const searchRef = useRef(null);
  useEffect(() => {
    if (!searchOpen) return;
    const h = (e) => { if (searchRef.current && !searchRef.current.contains(e.target)) setSearchOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [searchOpen]);
  const sq = (filter.bnt || '').toLowerCase().trim();
  const searchMatches = sq
    ? searchItems.filter((it) => it.product.toLowerCase().includes(sq) || it.bntNo.toLowerCase().includes(sq)).slice(0, 8)
    : [];

  return (
    <div className={`flex flex-wrap items-center gap-2.5 ${PHONE_FILTER_GRID}`}>
      {/* Search pill + autocomplete */}
      <div ref={searchRef} className="relative min-w-[200px] max-w-[320px] flex-1 max-sm:col-span-2 max-sm:max-w-none">
        <label className="inline-flex w-full h-8 items-center gap-2 rounded-full border border-transparent bg-muted/60 px-3.5 text-muted-foreground transition-colors hover:bg-muted focus-within:border-primary/40 focus-within:bg-card">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="shrink-0"><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>
          <input
            type="search"
            value={filter.bnt}
            onChange={(e) => { set('bnt', e.target.value); setSearchOpen(true); }}
            onFocus={() => setSearchOpen(true)}
            placeholder={searchPlaceholder}
            className="min-w-0 flex-1 bg-transparent text-[12.5px] font-medium text-foreground placeholder:text-muted-foreground/70 outline-none [&::-webkit-search-cancel-button]:hidden"
          />
          {filter.bnt ? (
            <button type="button" aria-label="Clear search"
              onClick={() => { set('bnt', ''); setSearchOpen(false); }}
              className="grid size-4 shrink-0 place-items-center rounded-full bg-muted-foreground/50 text-card transition-colors hover:bg-muted-foreground">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          ) : null}
        </label>
        {searchOpen && searchMatches.length > 0 && (
          <div className="absolute left-0 top-full z-50 mt-1.5 w-full max-h-[280px] overflow-y-auto rounded-xl border border-border bg-surface shadow-modal py-1.5">
            {searchMatches.map((it) => (
              <button key={it.bntNo} type="button" onMouseDown={(e) => { e.preventDefault(); set('bnt', it.product); setSearchOpen(false); }}
                className="flex w-full flex-col items-start px-3.5 py-2 text-left hover:bg-surface-tint transition-colors">
                <span className="text-[12.5px] font-semibold text-foreground leading-tight">{it.product}</span>
                <span className="text-[11px] text-muted-foreground tabular-nums">{it.bntNo}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      {[...coreFields, ...visibleExtras].map((f) => (
        <FilterPill
          key={f.key}
          label={f.label}
          value={filter[f.key] || []}
          options={f.opts}
          onChange={(v) => set(f.key, v)}
          icon={f.icon}
          onRemove={!CORE.includes(f.key) ? () => handleRemoveExtra(f.key) : null}
        />
      ))}

      <AddFilterMenu fields={hiddenExtras} onAdd={(k) => setExtras(e => [...e, k])} />

      {middleActions}

      {activeCount > 0 && (
        <button
          onClick={reset}
          className="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full px-2.5 text-[12.5px] font-semibold text-muted-foreground transition-colors hover:bg-danger/10 hover:text-danger-text max-sm:justify-self-end"
        >
          Reset filters
        </button>
      )}

      {trailing && <div className="ml-auto flex items-center max-sm:order-last max-sm:col-span-2 max-sm:ml-0 max-sm:w-full max-sm:justify-end max-sm:border-t max-sm:border-border/60 max-sm:pt-2.5">{trailing}</div>}
    </div>
  );
}
