import { useState, useRef, useEffect } from "react";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport, type UIMessage } from "ai";
import { Bot, Send, X, Sparkles, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import ReactMarkdown from "react-markdown";
import { MermaidBlock } from "./mermaid-block";

const transport = new DefaultChatTransport({ api: "/api/chat" });

const SUGGESTIONS = [
  "আমি stock কোথায় পাবো?",
  "নতুন ক্রয় কিভাবে করব?",
  "বিক্রয়ের flow chart দেখাও",
  "আজকের লাভ কোথায় দেখব?",
];

function renderText(parts: UIMessage["parts"]) {
  return parts.map((p, i) => (p.type === "text" ? <span key={i}>{p.text}</span> : null));
}

function getText(parts: UIMessage["parts"]) {
  return parts.map((p) => (p.type === "text" ? p.text : "")).join("");
}

export function AIAssistant() {
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState("");
  const { messages, sendMessage, status } = useChat({ transport });
  const scrollRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => { scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" }); }, [messages, status]);
  useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 100); }, [open]);

  const send = (text: string) => {
    const t = text.trim(); if (!t) return;
    sendMessage({ text: t });
    setInput("");
  };

  const busy = status === "submitted" || status === "streaming";

  return (
    <>
      {!open && (
        <button
          onClick={() => setOpen(true)}
          className="fixed bottom-20 lg:bottom-6 right-4 z-40 size-14 rounded-full gradient-primary text-white shadow-elegant grid place-items-center hover:scale-110 transition-transform animate-fade-in"
          title="AI Assistant"
          aria-label="AI Assistant"
        >
          <Sparkles className="size-6" />
        </button>
      )}

      {open && (
        <div className="fixed inset-0 z-50 bg-black/40 lg:bg-transparent lg:inset-auto lg:bottom-6 lg:right-6 lg:w-[420px] lg:h-[640px] flex" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
          <div className="m-auto lg:m-0 w-full max-w-md lg:max-w-none lg:w-full lg:h-full h-[88vh] bg-card rounded-2xl shadow-elegant flex flex-col overflow-hidden border animate-fade-in">
            <div className="gradient-primary text-white px-4 py-3 flex items-center gap-2">
              <div className="size-9 rounded-xl bg-white/20 grid place-items-center"><Bot className="size-5" /></div>
              <div className="flex-1 min-w-0">
                <div className="font-bold">Helpgate AI সহকারী</div>
                <div className="text-xs opacity-80">যেকোনো প্রশ্ন করো</div>
              </div>
              <button onClick={() => setOpen(false)} className="size-8 rounded-lg hover:bg-white/20 grid place-items-center"><X className="size-5" /></button>
            </div>

            <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
              {messages.length === 0 && (
                <div className="space-y-3">
                  <div className="text-center text-sm text-muted-foreground">
                    👋 আমি Helpgate Inventory এর সহকারী। অ্যাপের যেকোনো কাজ বা পেজ সম্পর্কে জিজ্ঞাসা করুন।
                  </div>
                  <div className="grid gap-2">
                    {SUGGESTIONS.map((s) => (
                      <button key={s} onClick={() => send(s)} className="text-left text-sm px-3 py-2 rounded-lg border hover:bg-muted transition">
                        {s}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {messages.map((m) => (
                <div key={m.id} className={m.role === "user" ? "flex justify-end" : ""}>
                  {m.role === "user" ? (
                    <div className="bg-primary text-primary-foreground rounded-2xl rounded-tr-sm px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap">
                      {renderText(m.parts)}
                    </div>
                  ) : (
                    <div className="flex gap-2 max-w-full">
                      <div className="size-7 shrink-0 rounded-lg gradient-primary text-white grid place-items-center"><Bot className="size-4" /></div>
                      <div className="text-sm min-w-0 flex-1 prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-ul:my-1 prose-ol:my-1 prose-headings:my-2 prose-headings:font-bold">
                        <ReactMarkdown
                          components={{
                            code({ className, children, ...props }: any) {
                              const txt = String(children).replace(/\n$/, "");
                              const lang = /language-(\w+)/.exec(className || "")?.[1];
                              if (lang === "mermaid") return <MermaidBlock code={txt} />;
                              if (!className) return <code className="bg-muted px-1 py-0.5 rounded text-xs" {...props}>{children}</code>;
                              return <pre className="bg-muted p-2 rounded text-xs overflow-x-auto"><code {...props}>{children}</code></pre>;
                            },
                            a: ({ href, children }) => <a href={href} className="text-primary underline">{children}</a>,
                          }}
                        >{getText(m.parts)}</ReactMarkdown>
                      </div>
                    </div>
                  )}
                </div>
              ))}

              {status === "submitted" && (
                <div className="flex gap-2 items-center text-sm text-muted-foreground">
                  <div className="size-7 rounded-lg gradient-primary text-white grid place-items-center"><Bot className="size-4" /></div>
                  <Loader2 className="size-4 animate-spin" /> ভাবছি...
                </div>
              )}
            </div>

            <form
              onSubmit={(e) => { e.preventDefault(); send(input); }}
              className="border-t p-3 flex gap-2 items-end"
            >
              <textarea
                ref={inputRef}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(input); } }}
                rows={1}
                placeholder="প্রশ্ন লিখুন..."
                className="flex-1 resize-none rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary max-h-32"
                disabled={busy}
              />
              <Button type="submit" size="icon" disabled={busy || !input.trim()} className="gradient-primary text-white shrink-0">
                <Send className="size-4" />
              </Button>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
