import { useState, useRef, useEffect } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Send, LifeBuoy, Bot, User as UserIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { askAiSupport, createSupportTicket } from "@/lib/support.functions";
import { getPublicSettings } from "@/lib/public-settings.functions";

type Msg = { role: "user" | "assistant"; content: string };

const STORAGE_KEY = "billsline:ai-support-chat";

/**
 * Grounded AI support chat. Rendered inline inside the Support / Contact page —
 * deliberately NOT a floating button, so it never covers app controls.
 */
export function SupportChat({ className }: { className?: string }) {
  const fetchPublic = useServerFn(getPublicSettings);
  const ask = useServerFn(askAiSupport);
  const ticket = useServerFn(createSupportTicket);
  const { data: settings } = useQuery({
    queryKey: ["public-settings"],
    queryFn: () => fetchPublic(),
    staleTime: 60_000,
  });
  const enabled = settings?.ai_support_enabled !== false;

  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Msg[]>(() => {
    if (typeof window === "undefined") return [];
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]") as Msg[]; } catch { return []; }
  });
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (typeof window !== "undefined") localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
    endRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  }, [messages]);

  const send = useMutation({
    mutationFn: async (text: string) => {
      const next: Msg[] = [...messages, { role: "user", content: text }];
      setMessages(next);
      return ask({ data: { messages: next.map(({ role, content }) => ({ role, content })) } });
    },
    onSuccess: (r) => setMessages((m) => [...m, { role: "assistant", content: r.text }]),
    onError: (e: Error) => setMessages((m) => [...m, { role: "assistant", content: e.message }]),
  });

  const escalate = useMutation({
    mutationFn: async () => {
      const lastUser = [...messages].reverse().find((m) => m.role === "user")?.content;
      if (!lastUser) throw new Error("Type a question first");
      return ticket({
        data: {
          subject: lastUser.slice(0, 120),
          message: lastUser,
          transcript: messages.slice(-20),
        },
      });
    },
    onSuccess: () => toast.success("Support ticket created — our team has been notified"),
    onError: (e: Error) => toast.error(e.message),
  });

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const t = input.trim();
    if (!t || send.isPending) return;
    setInput("");
    send.mutate(t);
  };

  const wa = settings?.support_whatsapp ? `https://wa.me/${settings.support_whatsapp.replace(/\D/g, "")}` : null;

  if (!enabled) return null;

  return (
    <div className={cn("flex h-[420px] flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-card", className)}>
      <div className="flex items-center gap-2 border-b bg-gradient-primary p-3 text-primary-foreground">
        <LifeBuoy className="h-5 w-5" />
        <div className="flex-1">
          <div className="text-sm font-bold">{settings?.app_name ?? "Billsline"} AI Support</div>
          <div className="text-[10px] opacity-80">Replies in seconds · escalate to a human anytime</div>
        </div>
      </div>

      <div className="flex-1 space-y-3 overflow-y-auto p-3 text-sm">
        {messages.length === 0 && (
          <div className="rounded-xl bg-muted/50 p-3 text-xs text-muted-foreground">
            Hi! Ask me anything — wallet, data plans, cable, electricity, transfers or referrals.
          </div>
        )}
        {messages.map((m, i) => <Bubble key={i} msg={m} />)}
        {send.isPending && <Bubble msg={{ role: "assistant", content: "…" }} />}
        <div ref={endRef} />
      </div>

      <div className="border-t bg-card p-2">
        {messages.length > 0 && (
          <div className="mb-2 flex flex-wrap gap-1.5 px-1">
            <Button size="sm" variant="outline" className="h-7 text-[11px]"
              onClick={() => escalate.mutate()} disabled={escalate.isPending}>
              Create ticket
            </Button>
            {wa && (
              <a href={wa} target="_blank" rel="noopener noreferrer"
                className="inline-flex h-7 items-center rounded-md border border-border px-3 text-[11px] font-medium transition hover:bg-secondary">
                WhatsApp
              </a>
            )}
            <Button size="sm" variant="ghost" className="h-7 text-[11px] text-muted-foreground"
              onClick={() => setMessages([])}>
              Clear
            </Button>
          </div>
        )}
        <form onSubmit={onSubmit} className="flex items-center gap-2">
          <Input value={input} onChange={(e) => setInput(e.target.value)}
            placeholder="Type your question…" className="h-10" maxLength={1000} />
          <Button type="submit" size="icon" disabled={!input.trim() || send.isPending}
            className="bg-gradient-primary">
            <Send className="h-4 w-4" />
          </Button>
        </form>
      </div>
    </div>
  );
}

function Bubble({ msg }: { msg: Msg }) {
  const isUser = msg.role === "user";
  return (
    <div className={cn("flex items-start gap-2", isUser && "flex-row-reverse")}>
      <div className={cn(
        "grid h-7 w-7 shrink-0 place-items-center rounded-full text-[10px]",
        isUser ? "bg-secondary text-secondary-foreground" : "bg-gradient-primary text-primary-foreground",
      )}>
        {isUser ? <UserIcon className="h-3.5 w-3.5" /> : <Bot className="h-3.5 w-3.5" />}
      </div>
      <div className={cn(
        "max-w-[80%] whitespace-pre-wrap break-words rounded-2xl px-3 py-2 text-sm leading-snug",
        isUser ? "bg-primary text-primary-foreground" : "bg-muted text-foreground",
      )}>
        {msg.content}
      </div>
    </div>
  );
}
