import { useState, useCallback } from "react";
import axios from "axios";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, Search } from "lucide-react";
import type { SearchProduct } from "./types";

interface QuickSearchResult {
  pid: number;
  title: string;
  sku: string;
  barcode: string;
  brand: string;
  line: string;
  regular_price: number;
  image_175: string | null;
}

export function ProductSearch({
  onSelect,
}: {
  onSelect: (product: SearchProduct) => void;
}) {
  const [searchTerm, setSearchTerm] = useState("");
  const [searchResults, setSearchResults] = useState<QuickSearchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [isLoadingProduct, setIsLoadingProduct] = useState<number | null>(null);

  const handleSearch = useCallback(async () => {
    if (!searchTerm.trim()) return;
    setIsSearching(true);
    try {
      const res = await axios.get("/api/products/search", {
        params: { q: searchTerm },
      });
      setSearchResults(res.data);
    } catch {
      toast.error("Search failed");
    } finally {
      setIsSearching(false);
    }
  }, [searchTerm]);

  const handleSelect = useCallback(
    async (product: QuickSearchResult) => {
      setIsLoadingProduct(product.pid);
      try {
        const res = await axios.get("/api/import/search-products", {
          params: { pid: product.pid },
        });
        const full = (res.data as SearchProduct[])[0];
        if (full) {
          onSelect(full);
          setSearchResults([]);
        } else {
          toast.error("Could not load full product details");
        }
      } catch {
        toast.error("Failed to load product details");
      } finally {
        setIsLoadingProduct(null);
      }
    },
    [onSelect]
  );

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">Search Products</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="flex gap-2">
          <Input
            placeholder="Search by name, SKU, UPC, brand..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
          />
          <Button onClick={handleSearch} disabled={isSearching}>
            {isSearching ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Search className="h-4 w-4" />
            )}
          </Button>
        </div>

        {searchResults.length > 0 && (
          <div className="mt-4 border rounded-md">
            <ScrollArea className="max-h-80">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>SKU</TableHead>
                    <TableHead>Brand</TableHead>
                    <TableHead>Line</TableHead>
                    <TableHead className="text-right">Price</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {searchResults.map((product) => (
                    <TableRow
                      key={product.pid}
                      className={`cursor-pointer hover:bg-muted/50 ${isLoadingProduct === product.pid ? "opacity-50" : ""}`}
                      onClick={() => !isLoadingProduct && handleSelect(product)}
                    >
                      <TableCell className="max-w-[300px] truncate">
                        {isLoadingProduct === product.pid && (
                          <Loader2 className="h-3 w-3 animate-spin inline mr-2" />
                        )}
                        {product.title}
                      </TableCell>
                      <TableCell>{product.sku}</TableCell>
                      <TableCell>{product.brand}</TableCell>
                      <TableCell>{product.line}</TableCell>
                      <TableCell className="text-right">
                        $
                        {Number(product.regular_price)?.toFixed(2) ??
                          product.regular_price}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </ScrollArea>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
