"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import type { LoadFilters } from "@/types";

type DispatchPreset = {
  key: string;
  label: string;
  filters: LoadFilters;
};

const PRESETS: DispatchPreset[] = [
  { key: "all", label: "All Loads", filters: {} },
  { key: "unassigned", label: "Unassigned", filters: { unassigned: true } },
  { key: "pickup_today", label: "Pickup Today", filters: { status: "AVAILABLE" } },
  { key: "in_transit", label: "In Transit", filters: { status: "IN_TRANSIT" } },
  { key: "delivered", label: "Delivered Awaiting Invoice", filters: { uninvoiced: true } },
  { key: "collections", label: "Collections", filters: { status: "INVOICED", unpaid: true } },
];

function sameFilters(a: LoadFilters, b: LoadFilters) {
  return JSON.stringify(a) === JSON.stringify(b);
}

export function DispatchFiltersBar({ filters, onApply }: { filters: LoadFilters; onApply: (next: LoadFilters) => void; }) {
  const [local, setLocal] = useState<LoadFilters>(filters);
  const searchRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    setLocal(filters);
  }, [filters]);

  useEffect(() => {
    function handleShortcut(event: KeyboardEvent) {
      const target = event.target as HTMLElement | null;
      const typing = target && ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
      if ((event.key === "/" || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k")) && !typing) {
        event.preventDefault();
        searchRef.current?.focus();
        searchRef.current?.select();
      }
    }
    window.addEventListener("keydown", handleShortcut);
    return () => window.removeEventListener("keydown", handleShortcut);
  }, []);

  const activePreset = useMemo(() => PRESETS.find((preset) => sameFilters(preset.filters, filters))?.key ?? null, [filters]);

  function applyPreset(preset: DispatchPreset) {
    setLocal(preset.filters);
    onApply(preset.filters);
  }

  function apply() { onApply(local); }
  function clear() { const cleared = {} as LoadFilters; setLocal(cleared); onApply(cleared); }

  const activeSummary = [
    local.search ? `Search: ${local.search}` : null,
    local.status ? `Status: ${String(local.status).replaceAll("_", " ")}` : null,
    local.unassigned ? "Unassigned only" : null,
    local.uninvoiced ? "Awaiting invoice" : null,
    local.unpaid ? "Awaiting payment" : null,
  ].filter(Boolean) as string[];

  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="space-y-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-gray-900">Saved dispatch views</div>
            <div className="text-xs text-gray-500">Jump into the most common queues first, then refine only if needed. Press / or Ctrl/Cmd+K to jump into search instantly.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            {PRESETS.map((preset) => (
              <button key={preset.key} type="button" onClick={() => applyPreset(preset)} className={`rounded-xl px-3 py-2 text-sm font-medium ${activePreset === preset.key ? "bg-black text-white" : "border bg-white text-gray-700"}`}>
                {preset.label}
              </button>
            ))}
          </div>
        </div>

        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
          <input
            ref={searchRef}
            value={local.search ?? ""}
            onChange={(e) => setLocal((current) => ({ ...current, search: e.target.value }))}
            onKeyDown={(e) => {
              if (e.key === "Enter") apply();
              if (e.key === "Escape") setLocal((current) => ({ ...current, search: undefined }));
            }}
            placeholder="Search reference, route, broker..."
            className="rounded-xl border px-3 py-2 text-sm"
          />
          <select value={local.status ?? ""} onChange={(e) => setLocal((current) => ({ ...current, status: e.target.value || undefined }))} className="rounded-xl border bg-white px-3 py-2 text-sm">
            <option value="">All statuses</option><option value="DRAFT">Draft</option><option value="AVAILABLE">Available</option><option value="ASSIGNED">Assigned</option><option value="IN_TRANSIT">In Transit</option><option value="DELIVERED">Delivered</option><option value="INVOICED">Invoiced</option><option value="PAID_FULL">Paid Full</option><option value="CANCELLED">Cancelled</option>
          </select>
          <label className="flex items-center gap-2 rounded-xl border px-3 py-2 text-sm"><input type="checkbox" checked={!!local.unassigned} onChange={(e) => setLocal((current) => ({ ...current, unassigned: e.target.checked || undefined }))} />Unassigned only</label>
          <label className="flex items-center gap-2 rounded-xl border px-3 py-2 text-sm"><input type="checkbox" checked={!!local.uninvoiced} onChange={(e) => setLocal((current) => ({ ...current, uninvoiced: e.target.checked || undefined }))} />Awaiting invoice</label>
          <label className="flex items-center gap-2 rounded-xl border px-3 py-2 text-sm"><input type="checkbox" checked={!!local.unpaid} onChange={(e) => setLocal((current) => ({ ...current, unpaid: e.target.checked || undefined }))} />Awaiting payment</label>
          <div className="grid grid-cols-2 gap-2 sm:flex sm:gap-2 xl:grid xl:grid-cols-2">
            <button type="button" onClick={apply} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white">Apply</button>
            <button type="button" onClick={clear} className="rounded-xl border px-4 py-2 text-sm font-medium">Reset</button>
          </div>
        </div>

        <div className="flex flex-col gap-2 rounded-xl border border-dashed bg-gray-50 px-3 py-3 text-xs text-gray-600 lg:flex-row lg:items-center lg:justify-between">
          <div className="font-medium text-gray-700">Keyboard-first filtering</div>
          <div className="flex flex-wrap gap-2">
            {activeSummary.length ? activeSummary.map((item) => (<span key={item} className="rounded-full bg-white px-2.5 py-1 font-medium text-gray-700">{item}</span>)) : <span className="text-gray-500">No active filters. Press / or Ctrl/Cmd+K to focus search, then Enter to apply instantly.</span>}
          </div>
        </div>
      </div>
    </div>
  );
}
