/**
 * OldBillSearch — Vyapar-style inline "search old bill by number" widget that
 * sits in the New Invoice header. User types a partial invoice number, sees
 * matching past invoices, and clicks one to open it (View / Edit / Print).
 *
 * Uses GET /api/invoices?company_id=…&q=… (server-side full-text search).
 */
import React, { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, Loader2, FileText, Eye, Edit3, Printer } from "lucide-react";
import { api } from "@/lib/api";
import { formatINR } from "@/lib/format";

const TYPE_TO_PATH = {
    sale: "/sales", purchase: "/purchases", quotation: "/quotations",
    challan: "/sales", sale_order: "/sale-orders", proforma: "/proforma",
    credit_note: "/credit-notes", debit_note: "/debit-notes",
};

export function OldBillSearch({ companyId, type = "sale" }) {
    const [open, setOpen] = useState(false);
    const [q, setQ] = useState("");
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const timerRef = useRef(null);

    // Debounced server-side search
    useEffect(() => {
        if (!open || !companyId) return;
        if (!q.trim()) {
            setResults([]);
            return;
        }
        if (timerRef.current) clearTimeout(timerRef.current);
        timerRef.current = setTimeout(async () => {
            setLoading(true);
            try {
                const { data } = await api.get("/invoices", {
                    params: { company_id: companyId, type, q: q.trim() },
                });
                setResults(Array.isArray(data) ? data.slice(0, 20) : []);
            } catch (e) {
                setResults([]);
            } finally {
                setLoading(false);
            }
        }, 250);
        return () => { if (timerRef.current) clearTimeout(timerRef.current); };
    }, [q, companyId, type, open]);

    const goto = (inv, action = "view") => {
        const base = TYPE_TO_PATH[inv.type || type] || "/sales";
        if (action === "edit") navigate(`${base}/${inv.id}/edit`);
        else if (action === "print") navigate(`${base}/${inv.id}?action=print`);
        else navigate(`${base}/${inv.id}`);
        setOpen(false);
        setQ("");
    };

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button
                    size="sm"
                    variant="outline"
                    className="gap-1.5"
                    data-testid="old-bill-search-trigger"
                    title="Search a past invoice by number"
                >
                    <Search className="h-3.5 w-3.5" />
                    <span className="hidden sm:inline">Search Old Bill</span>
                </Button>
            </PopoverTrigger>
            <PopoverContent className="p-0 w-[480px]" align="end">
                <div className="p-2 border-b">
                    <Input
                        autoFocus
                        placeholder="Type bill number e.g. RM/26-27/0001"
                        value={q}
                        onChange={(e) => setQ(e.target.value)}
                        className="h-9 font-mono"
                        data-testid="old-bill-search-input"
                    />
                </div>
                <div className="max-h-80 overflow-y-auto">
                    {loading && (
                        <div className="flex items-center justify-center py-6 text-muted-foreground">
                            <Loader2 className="h-4 w-4 animate-spin" />
                        </div>
                    )}
                    {!loading && q.trim() && results.length === 0 && (
                        <div className="px-3 py-6 text-center text-xs text-muted-foreground" data-testid="old-bill-no-results">
                            No bill found for &ldquo;{q.trim()}&rdquo;.
                        </div>
                    )}
                    {!loading && !q.trim() && (
                        <div className="px-3 py-6 text-center text-xs text-muted-foreground">
                            Start typing to search past invoices.
                        </div>
                    )}
                    {!loading && results.map((inv) => (
                        <div
                            key={inv.id}
                            className="px-3 py-2 border-b last:border-0 hover:bg-muted/40 flex items-center gap-2"
                            data-testid={`old-bill-result-${inv.id}`}
                        >
                            <FileText className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
                            <div className="flex-1 min-w-0 cursor-pointer" onClick={() => goto(inv, "view")}>
                                <div className="text-sm font-medium font-mono truncate">{inv.invoice_no || inv.id}</div>
                                <div className="text-[11px] text-muted-foreground truncate">
                                    {inv.party_name || "Walk-in"} · {inv.invoice_date} · {formatINR(inv.total)}
                                </div>
                            </div>
                            <div className="flex items-center gap-0.5 flex-shrink-0">
                                <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => goto(inv, "view")} title="View">
                                    <Eye className="h-3.5 w-3.5" />
                                </Button>
                                <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => goto(inv, "edit")} title="Edit">
                                    <Edit3 className="h-3.5 w-3.5" />
                                </Button>
                                <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => goto(inv, "print")} title="Print">
                                    <Printer className="h-3.5 w-3.5" />
                                </Button>
                            </div>
                        </div>
                    ))}
                </div>
            </PopoverContent>
        </Popover>
    );
}
