"use client";

import { useState, useRef, useEffect } from "react";
import { MessageCircle, X, Send, Loader2, Bot, User, Minimize2 } from "lucide-react";
import { aiChat } from "@/lib/api";
import type { ChatMessage } from "@/lib/types";

interface DisplayMessage extends ChatMessage {
  id: string;
}

const WELCOME = "Hi! I'm your DriveHub car advisor. Ask me anything about cars — comparisons, specs, budget picks, or ownership tips for the Indian market.";

export default function AIChatAssistant() {
  const [open, setOpen] = useState(false);
  const [minimised, setMinimised] = useState(false);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [messages, setMessages] = useState<DisplayMessage[]>([
    { id: "welcome", role: "assistant", content: WELCOME },
  ]);
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef  = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (open && !minimised) {
      bottomRef.current?.scrollIntoView({ behavior: "smooth" });
      inputRef.current?.focus();
    }
  }, [messages, open, minimised]);

  useEffect(() => {
    function handleOpenAdvisor() {
      setOpen(true);
      setMinimised(false);
    }
    window.addEventListener("drivehub:open-advisor", handleOpenAdvisor);
    return () => window.removeEventListener("drivehub:open-advisor", handleOpenAdvisor);
  }, []);

  async function send() {
    const text = input.trim();
    if (!text || loading) return;

    const userMsg: DisplayMessage = { id: Date.now().toString(), role: "user", content: text };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setLoading(true);
    setError(null);

    try {
      const history: ChatMessage[] = messages
        .filter((m) => m.id !== "welcome")
        .map(({ role, content }) => ({ role, content }));
      history.push({ role: "user", content: text });

      const { reply } = await aiChat(history);
      setMessages((prev) => [
        ...prev,
        { id: Date.now().toString() + "r", role: "assistant", content: reply },
      ]);
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
        "Something went wrong. Please try again.";
      setError(msg);
      // remove the user message we optimistically added
      setMessages((prev) => prev.filter((m) => m.id !== userMsg.id));
      setInput(text);
    } finally {
      setLoading(false);
    }
  }

  function handleKey(e: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  }

  function reset() {
    setMessages([{ id: "welcome", role: "assistant", content: WELCOME }]);
    setError(null);
    setInput("");
  }

  // ── Floating button ────────────────────────────────────────────────────
  if (!open) {
    return (
      <button
        onClick={() => setOpen(true)}
        aria-label="Open car advisor"
        className="fixed right-4 sm:right-6 z-50 floater-bottom flex items-center gap-2 rounded-full bg-blue-600 px-3 sm:px-4 py-3 text-sm font-semibold text-white shadow-lg hover:bg-blue-700 transition-all hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-400"
      >
        <Bot className="h-5 w-5" />
        <span className="hidden sm:inline">Car Advisor</span>
      </button>
    );
  }

  // ── Chat window ────────────────────────────────────────────────────────
  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="DriveHub Car Advisor chat"
      className={`fixed right-3 sm:right-6 z-50 floater-bottom flex flex-col rounded-2xl bg-white shadow-2xl border border-gray-200 transition-all duration-200 ${
        minimised
          ? "h-14 w-[min(18rem,calc(100vw-1.5rem))] overflow-hidden"
          : "h-[min(520px,calc(100vh-var(--floater-bottom)-1rem))] w-[min(400px,calc(100vw-1.5rem))]"
      }`}
    >
      {/* Header */}
      <div className="flex items-center justify-between rounded-t-2xl bg-blue-600 px-4 py-3 text-white min-w-0">
        <div className="flex items-center gap-2 min-w-0">
          <Bot className="h-5 w-5 shrink-0" />
          <span className="font-semibold text-sm truncate">DriveHub Car Advisor</span>
          <span className="rounded-full bg-green-400 px-2 py-0.5 text-xs font-medium text-gray-900 shrink-0">
            Live
          </span>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={() => setMinimised((v) => !v)}
            className="rounded p-1 hover:bg-blue-700 transition-colors"
            aria-label={minimised ? "Expand chat" : "Minimise chat"}
          >
            <Minimize2 className="h-4 w-4" />
          </button>
          <button
            onClick={() => { setOpen(false); setMinimised(false); }}
            className="rounded p-1 hover:bg-blue-700 transition-colors"
            aria-label="Close chat"
          >
            <X className="h-4 w-4" />
          </button>
        </div>
      </div>

      {!minimised && (
        <>
          {/* Messages */}
          <div className="flex-1 overflow-y-auto px-3 py-3 space-y-3 bg-gray-50">
            {messages.map((msg) => (
              <div
                key={msg.id}
                className={`flex gap-2 ${msg.role === "user" ? "flex-row-reverse" : "flex-row"}`}
              >
                <div
                  className={`flex-shrink-0 h-7 w-7 rounded-full flex items-center justify-center ${
                    msg.role === "user" ? "bg-blue-600" : "bg-gray-200"
                  }`}
                >
                  {msg.role === "user" ? (
                    <User className="h-4 w-4 text-white" />
                  ) : (
                    <Bot className="h-4 w-4 text-gray-600" />
                  )}
                </div>
                <div
                  className={`max-w-[80%] rounded-2xl px-3 py-2 text-sm leading-relaxed break-words ${
                    msg.role === "user"
                      ? "bg-blue-600 text-white rounded-tr-sm"
                      : "bg-white text-gray-800 border border-gray-200 rounded-tl-sm"
                  }`}
                >
                  {msg.content}
                </div>
              </div>
            ))}

            {loading && (
              <div className="flex gap-2">
                <div className="h-7 w-7 rounded-full bg-gray-200 flex items-center justify-center flex-shrink-0">
                  <Bot className="h-4 w-4 text-gray-600" />
                </div>
                <div className="bg-white border border-gray-200 rounded-2xl rounded-tl-sm px-3 py-2 flex items-center gap-1">
                  <span className="h-1.5 w-1.5 rounded-full bg-gray-400 animate-bounce [animation-delay:0ms]" />
                  <span className="h-1.5 w-1.5 rounded-full bg-gray-400 animate-bounce [animation-delay:150ms]" />
                  <span className="h-1.5 w-1.5 rounded-full bg-gray-400 animate-bounce [animation-delay:300ms]" />
                </div>
              </div>
            )}

            {error && (
              <div className="rounded-lg bg-red-50 border border-red-200 px-3 py-2 text-xs text-red-600">
                {error}
              </div>
            )}

            <div ref={bottomRef} />
          </div>

          {/* Suggested prompts (shown only when no user messages yet) */}
          {messages.length === 1 && (
            <div className="px-3 pb-2 flex flex-wrap gap-1.5">
              {[
                "Best SUV under ₹15L",
                "Most fuel-efficient car?",
                "EV vs petrol — which to buy?",
                "7-seater recommendations",
              ].map((prompt) => (
                <button
                  key={prompt}
                  onClick={() => { setInput(prompt); inputRef.current?.focus(); }}
                  className="rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1 text-xs text-blue-700 hover:bg-blue-100 transition-colors"
                >
                  {prompt}
                </button>
              ))}
            </div>
          )}

          {/* Input */}
          <div className="border-t border-gray-200 bg-white rounded-b-2xl px-3 py-2">
            <div className="flex items-end gap-2">
              <textarea
                ref={inputRef}
                rows={1}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={handleKey}
                placeholder="Ask about any car…"
                className="flex-1 resize-none rounded-xl border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 max-h-24 bg-gray-50"
                style={{ minHeight: "38px" }}
              />
              <button
                onClick={send}
                disabled={!input.trim() || loading}
                className="flex-shrink-0 h-9 w-9 flex items-center justify-center rounded-xl bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                aria-label="Send message"
              >
                {loading ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Send className="h-4 w-4" />
                )}
              </button>
            </div>
            <div className="flex items-center justify-between mt-1.5 px-0.5">
              <p className="text-[10px] text-gray-400">Enter to send · Shift+Enter for newline</p>
              <button
                type="button"
                onClick={reset}
                aria-label="Clear chat history"
                className="text-[10px] text-gray-400 hover:text-gray-600 transition-colors"
              >
                Clear chat
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
