"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";

const STATUSES = [
  { value: "DRAFT", label: "Draft" },
  { value: "SUBMITTED", label: "Submitted" },
  { value: "MGR_REVIEW", label: "Pending Approval" },
  { value: "VENDOR_ID_PENDING", label: "Vendor ID Pending" },
  { value: "EDITS_REQUESTED", label: "Edits Requested" },
  { value: "MGR_APPROVED", label: "Approved" },
  { value: "SENT_FOR_PAYMENT", label: "Sent for Payment" },
  { value: "PAID_DELIVERED", label: "Paid / Delivered" },
  { value: "CLOSED", label: "Closed" },
  { value: "REJECTED", label: "Rejected" },
  { value: "CANCELLED", label: "Cancelled" },
];

interface Props {
  vessels: { id: string; name: string }[];
}

export function HistoryFilters({ vessels }: Props) {
  const router = useRouter();
  const sp = useSearchParams();

  const [dateFrom, setDateFrom] = useState(sp.get("dateFrom") ?? "");
  const [dateTo, setDateTo] = useState(sp.get("dateTo") ?? "");
  const [approvedFrom, setApprovedFrom] = useState(sp.get("approvedFrom") ?? "");
  const [approvedTo, setApprovedTo] = useState(sp.get("approvedTo") ?? "");
  const [vesselId, setVesselId] = useState(sp.get("vesselId") ?? "");
  const [statuses, setStatuses] = useState<string[]>(sp.getAll("status"));
  const [statusOpen, setStatusOpen] = useState(false);
  const statusRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (statusRef.current && !statusRef.current.contains(e.target as Node)) {
        setStatusOpen(false);
      }
    }
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  function toggleStatus(value: string) {
    setStatuses((prev) =>
      prev.includes(value) ? prev.filter((s) => s !== value) : [...prev, value]
    );
  }

  function apply() {
    const params = new URLSearchParams();
    if (dateFrom) params.set("dateFrom", dateFrom);
    if (dateTo) params.set("dateTo", dateTo);
    if (approvedFrom) params.set("approvedFrom", approvedFrom);
    if (approvedTo) params.set("approvedTo", approvedTo);
    if (vesselId) params.set("vesselId", vesselId);
    for (const s of statuses) params.append("status", s);
    router.push(`/history?${params.toString()}`);
  }

  function clear() {
    setDateFrom(""); setDateTo(""); setApprovedFrom(""); setApprovedTo(""); setVesselId(""); setStatuses([]);
    router.push("/history");
  }

  const hasFilters = dateFrom || dateTo || approvedFrom || approvedTo || vesselId || statuses.length > 0;

  const statusLabel =
    statuses.length === 0
      ? "All statuses"
      : statuses.length === 1
        ? (STATUSES.find((s) => s.value === statuses[0])?.label ?? statuses[0])
        : `${statuses.length} statuses`;

  return (
    <div className="mb-4 rounded-lg border border-neutral-200 bg-white p-4">
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div>
          <label className="block text-xs font-medium text-neutral-600 mb-1">From</label>
          <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20" />
        </div>
        <div>
          <label className="block text-xs font-medium text-neutral-600 mb-1">To</label>
          <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20" />
        </div>
        <div>
          <label className="block text-xs font-medium text-neutral-600 mb-1">Approved From</label>
          <input type="date" value={approvedFrom} onChange={(e) => setApprovedFrom(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20" />
        </div>
        <div>
          <label className="block text-xs font-medium text-neutral-600 mb-1">Approved To</label>
          <input type="date" value={approvedTo} onChange={(e) => setApprovedTo(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20" />
        </div>
        <div>
          <label className="block text-xs font-medium text-neutral-600 mb-1">Cost Centre</label>
          <select value={vesselId} onChange={(e) => setVesselId(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20">
            <option value="">All cost centres</option>
            {vessels.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
          </select>
        </div>
        <div className="relative" ref={statusRef}>
          <label className="block text-xs font-medium text-neutral-600 mb-1">Status</label>
          <button type="button" onClick={() => setStatusOpen((o) => !o)}
            className="flex w-full items-center justify-between rounded-lg border border-neutral-300 px-3 py-2 text-left text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20">
            <span className={statuses.length === 0 ? "text-neutral-500" : "text-neutral-900"}>{statusLabel}</span>
            <svg className="ml-2 h-4 w-4 shrink-0 text-neutral-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fillRule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.17l3.71-3.94a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clipRule="evenodd" />
            </svg>
          </button>
          {statusOpen && (
            <div className="absolute z-10 mt-1 max-h-64 w-full overflow-auto rounded-lg border border-neutral-200 bg-white py-1 shadow-lg">
              {STATUSES.map((s) => (
                <label key={s.value} className="flex cursor-pointer items-center gap-2 px-3 py-1.5 text-sm hover:bg-neutral-50">
                  <input type="checkbox" checked={statuses.includes(s.value)} onChange={() => toggleStatus(s.value)}
                    className="h-4 w-4 rounded border-neutral-300 text-primary-600 focus:ring-primary-500/20" />
                  <span className="text-neutral-700">{s.label}</span>
                </label>
              ))}
            </div>
          )}
        </div>
      </div>
      <div className="mt-3 flex items-center gap-2">
        <button onClick={apply}
          className="rounded-lg bg-primary-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-primary-700 transition-colors">
          Apply
        </button>
        {hasFilters && (
          <button onClick={clear}
            className="rounded-lg border border-neutral-300 bg-white px-3 py-1.5 text-sm font-medium text-neutral-600 hover:bg-neutral-50 transition-colors">
            Clear
          </button>
        )}
      </div>
    </div>
  );
}
