import { useState, useMemo } from "react";
import { useServerFn } from "@tanstack/react-start";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { toast } from "sonner";
import { Plus, Minus, Trash2, Search, Package, Send, Save, Sparkles } from "lucide-react";
import { portalListProducts, portalCreateQuotation } from "@/lib/quotation.functions";
import { QuotationAIChat } from "./QuotationAIChat";

type CartItem = { product_id: string; name: string; name_bn: string; image_url: string; unit: string; price: number; quantity: number };

export function QuotationDialog({
  open, onClose, token, onSaved, customerType,
}: { open: boolean; onClose: () => void; token: string; onSaved: () => void | Promise<void>; customerType?: string }) {
  const isAuthErr = (msg?: string) => !!msg && /portal session expired|invalid portal session|invalid token|expired|unauthorized/i.test(msg);
  const handleAuthFailure = () => {
    if (typeof window !== "undefined") {
      localStorage.removeItem("customer_portal_token");
      localStorage.removeItem("customer_portal_customer");
      window.location.href = "/portal/login?mobile=";
    }
  };
  const [forSelf, setForSelf] = useState(true);
  const [refName, setRefName] = useState("");
  const [refMobile, setRefMobile] = useState("");
  const [notes, setNotes] = useState("");
  const [search, setSearch] = useState("");
  const [cart, setCart] = useState<CartItem[]>([]);
  const [chatOpen, setChatOpen] = useState(false);

  const listFn = useServerFn(portalListProducts);
  const createFn = useServerFn(portalCreateQuotation);

  const { data: products = [], isLoading } = useQuery({
    queryKey: ["portal-products", search],
    enabled: open,
    queryFn: () => listFn({ data: { token, search } }),
    retry: false,
  });

  const total = useMemo(() => cart.reduce((s, i) => s + i.price * i.quantity, 0), [cart]);

  const reset = () => {
    setForSelf(true); setRefName(""); setRefMobile(""); setNotes(""); setSearch(""); setCart([]);
  };

  const addToCart = (p: any, qty: number = 1) => {
    setCart((prev) => {
      const existing = prev.find((x) => x.product_id === p.id);
      if (existing) return prev.map((x) => x.product_id === p.id ? { ...x, quantity: x.quantity + qty } : x);
      return [...prev, { product_id: p.id, name: p.name, name_bn: p.name_bn, image_url: p.image_url, unit: p.unit, price: p.price, quantity: qty }];
    });
  };
  const updateQty = (pid: string, q: number) => {
    if (q <= 0) return setCart((prev) => prev.filter((x) => x.product_id !== pid));
    setCart((prev) => prev.map((x) => x.product_id === pid ? { ...x, quantity: q } : x));
  };

  const submitMut = useMutation({
    mutationFn: async (submit: boolean) => {
      if (cart.length === 0) throw new Error("কমপক্ষে একটি প্রোডাক্ট যোগ করুন");
      if (!forSelf && refMobile.trim().length < 6) throw new Error("সঠিক রেফারেল মোবাইল দিন");
      return createFn({
        data: {
          token,
          for_self: forSelf,
          referral_name: forSelf ? "" : refName.trim(),
          referral_mobile: forSelf ? "" : refMobile.trim(),
          notes: notes.trim(),
          items: cart.map((c) => ({ product_id: c.product_id, quantity: c.quantity })),
          submit,
        },
      });
    },
    onSuccess: async (_res, submit) => {
      toast.success(submit ? "কোটেশন জমা হয়েছে" : "ড্রাফট সেভ হয়েছে");
      reset();
      await onSaved();
      onClose();
    },
    onError: (e: any) => {
      if (isAuthErr(e?.message)) {
        handleAuthFailure();
        return;
      }
      toast.error(e?.message || "ব্যর্থ");
    },
  });

  return (
    <Dialog open={open} onOpenChange={(o) => !o && (reset(), onClose())}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <div className="flex items-center justify-between gap-2 pr-6">
            <DialogTitle>নতুন কোটেশন</DialogTitle>
            <Button type="button" size="sm" variant="outline" onClick={() => setChatOpen(true)}
              className="gap-1 border-primary/40 text-primary hover:bg-primary/10">
              <Sparkles className="h-4 w-4" /> AI সহকারী
            </Button>
          </div>
        </DialogHeader>
        <QuotationAIChat
          open={chatOpen}
          onClose={() => setChatOpen(false)}
          token={token}
          customerType={customerType}
          onAddProduct={(p, q) => addToCart(p, q)}
          onSubmit={() => { if (!submitMut.isPending) submitMut.mutate(true); }}
        />

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 overflow-hidden flex-1">
          {/* LEFT — product picker */}
          <div className="flex flex-col min-h-0">
            <div className="relative mb-2">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="প্রোডাক্ট খুঁজুন..." className="pl-9" />
            </div>
            <ScrollArea className="flex-1 border rounded-lg">
              <div className="p-2 space-y-1">
                {isLoading ? (
                  <p className="text-center text-xs text-muted-foreground p-4">লোড হচ্ছে...</p>
                ) : products.length === 0 ? (
                  <p className="text-center text-xs text-muted-foreground p-4">কোনো প্রোডাক্ট নেই</p>
                ) : products.map((p: any) => (
                  <button key={p.id} type="button" onClick={() => addToCart(p)}
                    className="w-full flex items-center gap-2 p-2 rounded hover:bg-muted/50 text-left">
                    <div className="h-10 w-10 rounded bg-muted shrink-0 overflow-hidden grid place-items-center">
                      {p.image_url ? <img src={p.image_url} alt="" className="h-full w-full object-cover" /> : <Package className="h-4 w-4 text-muted-foreground" />}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium truncate">{p.name_bn || p.name}</div>
                      <div className="text-[10px] text-muted-foreground">প্রতি {p.unit} · ৳{p.price}</div>
                    </div>
                    <Plus className="h-4 w-4 text-primary" />
                  </button>
                ))}
              </div>
            </ScrollArea>
          </div>

          {/* RIGHT — settings + cart */}
          <div className="flex flex-col min-h-0 gap-3">
            <div className="rounded-lg border p-3 space-y-2">
              <div className="flex gap-2">
                <button type="button" onClick={() => setForSelf(true)}
                  className={`flex-1 py-2 px-3 rounded text-xs font-semibold border ${forSelf ? "bg-primary text-primary-foreground border-primary" : "bg-card"}`}>
                  নিজের জন্য
                </button>
                <button type="button" onClick={() => setForSelf(false)}
                  className={`flex-1 py-2 px-3 rounded text-xs font-semibold border ${!forSelf ? "bg-primary text-primary-foreground border-primary" : "bg-card"}`}>
                  অন্যের জন্য (রেফারেল)
                </button>
              </div>
              {!forSelf && (
                <div className="grid grid-cols-2 gap-2 pt-1">
                  <div>
                    <Label className="text-[11px]">নাম</Label>
                    <Input value={refName} onChange={(e) => setRefName(e.target.value)} placeholder="রেফারেল ব্যক্তির নাম" />
                  </div>
                  <div>
                    <Label className="text-[11px]">মোবাইল *</Label>
                    <Input value={refMobile} onChange={(e) => setRefMobile(e.target.value)} placeholder="01XXXXXXXXX" inputMode="tel" />
                  </div>
                </div>
              )}
            </div>

            <div className="flex-1 border rounded-lg flex flex-col min-h-0">
              <div className="px-3 py-2 border-b text-xs font-semibold flex items-center justify-between">
                <span>সিলেক্টেড ({cart.length})</span>
                {cart.length > 0 && <button onClick={() => setCart([])} className="text-destructive text-[11px]">সব ক্লিয়ার</button>}
              </div>
              <ScrollArea className="flex-1">
                {cart.length === 0 ? (
                  <p className="text-center text-xs text-muted-foreground p-6">বাঁদিক থেকে প্রোডাক্ট যোগ করুন</p>
                ) : (
                  <div className="divide-y">
                    {cart.map((i) => (
                      <div key={i.product_id} className="p-2 flex items-center gap-2">
                        <div className="flex-1 min-w-0">
                          <div className="text-xs font-medium truncate">{i.name_bn || i.name}</div>
                          <div className="text-[10px] text-muted-foreground">৳{i.price} × {i.quantity} = ৳{(i.price * i.quantity).toFixed(0)}</div>
                        </div>
                        <div className="flex items-center gap-1">
                          <Button type="button" size="icon" variant="outline" className="h-7 w-7" onClick={() => updateQty(i.product_id, i.quantity - 1)}><Minus className="h-3 w-3" /></Button>
                          <Input value={i.quantity} onChange={(e) => updateQty(i.product_id, Number(e.target.value) || 0)} className="h-7 w-14 text-center text-xs" />
                          <Button type="button" size="icon" variant="outline" className="h-7 w-7" onClick={() => updateQty(i.product_id, i.quantity + 1)}><Plus className="h-3 w-3" /></Button>
                          <Button type="button" size="icon" variant="ghost" className="h-7 w-7" onClick={() => updateQty(i.product_id, 0)}><Trash2 className="h-3 w-3 text-destructive" /></Button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </ScrollArea>
              <div className="border-t px-3 py-2 flex items-center justify-between bg-muted/30">
                <span className="text-xs text-muted-foreground">মোট</span>
                <span className="font-bold text-lg">৳{total.toFixed(2)}</span>
              </div>
            </div>

            <div>
              <Label className="text-[11px]">নোট (ঐচ্ছিক)</Label>
              <Textarea rows={2} value={notes} onChange={(e) => setNotes(e.target.value)} />
            </div>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={() => { reset(); onClose(); }}>বাতিল</Button>
          <Button variant="secondary" disabled={submitMut.isPending} onClick={() => submitMut.mutate(false)}>
            <Save className="h-4 w-4 mr-1" />ড্রাফট সেভ
          </Button>
          <Button disabled={submitMut.isPending} onClick={() => submitMut.mutate(true)}>
            <Send className="h-4 w-4 mr-1" />সাবমিট করুন
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export { quotationStatusBadge } from "./quotation-status";
