"use client";

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

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

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

  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);
  }, []);

  function update<K extends keyof LoadFilters>(key: K, nextValue: LoadFilters[K]) {
    const next = { ...local, [key]: nextValue };
    setLocal(next);
  }

  const summary = [
    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="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div className="text-sm font-semibold text-gray-900">Keyboard-first filtering</div>
          <div className="text-xs text-gray-500">Press / or Ctrl/Cmd+K to jump to search, Enter to apply, and Esc to clear the search field.</div>
        </div>
        <div className="rounded-full bg-gray-100 px-3 py-1 text-[11px] font-medium text-gray-600">/ focus search · Enter apply</div>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
        <input
          ref={searchRef}
          value={local.search ?? ""}
          onChange={(e) => update("search", e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter") onChange(local);
            if (e.key === "Escape") update("search", undefined);
          }}
          placeholder="Search loads, route, broker, ref #"
          className="rounded-xl border px-3 py-2 text-sm"
        />

        <select
          value={local.status ?? ""}
          onChange={(e) => update("status", e.target.value || undefined)}
          className="rounded-xl border 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 in 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={Boolean(local.unassigned)} onChange={(e) => update("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={Boolean(local.uninvoiced)} onChange={(e) => update("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={Boolean(local.unpaid)} onChange={(e) => update("unpaid", e.target.checked || undefined)} />
          Awaiting payment
        </label>
      </div>

      <div className="mt-3 flex flex-wrap gap-2">
        <button type="button" onClick={() => onChange(local)} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium hover:bg-gray-50">
          Apply Filters
        </button>

        <button
          type="button"
          onClick={() => {
            const cleared: LoadFilters = {};
            setLocal(cleared);
            onChange(cleared);
          }}
          className="rounded-xl border bg-white px-4 py-2 text-sm font-medium hover:bg-gray-50"
        >
          Reset
        </button>
      </div>

      <div className="mt-3 rounded-xl border border-dashed bg-gray-50 px-3 py-3 text-xs text-gray-600">
        {summary.length ? (
          <div className="flex flex-wrap gap-2">
            {summary.map((item) => (
              <span key={item} className="rounded-full bg-white px-2.5 py-1 font-medium text-gray-700">{item}</span>
            ))}
          </div>
        ) : (
          <div>High-frequency workflow polish: press / or Ctrl/Cmd+K to focus search, then Enter to apply immediately.</div>
        )}
      </div>
    </div>
  );
}
