import { useMemo, useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useLang } from "@/lib/i18n";
import { CROPS, NEWS } from "@/data/site";
import { VARIETIES, cropLabel } from "@/data/varieties";

type Hit = { label: string; sub: string; to: string };

const BASE: Hit[] = [
  { label: "Seed Variety Finder", sub: "Tool", to: "/variety-finder" },
  { label: "El Niño Advisory", sub: "Advisory hub", to: "/el-nino" },
  { label: "Sustainability & ESG", sub: "Page", to: "/sustainability" },
  { label: "Innovations & R&D", sub: "Page", to: "/innovations" },
  { label: "Investor Relations", sub: "Page", to: "/investors" },
  { label: "About Seed Co Group", sub: "Page", to: "/about" },
  { label: "Our Countries", sub: "Page", to: "/countries" },
  { label: "Contact Us", sub: "Page", to: "/contact" },
  ...CROPS.map((c) => ({ label: c.name, sub: "Crop", to: c.slug === "maize" ? "/products/maize" : "/products" })),
  ...VARIETIES.map((v) => ({ label: v.name, sub: `${cropLabel(v.crop)} variety`, to: "/variety-finder" })),
  ...NEWS.map((n) => ({ label: n.title, sub: n.category, to: `/media/${n.slug}` })),
];

export function SiteSearch({ className }: { className?: string }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const navigate = useNavigate();
  const { t } = useLang();

  const hits = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return BASE.slice(0, 8);
    return BASE.filter((h) => `${h.label} ${h.sub}`.toLowerCase().includes(term)).slice(0, 10);
  }, [q]);

  return (
    <>
      <Button
        variant="ghost"
        size="icon"
        aria-label={t("search")}
        onClick={() => setOpen(true)}
        className={className ?? "text-foreground hover:bg-black/5 hover:text-foreground dark:text-white dark:hover:bg-white/10"}
      >
        <Search aria-hidden="true" />
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Search seedcogroup.com</DialogTitle>
            <DialogDescription>Find crops, varieties, reports and news.</DialogDescription>
          </DialogHeader>
          <Label htmlFor="site-search-input" className="sr-only">
            Search term
          </Label>
          <Input
            id="site-search-input"
            autoFocus
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Try “drought tolerant maize”"
          />
          <p className="sr-only" role="status" aria-live="polite">
            {hits.length} results
          </p>
          <ul className="max-h-72 space-y-1 overflow-y-auto">
            {hits.map((h) => (
              <li key={`${h.label}-${h.to}`}>
                <button
                  type="button"
                  onClick={() => {
                    setOpen(false);
                    navigate({ to: h.to });
                  }}
                  className="flex w-full items-center justify-between gap-3 rounded-md px-3 py-2 text-left text-sm hover:bg-secondary"
                >
                  <span className="font-medium">{h.label}</span>
                  <span className="shrink-0 text-xs text-muted-foreground">{h.sub}</span>
                </button>
              </li>
            ))}
            {hits.length === 0 && <li className="px-3 py-6 text-sm text-muted-foreground">No matches found.</li>}
          </ul>
        </DialogContent>
      </Dialog>
    </>
  );
}
