"use client";

import { useEffect, useState, useTransition } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Search, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const STATUS_OPTIONS = [
  { value: "all", label: "Tüm durumlar" },
  { value: "pending", label: "Bekliyor" },
  { value: "in_progress", label: "İşlemde" },
  { value: "sent", label: "Gönderildi" },
  { value: "delivered", label: "Teslim alındı" },
  { value: "cancelled", label: "İptal" },
];

const LOCATION_OPTIONS = [
  { value: "all", label: "Her yerde" },
  { value: "at_lab", label: "Laboratuvarda" },
  { value: "at_clinic", label: "Klinikte" },
];

export function JobsFilterBar() {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const [, startTransition] = useTransition();

  const [q, setQ] = useState(params.get("q") ?? "");
  const status = params.get("status") ?? "all";
  const location = params.get("location") ?? "all";

  // Debounce text input so we don't refetch on every keystroke.
  useEffect(() => {
    const current = params.get("q") ?? "";
    if (current === q) return;
    const t = setTimeout(() => commit({ q }), 250);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q]);

  function commit(patch: Record<string, string | undefined>) {
    const next = new URLSearchParams(params.toString());
    for (const [key, value] of Object.entries(patch)) {
      if (!value || value === "all") next.delete(key);
      else next.set(key, value);
    }
    startTransition(() => {
      router.replace(`${pathname}?${next.toString()}`);
    });
  }

  const isFiltering =
    q.trim() !== "" || status !== "all" || location !== "all";

  return (
    <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_180px_180px_auto]">
      <div className="relative">
        <Search className="text-muted-foreground absolute left-3 top-1/2 size-4 -translate-y-1/2" />
        <Input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Hasta kodu veya karşı taraf ara..."
          className="pl-9"
        />
      </div>
      <Select value={status} onValueChange={(v) => commit({ status: v })}>
        <SelectTrigger>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {STATUS_OPTIONS.map((o) => (
            <SelectItem key={o.value} value={o.value}>
              {o.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Select value={location} onValueChange={(v) => commit({ location: v })}>
        <SelectTrigger>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {LOCATION_OPTIONS.map((o) => (
            <SelectItem key={o.value} value={o.value}>
              {o.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      {isFiltering && (
        <Button
          variant="outline"
          onClick={() => {
            setQ("");
            commit({ q: undefined, status: undefined, location: undefined });
          }}
        >
          <X className="size-4" />
          Temizle
        </Button>
      )}
    </div>
  );
}
