import { useState, useRef, useEffect } from "react";
import { cn } from "@/lib/utils";
import { XIcon, SendIcon, Loader2Icon } from "lucide-react";

type Message = {
  role: "user" | "ai";
  content: string;
};

type ChatbotPanelProps = {
  className?: string;
  variant?: "inline" | "widget";
  onClose?: () => void;
  hideHeader?: boolean;
};

const ChatbotPanel = ({ className, onClose, hideHeader = false }: ChatbotPanelProps) => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [historyCursor, setHistoryCursor] = useState<number | null>(null);
  const [isHistoryLoading, setIsHistoryLoading] = useState(false);
  const [input, setInput] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom when messages change
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  const mapHistoryToMessages = (items: any[]): Message[] => {
    return items.map((item) => ({
      role: item.is_human ? "user" : "ai",
      content: String(item.message ?? ""),
    }));
  };

  const loadHistory = async (isRefresh: boolean) => {
    if (isHistoryLoading) return;
    setIsHistoryLoading(true);

    try {
      const cursor = isRefresh ? null : historyCursor;
      const url = `/api/history/me?limit=20${cursor ? `&before_id=${cursor}` : ""}`;

      const res = await fetch(url);
      if (!res.ok) throw new Error("Failed to load history");
      const data = await res.json();

      const items: any[] = Array.isArray(data.data) ? data.data : Array.isArray(data) ? data : [];
      const nextCursor: number | null = data.next_cursor ?? null;

      if (items.length === 0) {
        if (isRefresh && messages.length === 0) {
          // No history at all -> show default greeting
          setMessages([{ role: "ai", content: "Hello! I'm CiCi. How can I help you with your notes today?" }]);
        }
        setHistoryCursor(null);
        return;
      }

      // API trả về DESC theo id, ta đảo để oldest -> newest trong batch
      const batchMessages = mapHistoryToMessages([...items].reverse());

      if (isRefresh) {
        setMessages(batchMessages);
      } else {
        // Load older: prepend vào đầu
        setMessages((prev) => [...batchMessages, ...prev]);
      }

      setHistoryCursor(nextCursor);
    } catch (error) {
      console.error("Failed to load history:", error);
      if (isRefresh && messages.length === 0) {
        setMessages([{ role: "ai", content: "Hello! I'm CiCi. How can I help you with your notes today?" }]);
      }
    } finally {
      setIsHistoryLoading(false);
    }
  };

  // Load initial history on mount
  useEffect(() => {
    void loadHistory(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSendMessage = async () => {
    if (!input.trim() || isLoading) return;

    const userMessage = input.trim();
    setInput("");
    setMessages((prev) => [...prev, { role: "user", content: userMessage }]);
    setIsLoading(true);

    try {
      const response = await fetch("/api/agent/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ user_query: userMessage })
      });

      if (!response.ok) throw new Error("Failed to get response from AI");

      const data = await response.json();
      if (data.status === "success" && data.ai_response) {
        setMessages((prev) => [...prev, { role: "ai", content: data.ai_response }]);
      } else {
        throw new Error("Invalid response format");
      }
    } catch (error) {
      console.error("Chat error:", error);
      setMessages((prev) => [...prev, { role: "ai", content: "Sorry, I'm having trouble connecting to the server. Please check your backend." }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={cn("w-full h-full flex flex-col bg-background border rounded-lg overflow-hidden shadow-sm", className)}>
      {/* Header */}
      {!hideHeader && (
        <div className="flex items-center justify-between p-4 border-b bg-muted/30">
          <h2 className="font-semibold text-sm">CiCi Assistant</h2>
          {onClose && (
            <button onClick={onClose} className="p-1 hover:bg-muted rounded-md transition-colors">
              <XIcon className="size-4" />
            </button>
          )}
        </div>
      )}

      {/* Messages */}
      <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* Load older history */}
        {historyCursor && (
          <div className="flex justify-center mb-2">
            <button
              type="button"
              onClick={() => void loadHistory(false)}
              className="text-xs px-3 py-1 rounded-full border border-border text-muted-foreground hover:bg-muted/60 transition-colors"
              disabled={isHistoryLoading}
            >
              {isHistoryLoading ? "Loading..." : "Load older messages"}
            </button>
          </div>
        )}

        {messages.map((msg, i) => (
          <div key={i} className={cn("flex", msg.role === "user" ? "justify-end" : "justify-start")}>
            <div className={cn(
              "max-w-[85%] p-3 rounded-2xl text-sm shadow-sm",
              msg.role === "user"
                ? "bg-primary text-primary-content rounded-tr-none"
                : "bg-muted text-foreground rounded-tl-none border"
            )}>
              {msg.content}
            </div>
          </div>
        ))}
        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-muted p-3 rounded-2xl rounded-tl-none border flex items-center gap-2">
              <Loader2Icon className="size-3 animate-spin" />
              <span className="text-xs">Typing...</span>
            </div>
          </div>
        )}
      </div>

      {/* Input */}
      <div className="p-4 border-t bg-background">
        <form
          onSubmit={(e) => { e.preventDefault(); handleSendMessage(); }}
          className="flex items-center gap-2"
        >
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Ask CiCi something..."
            className="flex-1 bg-muted/50 border-none focus:ring-1 focus:ring-primary rounded-xl px-4 py-2 text-sm outline-none transition-all"
            disabled={isLoading}
          />
          <button
            type="submit"
            disabled={!input.trim() || isLoading}
            className="p-2 bg-primary text-primary-content rounded-xl hover:opacity-90 disabled:opacity-50 transition-all flex items-center justify-center"
          >
            {isLoading ? <Loader2Icon className="size-4 animate-spin" /> : <SendIcon className="size-4" />}
          </button>
        </form>
      </div>
    </div>
  );
};

export default ChatbotPanel;
