import { useState, useRef, useEffect } from "react";
import { useServerFn } from "@tanstack/react-start";
import { useMutation } from "@tanstack/react-query";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Sparkles, Send, Loader2, Bot, User as UserIcon } from "lucide-react";
import { toast } from "sonner";
import { portalQuotationAIChat } from "@/lib/quotation.functions";

type Msg = { role: "user" | "assistant"; content: string };
type ChatProduct = { id: string; name: string; name_bn: string; image_url: string; unit: string; price: number };

export function QuotationAIChat({
  open, onClose, token, customerType, onAddProduct, onSubmit,
}: {
  open: boolean;
  onClose: () => void;
  token: string;
  customerType?: string;
  onAddProduct?: (product: ChatProduct, quantity: number) => void;
  onSubmit?: () => void;
}) {
  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 isRetail = (customerType || "retail") === "retail";
  const [messages, setMessages] = useState<Msg[]>([
    { role: "assistant", content: isRetail
      ? "আসসালামু আলাইকুম! আমি আপনার AI বিক্রয় সহকারী। প্রোডাক্ট জিজ্ঞেস করুন বা বলুন \"এটা যোগ করো\" — আমি কার্টে দিয়ে দেব। প্রস্তুত হলে \"সাবমিট করো\" বললেই কোটেশন পাঠিয়ে দেব।"
      : "আসসালামু আলাইকুম! AI বিক্রয় সহকারী এখানে। প্রোডাক্ট/ডিসকাউন্ট জিজ্ঞেস করুন, বা বলুন \"এটা ৫টা যোগ করো\" / \"সাবমিট করো\" — আমি করে দেব।" },
  ]);
  const [input, setInput] = useState("");
  const scrollRef = useRef<HTMLDivElement>(null);
  const chatFn = useServerFn(portalQuotationAIChat);

  const mut = useMutation({
    mutationFn: async (next: Msg[]) => chatFn({ data: { token, messages: next } }),
    onSuccess: (res: any) => {
      setMessages((m) => [...m, { role: "assistant", content: res.reply }]);
      const acts = (res?.actions || []) as Array<
        { type: "add"; product: ChatProduct; quantity: number } | { type: "submit" }
      >;
      let shouldSubmit = false;
      for (const a of acts) {
        if (a.type === "add" && onAddProduct) {
          onAddProduct(a.product, a.quantity);
          toast.success(`যোগ হয়েছে: ${a.product.name_bn || a.product.name} × ${a.quantity}`);
        } else if (a.type === "submit") {
          shouldSubmit = true;
        }
      }
      if (shouldSubmit && onSubmit) {
        toast.success("কোটেশন সাবমিট হচ্ছে...");
        onSubmit();
      }
    },
    onError: (e: any) => {
      if (isAuthErr(e?.message)) {
        handleAuthFailure();
        return;
      }
      toast.error(e?.message || "ত্রুটি");
    },
  });

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, mut.isPending]);

  const send = () => {
    const text = input.trim();
    if (!text || mut.isPending) return;
    const next: Msg[] = [...messages, { role: "user", content: text }];
    setMessages(next);
    setInput("");
    mut.mutate(next);
  };

  const suggestions = isRetail
    ? [
        "সবচেয়ে সস্তা প্রোডাক্ট কী?",
        "স্টকে কী কী আছে?",
        "প্রোডাক্টের দাম জানতে চাই",
      ]
    : [
        "সবচেয়ে সস্তা প্রোডাক্ট কী?",
        "কোন প্রোডাক্টে ডিসকাউন্ট আছে?",
        "স্টকে কী কী আছে?",
      ];

  return (
    <Sheet open={open} onOpenChange={(o) => !o && onClose()}>
      <SheetContent side="right" className="w-full sm:max-w-md p-0 flex flex-col">
        <SheetHeader className="px-4 py-3 border-b bg-gradient-to-r from-primary/10 to-violet-500/10">
          <SheetTitle className="flex items-center gap-2 text-base">
            <Sparkles className="h-5 w-5 text-primary" />
            AI বিক্রয় সহকারী
          </SheetTitle>
          <p className="text-[11px] text-muted-foreground text-left">প্রোডাক্ট, দাম, ডিসকাউন্ট জিজ্ঞেস করুন</p>
        </SheetHeader>

        <ScrollArea className="flex-1">
          <div ref={scrollRef} className="p-3 space-y-3">
            {messages.map((m, i) => (
              <div key={i} className={`flex gap-2 ${m.role === "user" ? "justify-end" : "justify-start"}`}>
                {m.role === "assistant" && (
                  <div className="h-7 w-7 rounded-full bg-primary/15 grid place-items-center shrink-0">
                    <Bot className="h-4 w-4 text-primary" />
                  </div>
                )}
                <div className={`max-w-[80%] rounded-2xl px-3 py-2 text-sm whitespace-pre-wrap ${
                  m.role === "user" ? "bg-primary text-primary-foreground rounded-tr-sm" : "bg-muted rounded-tl-sm"
                }`}>
                  {m.content}
                </div>
                {m.role === "user" && (
                  <div className="h-7 w-7 rounded-full bg-muted grid place-items-center shrink-0">
                    <UserIcon className="h-4 w-4" />
                  </div>
                )}
              </div>
            ))}
            {mut.isPending && (
              <div className="flex gap-2 justify-start">
                <div className="h-7 w-7 rounded-full bg-primary/15 grid place-items-center shrink-0">
                  <Bot className="h-4 w-4 text-primary" />
                </div>
                <div className="bg-muted rounded-2xl rounded-tl-sm px-3 py-2 text-sm flex items-center gap-2">
                  <Loader2 className="h-3 w-3 animate-spin" /> লিখছে...
                </div>
              </div>
            )}
          </div>
        </ScrollArea>

        {messages.length <= 1 && (
          <div className="px-3 pb-2 flex flex-wrap gap-1">
            {suggestions.map((s) => (
              <button key={s} type="button" onClick={() => { setInput(s); }}
                className="text-[11px] px-2 py-1 rounded-full border bg-card hover:bg-muted">
                {s}
              </button>
            ))}
          </div>
        )}

        <div className="border-t p-3 flex gap-2">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder="আপনার প্রশ্ন লিখুন..."
            disabled={mut.isPending}
          />
          <Button onClick={send} disabled={mut.isPending || !input.trim()} size="icon">
            <Send className="h-4 w-4" />
          </Button>
        </div>
      </SheetContent>
    </Sheet>
  );
}
