import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { PageLayout } from "@/components/PageLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { Search, Eye, Link2, AlertTriangle, Check, X, Plus, Trash2, Pencil } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import {
  adminListQuotations, adminGetQuotation, adminSetQuotationStatus,
  adminSearchCustomers, adminSearchProducts, adminCreateQuotation,
  adminUpdateQuotation, adminDeleteQuotation,
} from "@/lib/quotation.functions";
import { quotationStatusBadge } from "@/components/portal/quotation-status";


export const Route = createFileRoute("/_authenticated/quotations")({
  head: () => ({ meta: [{ title: "Quotations — Niyamah ERP" }] }),
  component: QuotationsPage,
});

function QuotationsPage() {
  const qc = useQueryClient();
  const listFn = useServerFn(adminListQuotations);
  const getFn = useServerFn(adminGetQuotation);
  const setStatusFn = useServerFn(adminSetQuotationStatus);
  const deleteFn = useServerFn(adminDeleteQuotation);

  const [search, setSearch] = useState("");
  const [status, setStatus] = useState<"all" | "draft" | "submitted" | "approved" | "rejected">("all");
  const [openId, setOpenId] = useState<string | null>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);


  const { data: rawRows, isLoading } = useQuery({
    queryKey: ["admin-quotations", search],
    queryFn: () => listFn({ data: { search, status: "all" } }),
  });

  const allRows: any[] = Array.isArray(rawRows)
    ? rawRows
    : Array.isArray((rawRows as any)?.result)
      ? (rawRows as any).result
      : Array.isArray((rawRows as any)?.data)
        ? (rawRows as any).data
        : [];

  const counts = {
    all: allRows.length,
    draft: allRows.filter((r: any) => r.status === "draft").length,
    submitted: allRows.filter((r: any) => r.status === "submitted").length,
    approved: allRows.filter((r: any) => r.status === "approved").length,
    rejected: allRows.filter((r: any) => r.status === "rejected").length,
  };
  const rows = status === "all" ? allRows : allRows.filter((r: any) => r.status === status);

  const { data: detail } = useQuery({
    queryKey: ["admin-quotation", openId],
    enabled: !!openId,
    queryFn: () => getFn({ data: { id: openId! } }),
  });

  const setStatusMut = useMutation({
    mutationFn: (vars: { id: string; status: "approved" | "rejected" | "submitted" | "draft" }) => setStatusFn({ data: vars }),
    onSuccess: () => {
      toast.success("Status updated");
      qc.invalidateQueries({ queryKey: ["admin-quotations"] });
      qc.invalidateQueries({ queryKey: ["admin-quotation"] });
    },
    onError: (e: any) => toast.error(e?.message || "Failed"),
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => deleteFn({ data: { id } }),
    onSuccess: () => {
      toast.success("ডিলিট হয়েছে");
      setDeleteId(null);
      setOpenId(null);
      qc.invalidateQueries({ queryKey: ["admin-quotations"] });
    },
    onError: (e: any) => toast.error(e?.message || "ডিলিট ব্যর্থ"),
  });

  return (
    <PageLayout title="Quotations" subtitle="কাস্টমার কোটেশন রিভিউ ও অনুমোদন">
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row gap-2">
          <div className="relative flex-1">
            <Search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Quote no / referral mobile / name" className="pl-9" />
          </div>
          <Button onClick={() => setCreateOpen(true)}>
            <Plus className="h-4 w-4 mr-1" /> নতুন কোটেশন
          </Button>
        </div>


        <Tabs value={status} onValueChange={(v) => setStatus(v as any)}>
          <TabsList className="flex flex-wrap h-auto">
            <TabsTrigger value="all">সকল <span className="ml-1.5 text-[10px] opacity-70">({counts.all})</span></TabsTrigger>
            <TabsTrigger value="draft">ড্রাফট <span className="ml-1.5 text-[10px] opacity-70">({counts.draft})</span></TabsTrigger>
            <TabsTrigger value="submitted">জমা <span className="ml-1.5 text-[10px] opacity-70">({counts.submitted})</span></TabsTrigger>
            <TabsTrigger value="approved">অনুমোদিত <span className="ml-1.5 text-[10px] opacity-70">({counts.approved})</span></TabsTrigger>
            <TabsTrigger value="rejected">প্রত্যাখ্যাত <span className="ml-1.5 text-[10px] opacity-70">({counts.rejected})</span></TabsTrigger>
          </TabsList>
        </Tabs>

        <div className="rounded-xl border bg-card overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Quote#</TableHead>
                <TableHead>কাস্টমার</TableHead>
                <TableHead>রেফারেল</TableHead>
                <TableHead className="text-right">মোট</TableHead>
                <TableHead>স্ট্যাটাস</TableHead>
                <TableHead>তারিখ</TableHead>
                <TableHead className="text-right">অ্যাকশন</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow><TableCell colSpan={7} className="text-center text-muted-foreground py-8">লোড হচ্ছে...</TableCell></TableRow>
              ) : rows.length === 0 ? (
                <TableRow><TableCell colSpan={7} className="text-center text-muted-foreground py-8">কোনো কোটেশন নেই</TableCell></TableRow>
              ) : rows.map((r: any) => (
                <TableRow key={r.id}>
                  <TableCell className="font-mono text-xs">{r.quote_no}</TableCell>
                  <TableCell>
                    <div className="font-medium text-sm">{r.customer?.name_bn || r.customer?.name || "—"}</div>
                    <div className="text-[11px] text-muted-foreground font-mono">{r.customer?.mobile}</div>
                  </TableCell>
                  <TableCell>
                    {r.for_self ? (
                      <Badge variant="outline" className="text-[10px]">নিজের জন্য</Badge>
                    ) : (
                      <div>
                        <div className="text-sm">{r.referral_name || "—"}</div>
                        <div className="text-[11px] font-mono text-muted-foreground">{r.referral_mobile}</div>
                        {r.referral_customer_id ? (
                          <Badge className="mt-1 bg-green-600 text-white text-[10px] border-0"><Link2 className="h-3 w-3 mr-1" />Linked</Badge>
                        ) : (
                          <Badge variant="destructive" className="mt-1 text-[10px]"><AlertTriangle className="h-3 w-3 mr-1" />অপেক্ষমান</Badge>
                        )}
                      </div>
                    )}
                  </TableCell>
                  <TableCell className="text-right font-semibold">৳{Number(r.total_amount || 0).toLocaleString()}</TableCell>
                  <TableCell>{quotationStatusBadge(r.status)}</TableCell>
                  <TableCell className="text-xs text-muted-foreground">{new Date(r.created_at).toLocaleDateString()}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Button size="sm" variant="outline" onClick={() => setOpenId(r.id)}>
                        <Eye className="h-3.5 w-3.5" />
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => setEditId(r.id)}>
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      <Button size="sm" variant="outline" className="text-destructive hover:text-destructive" onClick={() => setDeleteId(r.id)}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      <Sheet open={!!openId} onOpenChange={(o) => !o && setOpenId(null)}>
        <SheetContent className="w-full sm:max-w-2xl overflow-y-auto">
          <SheetHeader>
            <SheetTitle>{(detail as any)?.quotation?.quote_no || "Quotation"}</SheetTitle>
          </SheetHeader>
          {detail && (
            <div className="mt-4 space-y-4">
              <div className="grid grid-cols-2 gap-3 text-sm">
                <Info label="কাস্টমার" value={(detail as any).customer?.name_bn || (detail as any).customer?.name || "—"} sub={(detail as any).customer?.mobile} />
                <Info label="স্ট্যাটাস" valueNode={quotationStatusBadge((detail as any).quotation.status)} />
                <Info label="ধরন" value={(detail as any).quotation.for_self ? "নিজের জন্য" : "রেফারেল"} />
                <Info label="মোট" value={`৳${Number((detail as any).quotation.total_amount).toFixed(2)}`} />
                {!(detail as any).quotation.for_self && (
                  <>
                    <Info label="রেফারেল নাম" value={(detail as any).quotation.referral_name || "—"} />
                    <Info
                      label="রেফারেল মোবাইল"
                      value={(detail as any).quotation.referral_mobile || "—"}
                      sub={(detail as any).referrer ? `✓ Linked: ${(detail as any).referrer.name_bn || (detail as any).referrer.name}` : "অপেক্ষমান (অটো-লিংক হবে)"}
                    />
                  </>
                )}
              </div>

              {(detail as any).quotation.notes && (
                <div className="rounded-lg border p-3 bg-muted/30">
                  <div className="text-[11px] text-muted-foreground uppercase mb-1">নোট</div>
                  <div className="text-sm">{(detail as any).quotation.notes}</div>
                </div>
              )}

              <div className="rounded-lg border overflow-hidden">
                <div className="px-3 py-2 bg-muted/50 text-xs font-semibold">প্রোডাক্ট ({(detail as any).items.length})</div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>প্রোডাক্ট</TableHead>
                      <TableHead className="text-right">পরিমাণ</TableHead>
                      <TableHead className="text-right">দাম</TableHead>
                      <TableHead className="text-right">মোট</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(detail as any).items.map((it: any) => (
                      <TableRow key={it.id}>
                        <TableCell>
                          <div className="text-sm">{it.product_name_bn || it.product_name}</div>
                        </TableCell>
                        <TableCell className="text-right">{it.quantity} {it.unit}</TableCell>
                        <TableCell className="text-right">৳{Number(it.unit_price).toFixed(2)}</TableCell>
                        <TableCell className="text-right font-semibold">৳{Number(it.line_total).toFixed(2)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {(detail as any).quotation.status === "submitted" && (
                <div className="flex gap-2 sticky bottom-0 bg-background pt-2 border-t">
                  <Button className="flex-1 bg-green-600 hover:bg-green-700" disabled={setStatusMut.isPending}
                    onClick={() => setStatusMut.mutate({ id: openId!, status: "approved" })}>
                    <Check className="h-4 w-4 mr-1" /> অনুমোদন
                  </Button>
                  <Button variant="destructive" className="flex-1" disabled={setStatusMut.isPending}
                    onClick={() => setStatusMut.mutate({ id: openId!, status: "rejected" })}>
                    <X className="h-4 w-4 mr-1" /> প্রত্যাখ্যান
                  </Button>
                </div>
              )}
            </div>
          )}
        </SheetContent>
      </Sheet>

      <CreateQuotationDialog open={createOpen} onOpenChange={setCreateOpen} onCreated={() => {
        qc.invalidateQueries({ queryKey: ["admin-quotations"] });
      }} />

      <EditQuotationDialog
        editId={editId}
        onClose={() => setEditId(null)}
        onSaved={() => {
          qc.invalidateQueries({ queryKey: ["admin-quotations"] });
          qc.invalidateQueries({ queryKey: ["admin-quotation"] });
        }}
      />

      <AlertDialog open={!!deleteId} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>কোটেশন ডিলিট করবেন?</AlertDialogTitle>
            <AlertDialogDescription>
              এই কোটেশন এবং এর সকল আইটেম স্থায়ীভাবে মুছে যাবে। এটি ফিরিয়ে আনা যাবে না।
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>বাতিল</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={deleteMut.isPending}
              onClick={() => deleteId && deleteMut.mutate(deleteId)}
            >
              {deleteMut.isPending ? "ডিলিট হচ্ছে..." : "ডিলিট করুন"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}

function CreateQuotationDialog({ open, onOpenChange, onCreated }: { open: boolean; onOpenChange: (o: boolean) => void; onCreated: () => void }) {
  const searchCustFn = useServerFn(adminSearchCustomers);
  const searchProdFn = useServerFn(adminSearchProducts);
  const createFn = useServerFn(adminCreateQuotation);

  const [custSearch, setCustSearch] = useState("");
  const [customer, setCustomer] = useState<{ id: string; name: string; name_bn?: string | null; mobile: string } | null>(null);
  const [forSelf, setForSelf] = useState(true);
  const [refName, setRefName] = useState("");
  const [refMobile, setRefMobile] = useState("");
  const [notes, setNotes] = useState("");
  const [stat, setStat] = useState<"draft" | "submitted" | "approved">("approved");

  const [prodSearch, setProdSearch] = useState("");
  const [items, setItems] = useState<Array<{ product_id: string; name: string; unit: string; price: number; quantity: number }>>([]);

  const { data: customers = [] } = useQuery({
    queryKey: ["adm-cust-search", custSearch],
    enabled: open && !customer,
    queryFn: () => searchCustFn({ data: { search: custSearch } }),
  });

  const { data: products = [] } = useQuery({
    queryKey: ["adm-prod-search", prodSearch],
    enabled: open,
    queryFn: () => searchProdFn({ data: { search: prodSearch } }),
  });

  const total = items.reduce((s, i) => s + i.price * i.quantity, 0);

  function addProduct(p: any) {
    setItems((prev) => {
      const idx = prev.findIndex((x) => x.product_id === p.id);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = { ...copy[idx], quantity: copy[idx].quantity + 1 };
        return copy;
      }
      return [...prev, { product_id: p.id, name: p.name_bn || p.name, unit: p.unit, price: p.price, quantity: 1 }];
    });
  }

  const createMut = useMutation({
    mutationFn: () => createFn({
      data: {
        customer_id: customer!.id,
        for_self: forSelf,
        referral_name: refName,
        referral_mobile: refMobile,
        items: items.map((i) => ({ product_id: i.product_id, quantity: i.quantity })),
        notes,
        status: stat,
      },
    }),
    onSuccess: (res: any) => {
      toast.success(`তৈরি হয়েছে: ${res.quote_no}`);
      onCreated();
      // reset
      setCustomer(null); setCustSearch(""); setForSelf(true); setRefName(""); setRefMobile("");
      setNotes(""); setItems([]); setProdSearch(""); setStat("approved");
      onOpenChange(false);
    },
    onError: (e: any) => toast.error(e?.message || "Failed"),
  });

  function submit() {
    if (!customer) return toast.error("কাস্টমার সিলেক্ট করুন");
    if (items.length === 0) return toast.error("কমপক্ষে একটি প্রোডাক্ট যোগ করুন");
    if (!forSelf && refMobile.trim().length < 6) return toast.error("রেফারেল মোবাইল দিন");
    createMut.mutate();
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>নতুন কোটেশন তৈরি</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Customer */}
          <div>
            <Label className="text-xs">কাস্টমার</Label>
            {customer ? (
              <div className="flex items-center justify-between rounded-md border p-2 mt-1">
                <div>
                  <div className="font-medium text-sm">{customer.name_bn || customer.name}</div>
                  <div className="text-xs text-muted-foreground font-mono">{customer.mobile}</div>
                </div>
                <Button size="sm" variant="ghost" onClick={() => setCustomer(null)}>পরিবর্তন</Button>
              </div>
            ) : (
              <div className="space-y-2 mt-1">
                <Input placeholder="নাম / মোবাইল দিয়ে খুঁজুন" value={custSearch} onChange={(e) => setCustSearch(e.target.value)} />
                <div className="max-h-40 overflow-y-auto rounded-md border">
                  {(customers as any[]).slice(0, 20).map((c: any) => (
                    <button key={c.id} type="button" className="w-full text-left px-3 py-2 hover:bg-muted text-sm border-b last:border-b-0"
                      onClick={() => setCustomer(c)}>
                      <div className="font-medium">{c.name_bn || c.name}</div>
                      <div className="text-xs text-muted-foreground font-mono">{c.mobile}</div>
                    </button>
                  ))}
                  {(customers as any[]).length === 0 && (
                    <div className="text-xs text-muted-foreground text-center py-4">কোনো কাস্টমার নেই</div>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Type */}
          <div className="grid grid-cols-2 gap-2">
            <Button variant={forSelf ? "default" : "outline"} size="sm" onClick={() => setForSelf(true)}>নিজের জন্য</Button>
            <Button variant={!forSelf ? "default" : "outline"} size="sm" onClick={() => setForSelf(false)}>রেফারেল</Button>
          </div>
          {!forSelf && (
            <div className="grid grid-cols-2 gap-2">
              <Input placeholder="রেফারেল নাম" value={refName} onChange={(e) => setRefName(e.target.value)} />
              <Input placeholder="রেফারেল মোবাইল" value={refMobile} onChange={(e) => setRefMobile(e.target.value)} />
            </div>
          )}

          {/* Products */}
          <div>
            <Label className="text-xs">প্রোডাক্ট যোগ করুন</Label>
            <Input className="mt-1" placeholder="প্রোডাক্ট খুঁজুন" value={prodSearch} onChange={(e) => setProdSearch(e.target.value)} />
            <div className="max-h-40 overflow-y-auto rounded-md border mt-2">
              {(products as any[]).slice(0, 30).map((p: any) => (
                <button key={p.id} type="button" className="w-full text-left px-3 py-2 hover:bg-muted text-sm border-b last:border-b-0 flex justify-between items-center"
                  onClick={() => addProduct(p)}>
                  <span>{p.name_bn || p.name} <span className="text-xs text-muted-foreground">/ {p.unit}</span></span>
                  <span className="text-xs font-mono">৳{p.price}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Items list */}
          {items.length > 0 && (
            <div className="rounded-md border overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>প্রোডাক্ট</TableHead>
                    <TableHead className="w-24">পরিমাণ</TableHead>
                    <TableHead className="text-right">মোট</TableHead>
                    <TableHead className="w-10"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {items.map((it, idx) => (
                    <TableRow key={it.product_id}>
                      <TableCell className="text-sm">
                        {it.name}
                        <div className="text-[11px] text-muted-foreground">৳{it.price} / {it.unit}</div>
                      </TableCell>
                      <TableCell>
                        <Input type="number" min={1} value={it.quantity}
                          onChange={(e) => {
                            const v = Math.max(1, Number(e.target.value) || 1);
                            setItems((prev) => prev.map((x, i) => i === idx ? { ...x, quantity: v } : x));
                          }}
                          className="h-8" />
                      </TableCell>
                      <TableCell className="text-right font-semibold text-sm">৳{(it.price * it.quantity).toFixed(2)}</TableCell>
                      <TableCell>
                        <Button size="icon" variant="ghost" onClick={() => setItems((prev) => prev.filter((_, i) => i !== idx))}>
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              <div className="px-3 py-2 bg-muted/40 text-right font-semibold text-sm">
                মোট: ৳{total.toFixed(2)}
              </div>
            </div>
          )}

          <div>
            <Label className="text-xs">নোট</Label>
            <Textarea className="mt-1" rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
          </div>

          <div>
            <Label className="text-xs">স্ট্যাটাস</Label>
            <Select value={stat} onValueChange={(v) => setStat(v as any)}>
              <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="draft">ড্রাফট</SelectItem>
                <SelectItem value="submitted">জমা</SelectItem>
                <SelectItem value="approved">অনুমোদিত</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>বাতিল</Button>
          <Button onClick={submit} disabled={createMut.isPending}>
            {createMut.isPending ? "তৈরি হচ্ছে..." : "তৈরি করুন"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}



function Info({ label, value, valueNode, sub }: { label: string; value?: string; valueNode?: React.ReactNode; sub?: string }) {
  return (
    <div>
      <div className="text-[11px] uppercase text-muted-foreground mb-0.5">{label}</div>
      {valueNode || <div className="font-medium text-sm">{value}</div>}
      {sub && <div className="text-[11px] text-muted-foreground mt-0.5">{sub}</div>}
    </div>
  );
}

function EditQuotationDialog({ editId, onClose, onSaved }: { editId: string | null; onClose: () => void; onSaved: () => void }) {
  const getFn = useServerFn(adminGetQuotation);
  const searchProdFn = useServerFn(adminSearchProducts);
  const updateFn = useServerFn(adminUpdateQuotation);

  const open = !!editId;
  const [forSelf, setForSelf] = useState(true);
  const [refName, setRefName] = useState("");
  const [refMobile, setRefMobile] = useState("");
  const [notes, setNotes] = useState("");
  const [stat, setStat] = useState<"draft" | "submitted" | "approved" | "rejected">("approved");
  const [items, setItems] = useState<Array<{ product_id: string; name: string; unit: string; price: number; quantity: number }>>([]);
  const [prodSearch, setProdSearch] = useState("");
  const [quoteNo, setQuoteNo] = useState("");

  const { data: detail } = useQuery({
    queryKey: ["admin-quotation-edit", editId],
    enabled: open,
    queryFn: () => getFn({ data: { id: editId! } }),
  });

  // Hydrate state when detail loads
  const [loadedId, setLoadedId] = useState<string | null>(null);
  if (detail && (detail as any).quotation?.id !== loadedId) {
    const q = (detail as any).quotation;
    const its = (detail as any).items as any[];
    setLoadedId(q.id);
    setForSelf(!!q.for_self);
    setRefName(q.referral_name || "");
    setRefMobile(q.referral_mobile || "");
    setNotes(q.notes || "");
    setStat(q.status);
    setQuoteNo(q.quote_no || "");
    setItems(its.map((it) => ({
      product_id: it.product_id,
      name: it.product_name_bn || it.product_name,
      unit: it.unit || "pcs",
      price: Number(it.unit_price || 0),
      quantity: Number(it.quantity || 0),
    })));
  }
  if (!open && loadedId) setLoadedId(null);

  const { data: products = [] } = useQuery({
    queryKey: ["adm-prod-search-edit", prodSearch],
    enabled: open,
    queryFn: () => searchProdFn({ data: { search: prodSearch } }),
  });

  const total = items.reduce((s, i) => s + i.price * i.quantity, 0);

  function addProduct(p: any) {
    setItems((prev) => {
      const idx = prev.findIndex((x) => x.product_id === p.id);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = { ...copy[idx], quantity: copy[idx].quantity + 1 };
        return copy;
      }
      return [...prev, { product_id: p.id, name: p.name_bn || p.name, unit: p.unit, price: p.price, quantity: 1 }];
    });
  }

  const updateMut = useMutation({
    mutationFn: () => updateFn({
      data: {
        id: editId!,
        for_self: forSelf,
        referral_name: refName,
        referral_mobile: refMobile,
        items: items.map((i) => ({ product_id: i.product_id, quantity: i.quantity })),
        notes,
        status: stat,
      },
    }),
    onSuccess: () => {
      toast.success("আপডেট হয়েছে");
      onSaved();
      onClose();
    },
    onError: (e: any) => toast.error(e?.message || "Failed"),
  });

  function submit() {
    if (items.length === 0) return toast.error("কমপক্ষে একটি প্রোডাক্ট লাগবে");
    if (!forSelf && refMobile.trim().length < 6) return toast.error("রেফারেল মোবাইল দিন");
    updateMut.mutate();
  }

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>কোটেশন এডিট — <span className="font-mono text-sm">{quoteNo}</span></DialogTitle>
        </DialogHeader>

        {!detail ? (
          <div className="text-center py-8 text-muted-foreground text-sm">লোড হচ্ছে...</div>
        ) : (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-2">
              <Button variant={forSelf ? "default" : "outline"} size="sm" onClick={() => setForSelf(true)}>নিজের জন্য</Button>
              <Button variant={!forSelf ? "default" : "outline"} size="sm" onClick={() => setForSelf(false)}>রেফারেল</Button>
            </div>
            {!forSelf && (
              <div className="grid grid-cols-2 gap-2">
                <Input placeholder="রেফারেল নাম" value={refName} onChange={(e) => setRefName(e.target.value)} />
                <Input placeholder="রেফারেল মোবাইল" value={refMobile} onChange={(e) => setRefMobile(e.target.value)} />
              </div>
            )}

            <div>
              <Label className="text-xs">প্রোডাক্ট যোগ করুন</Label>
              <Input className="mt-1" placeholder="প্রোডাক্ট খুঁজুন" value={prodSearch} onChange={(e) => setProdSearch(e.target.value)} />
              <div className="max-h-40 overflow-y-auto rounded-md border mt-2">
                {(products as any[]).slice(0, 30).map((p: any) => (
                  <button key={p.id} type="button" className="w-full text-left px-3 py-2 hover:bg-muted text-sm border-b last:border-b-0 flex justify-between items-center"
                    onClick={() => addProduct(p)}>
                    <span>{p.name_bn || p.name} <span className="text-xs text-muted-foreground">/ {p.unit}</span></span>
                    <span className="text-xs font-mono">৳{p.price}</span>
                  </button>
                ))}
              </div>
            </div>

            {items.length > 0 && (
              <div className="rounded-md border overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>প্রোডাক্ট</TableHead>
                      <TableHead className="w-24">পরিমাণ</TableHead>
                      <TableHead className="text-right">মোট</TableHead>
                      <TableHead className="w-10"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {items.map((it, idx) => (
                      <TableRow key={it.product_id}>
                        <TableCell className="text-sm">
                          {it.name}
                          <div className="text-[11px] text-muted-foreground">৳{it.price} / {it.unit}</div>
                        </TableCell>
                        <TableCell>
                          <Input type="number" min={1} value={it.quantity}
                            onChange={(e) => {
                              const v = Math.max(1, Number(e.target.value) || 1);
                              setItems((prev) => prev.map((x, i) => i === idx ? { ...x, quantity: v } : x));
                            }}
                            className="h-8" />
                        </TableCell>
                        <TableCell className="text-right font-semibold text-sm">৳{(it.price * it.quantity).toFixed(2)}</TableCell>
                        <TableCell>
                          <Button size="icon" variant="ghost" onClick={() => setItems((prev) => prev.filter((_, i) => i !== idx))}>
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
                <div className="px-3 py-2 bg-muted/40 text-right font-semibold text-sm">
                  মোট: ৳{total.toFixed(2)}
                </div>
              </div>
            )}

            <div>
              <Label className="text-xs">নোট</Label>
              <Textarea className="mt-1" rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
            </div>

            <div>
              <Label className="text-xs">স্ট্যাটাস</Label>
              <Select value={stat} onValueChange={(v) => setStat(v as any)}>
                <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">ড্রাফট</SelectItem>
                  <SelectItem value="submitted">জমা</SelectItem>
                  <SelectItem value="approved">অনুমোদিত</SelectItem>
                  <SelectItem value="rejected">প্রত্যাখ্যাত</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>বাতিল</Button>
          <Button onClick={submit} disabled={updateMut.isPending || !detail}>
            {updateMut.isPending ? "সেভ হচ্ছে..." : "সেভ করুন"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

