import { useState, useRef, useEffect } from "react";
import { Sparkles, X, Send, Wand2, Languages, ShieldCheck, MessageSquare } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

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

const QUICK = [
  {
    label: "Rewrite",
    icon: Wand2,
    prompt: "Rewrite the selected ad copy to be more compliant and engaging.",
  },
  {
    label: "Translate",
    icon: Languages,
    prompt: "Translate this message into Hausa, Yoruba, Igbo and Pidgin.",
  },
  {
    label: "Compliance",
    icon: ShieldCheck,
    prompt: "Scan this draft for INEC and NCC compliance risks.",
  },
];

export function FloatingCopilot() {
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Msg[]>([
    {
      role: "assistant",
      content: "Hey — I'm your AI Copilot. Ask me to draft, translate or audit any campaign asset.",
    },
  ]);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, open]);

  const send = (text?: string) => {
    const value = (text ?? input).trim();
    if (!value) return;
    setMessages((m) => [
      ...m,
      { role: "user", content: value },
      {
        role: "assistant",
        content:
          'Drafting a response for: "' +
          value.slice(0, 60) +
          (value.length > 60 ? "…" : "") +
          '". (Connect Lovable AI Gateway to enable live generation.)',
      },
    ]);
    setInput("");
  };

  return (
    <>
      {!open && (
        <Button
          onClick={() => setOpen(true)}
          className="fixed bottom-5 right-5 z-50 h-12 rounded-full shadow-lg gap-2 bg-gradient-to-br from-primary to-accent text-primary-foreground hover:opacity-95"
          size="lg"
        >
          <Sparkles className="h-4 w-4" />
          <span className="hidden sm:inline">AI Copilot</span>
          <Badge
            variant="secondary"
            className="h-4 px-1.5 text-[9px] bg-white/20 text-white border-0"
          >
            AI
          </Badge>
        </Button>
      )}

      <div
        className={cn(
          "fixed bottom-5 right-5 z-50 w-[calc(100vw-2.5rem)] sm:w-[400px] h-[560px] max-h-[80vh] rounded-2xl border border-border bg-card shadow-2xl flex flex-col overflow-hidden transition-all duration-200 origin-bottom-right",
          open ? "scale-100 opacity-100" : "scale-95 opacity-0 pointer-events-none",
        )}
      >
        <div className="flex items-center justify-between gap-2 px-4 py-3 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-transparent">
          <div className="flex items-center gap-2">
            <div className="h-8 w-8 rounded-lg bg-gradient-to-br from-primary to-accent flex items-center justify-center">
              <Sparkles className="h-4 w-4 text-white" />
            </div>
            <div>
              <div className="text-sm font-semibold leading-tight">AI Copilot</div>
              <div className="text-[10px] text-muted-foreground">Powered by VotersAlert AI</div>
            </div>
          </div>
          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setOpen(false)}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        <div className="flex-1 overflow-y-auto p-3 space-y-3">
          {messages.map((m, i) => (
            <div
              key={i}
              className={cn("flex", m.role === "user" ? "justify-end" : "justify-start")}
            >
              <div
                className={cn(
                  "max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-relaxed whitespace-pre-wrap",
                  m.role === "user"
                    ? "bg-primary text-primary-foreground rounded-br-sm"
                    : "bg-muted text-foreground rounded-bl-sm",
                )}
              >
                {m.content}
              </div>
            </div>
          ))}
          <div ref={bottomRef} />
        </div>

        <div className="px-3 pb-2 flex flex-wrap gap-1.5">
          {QUICK.map((q) => (
            <button
              key={q.label}
              onClick={() => send(q.prompt)}
              className="inline-flex items-center gap-1 text-[11px] rounded-full border border-border bg-background px-2.5 py-1 hover:bg-accent hover:text-accent-foreground transition-colors"
            >
              <q.icon className="h-3 w-3" /> {q.label}
            </button>
          ))}
        </div>

        <div className="border-t p-2 flex items-end gap-2">
          <Textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Ask your AI copilot…"
            className="min-h-[44px] max-h-32 resize-none text-sm"
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                send();
              }
            }}
          />
          <Button size="icon" className="h-9 w-9 shrink-0" onClick={() => send()}>
            <Send className="h-4 w-4" />
          </Button>
        </div>
        <div className="px-3 pb-2 flex items-center gap-1 text-[10px] text-muted-foreground">
          <MessageSquare className="h-3 w-3" /> Shift + Enter for newline · responses are advisory,
          review before sending
        </div>
      </div>
    </>
  );
}
