import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent } from "react";
import { apiFetch } from '@/utils/api';
import { useQuery } from "@tanstack/react-query";
import { Search, Loader2, PackageOpen, Copy, Check } from "lucide-react";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";
import { cn } from "@/lib/utils";

type HtsProduct = {
  pid: number;
  title: string;
  sku: string;
  brand?: string | null;
  vendor?: string | null;
  barcode?: string | null;
};

type HtsDetail = {
  hts_number: string | null;
  indent?: string | null;
  description?: string | null;
  unit_of_quantity?: string | null;
  general_rate_of_duty?: string | null;
  special_rate_of_duty?: string | null;
  column2_rate_of_duty?: string | null;
  quota_quantity?: string | null;
  additional_duties?: string | null;
};

type HtsGroup = {
  harmonized_tariff_code: string;
  product_count: number;
  products: HtsProduct[];
  hts_details?: HtsDetail[] | null;
};

type HtsLookupResponse = {
  search: string;
  total: number;
  results: HtsGroup[];
};

export default function HtsLookup() {
  const [searchTerm, setSearchTerm] = useState("");
  const [submittedTerm, setSubmittedTerm] = useState("");
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const copyTimerRef = useRef<number | null>(null);

  const {
    data,
    error,
    isFetching,
    isFetched,
    refetch,
  } = useQuery<HtsLookupResponse>({
    queryKey: ["hts-lookup", submittedTerm],
    enabled: false,
    queryFn: async () => {
      const params = new URLSearchParams({ search: submittedTerm });
      const response = await apiFetch(`/api/hts-lookup?${params.toString()}`);
      const payload = await response.json().catch(() => ({}));

      if (!response.ok) {
        const message = typeof payload.error === "string" ? payload.error : "Failed to fetch HTS data";
        throw new Error(message);
      }

      return payload as HtsLookupResponse;
    },
    staleTime: 2 * 60 * 1000,
  });

  useEffect(() => {
    if (submittedTerm) {
      void refetch();
    }
  }, [submittedTerm, refetch]);

  useEffect(() => {
    return () => {
      if (copyTimerRef.current) {
        window.clearTimeout(copyTimerRef.current);
      }
    };
  }, []);

  useEffect(() => {
    if (error instanceof Error) {
      toast.error("Search failed", { description: error.message });
    }
  }, [error]);

  const totalMatches = data?.total ?? 0;
  const groupedResults = useMemo(() => data?.results ?? [], [data]);

  const handleCopyClick = async (event: MouseEvent<HTMLButtonElement>, code: string) => {
    event.preventDefault();
    event.stopPropagation();
    const valueToCopy = code === "Unspecified" ? "" : code;

    if (!navigator?.clipboard) {
      toast.error("Clipboard unavailable", {
        description: "Your browser did not allow copying the code.",
      });
      return;
    }

    try {
      await navigator.clipboard.writeText(valueToCopy);
      if (copyTimerRef.current) {
        window.clearTimeout(copyTimerRef.current);
      }
      setCopiedCode(code);
      copyTimerRef.current = window.setTimeout(() => setCopiedCode(null), 1200);
      toast.success("Copied HTS code", {
        description: valueToCopy || "Empty code copied",
      });
    } catch (err) {
      toast.error("Copy failed", {
        description: err instanceof Error ? err.message : "Unable to copy code",
      });
    }
  };

  const handleSearch = (event?: FormEvent) => {
    event?.preventDefault();
    const trimmed = searchTerm.trim();

    if (!trimmed) {
      toast.info("Enter a search term", {
        description: "Search by title, SKU, vendor, barcode, or HTS code.",
      });
      return;
    }

    if (trimmed === submittedTerm) {
      void refetch();
    } else {
      setSubmittedTerm(trimmed);
    }
  };

  const renderSummary = () => {
    if (!isFetched || !data) return null;

    if (!groupedResults.length) {
      return (
        <Card>
          <CardContent className="py-8 text-center text-muted-foreground space-y-3">
            <PackageOpen className="mx-auto h-10 w-10" />
            <div>No products found for "{data.search}".</div>
          </CardContent>
        </Card>
      );
    }

    return (
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader>
            <CardDescription>Search term</CardDescription>
            <CardTitle className="text-lg break-all">{data.search}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader>
            <CardDescription>Matched products</CardDescription>
            <CardTitle className="text-3xl">{totalMatches}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader>
            <CardDescription>Unique HTS codes</CardDescription>
            <CardTitle className="text-3xl">{groupedResults.length}</CardTitle>
          </CardHeader>
        </Card>
      </div>
    );
  };

  return (
    <div className="p-6 space-y-6">
      <div className="space-y-2">
        <h1 className="text-3xl font-bold">HTS Lookup</h1>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Search products</CardTitle>
          <CardDescription>Search by product title, item number, company name, UPC, or HTS code.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="flex flex-col gap-3 md:flex-row md:items-center">
            <Input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="md:max-w-xl"
            />
            <div className="flex gap-2">
              <Button type="submit" disabled={isFetching}>
                {isFetching ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
                <span className="ml-2">Search</span>
              </Button>
              {isFetched && (
                <Button type="button" variant="outline" onClick={() => setSearchTerm("")} disabled={isFetching}>
                  Clear
                </Button>
              )}
            </div>
          </form>
        </CardContent>
      </Card>

      {renderSummary()}

      {groupedResults.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>HTS codes by frequency</CardTitle>
            <CardDescription>Most-used codes appear first. Expand a code to see the matching products.</CardDescription>
          </CardHeader>
          <CardContent>
            <Accordion type="single" collapsible className="w-full">
              {groupedResults.map((group) => {
                const percentage = totalMatches > 0 ? Math.round((group.product_count / totalMatches) * 100) : 0;
                const codeLabel = group.harmonized_tariff_code === "Unspecified" ? "Not set" : group.harmonized_tariff_code;
                const htsDetails = group.hts_details || [];

                return (
                  <AccordionItem key={group.harmonized_tariff_code} value={group.harmonized_tariff_code}>
                    <AccordionTrigger className="hover:no-underline">
                      <div className="flex flex-1 items-center justify-between gap-4">
                        <div className="flex-1 space-y-1">
                          <div className="flex items-center gap-2">
                            <Button
                              type="button"
                              size="icon"
                              variant={copiedCode === group.harmonized_tariff_code ? "secondary" : "ghost"}
                              aria-label={`Copy HTS code ${codeLabel}`}
                              onClick={(event) => handleCopyClick(event, group.harmonized_tariff_code)}
                              className="mr-1"
                            >
                              {copiedCode === group.harmonized_tariff_code ? (
                                <Check className="h-4 w-4 text-emerald-500" />
                              ) : (
                                <Copy className="h-4 w-4" />
                              )}
                            </Button>
                            <Badge variant={group.harmonized_tariff_code === "Unspecified" ? "secondary" : "outline"}>
                              {codeLabel}
                            </Badge>
                            <span className="text-sm text-muted-foreground">
                              {group.product_count} product{group.product_count === 1 ? "" : "s"}
                            </span>
                          </div>
                          {htsDetails.length > 0 ? (
                            <div className="flex flex-col gap-1 text-xs text-muted-foreground">
                              {htsDetails.map((detail, idx) => (
                                <div
                                  key={`${detail.hts_number || "unknown"}-${idx}`}
                                  className="flex items-center gap-2"
                                  style={{ paddingLeft: Math.max(0, (Number(detail.indent) || 0) * 10) }}
                                >
                                  <Badge variant="outline" className="bg-muted/60">
                                    {detail.hts_number || "—"}
                                  </Badge>
                                  <span className="leading-tight">{detail.description || "No description"}</span>
                                </div>
                              ))}
                            </div>
                          ) : (
                            <div className="text-xs text-muted-foreground italic">No HTS reference found</div>
                          )}
                        </div>
                        <span className="text-xs text-muted-foreground whitespace-nowrap">{percentage}% of matches</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent>
                      <div className="rounded-md border">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead className="w-[45%]">Product</TableHead>
                              <TableHead>SKU</TableHead>
                              <TableHead>Brand</TableHead>
                              <TableHead>Vendor</TableHead>
                              <TableHead>Barcode</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {group.products.map((product) => (
                              <TableRow key={product.pid}>
                                <TableCell>
                                  <a
                                    href={`https://backend.acherryontop.com/product/${product.pid}`}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="font-medium text-primary hover:underline"
                                  >
                                    {product.title}
                                  </a>
                                </TableCell>
                                <TableCell className="whitespace-nowrap">{product.sku}</TableCell>
                                <TableCell>{product.brand || "—"}</TableCell>
                                <TableCell>{product.vendor || "—"}</TableCell>
                                <TableCell className={cn("text-muted-foreground", !product.barcode && "italic")}>
                                  {product.barcode || "—"}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </AccordionContent>
                  </AccordionItem>
                );
              })}
            </Accordion>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
