"use client";

import { useState, useEffect, useRef } from "react";
import { Send, Bot } from "lucide-react";
import { chatBotApi, getChatHistory } from "@/lib/api/apis";
import { decodeHtml } from "@/lib/commonFunctions";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useRouter } from "next/navigation";

interface Message {
  text: string;
  sender: "user" | "bot";
  typing?: boolean;
}

export default function AiChatbot() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const lang = getStoredLanguage();
  const t = getTranslation(lang).aiChatbotPage;
  const [userId, setUserId] = useState("");
  const router = useRouter();

  useEffect(() => {
    const userData = localStorage.getItem("user_data");

    if (!userData) {
      router.replace("/login");
      return;
    }

    const user = JSON.parse(userData);
    setUserId(user?.id);
  }, []);

  const getHistory = async (userId: string) => {
    try {
      const formData = new FormData();
      formData.append("user_id", String(userId));

      const res = await getChatHistory(formData);

      const history = res?.data?.history || [];

      // 🔥 Convert API format → UI format
      const formattedMessages = history
        .slice() 
        .reverse()
        .flatMap((item: any) => [
          {
            text: decodeHtml(item.question), // ✅ fix encoded text
            sender: "user",
          },
          {
            text: decodeHtml(item.response),
            sender: "bot",
          },
        ]);

      setMessages(formattedMessages);
    } catch (e) {
      console.log("Error--", e);
    }
  };

  useEffect(() => {
    getHistory(userId);
  }, [userId]);

  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTo({
        top: chatContainerRef.current.scrollHeight,
        behavior: "smooth",
      });
    }
  }, [messages, loading]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      sendMessage();
    }
  };

  const typeBotMessage = (fullText: string) => {
    let currentIndex = 0;
    setMessages((prev) => [...prev, { text: "", sender: "bot" }]);

    const interval = setInterval(() => {
      currentIndex++;
      setMessages((prev) => {
        const updated = [...prev];
        const lastMsgIndex = updated.length - 1;
        if (!updated[lastMsgIndex]) return prev;
        updated[lastMsgIndex] = {
          ...updated[lastMsgIndex],
          text: fullText.slice(0, currentIndex),
        };
        return updated;
      });

      if (currentIndex >= fullText.length) {
        clearInterval(interval);
      }
    }, 10);
  };

  const sendMessage = async () => {
    if (!input.trim()) return;

    const question = input;
    setMessages((prev) => [...prev, { text: question, sender: "user" }]);
    setInput("");
    setLoading(true);
    setMessages((prev) => [...prev, { text: "", sender: "bot", typing: true }]);

    try {
      const formData = new FormData();
      formData.append("question", question);
      formData.append("user_id", userId);

      const res = await chatBotApi(formData);
      const reply = res?.data?.reply || "";
      setLoading(false);
      setMessages((prev) => prev.slice(0, -1));
      typeBotMessage(reply);
    } catch (e) {
      console.log(e);
      setLoading(false);
    }
  };

  return (
    <div className="h-[100vh] bg-gradient-to-br from-orange-50 to-white flex items-center justify-center md:p-6">
      <div className="w-full h-[91vh] md:h-[85vh] md:max-w-3xl flex flex-col bg-white/80 backdrop-blur-xl md:rounded-2xl shadow-none md:shadow-2xl border overflow-hidden mt-20">
        <div className="sticky top-0 z-10 text-center py-4 border-b bg-white/80 backdrop-blur-xl">
          <h2 className="text-xl md:text-2xl font-semibold text-gray-800">
            {t.title}
          </h2>
          <p className="text-xs md:text-sm text-gray-500">{t.subtitle}</p>
        </div>

        <div
          ref={chatContainerRef}
          className="flex-1 overflow-y-auto px-4 md:px-10 py-6 space-y-4 chat-scroll"
        >
          {messages.map((msg, i) => (
            <div
              key={i}
              className={`flex ${msg.sender === "user" ? "justify-end" : "justify-start"}`}
            >
              {!loading && msg.sender !== "user" && (
                <div className="mr-2">
                  <Bot />
                </div>
              )}
              <div
                style={{ whiteSpace: "pre-line" }}
                className={`max-w-[80%] md:max-w-lg px-4 py-2 rounded-2xl text-sm leading-relaxed shadow-sm ${
                  msg.sender === "user"
                    ? "bg-[#FAA631] text-white"
                    : "bg-gray-100 text-gray-800"
                }`}
              >
                {decodeHtml(msg.text)}
              </div>
            </div>
          ))}

          {loading && (
            <div className="text-sm text-gray-500 animate-pulse">
              {t.thinking}
            </div>
          )}
        </div>

        <div className="sticky bottom-0 p-4 border-t flex gap-2 bg-white/90 backdrop-blur-xl">
          <input
            onKeyDown={handleKeyDown}
            className="flex-1 border rounded-xl px-4 py-2 focus:outline-none focus:ring-2 focus:ring-[#FAA631]"
            placeholder={t.placeholder}
            value={input}
            onChange={(e) => setInput(e.target.value)}
          />

          <button
            onClick={sendMessage}
            className="bg-[#FAA631] hover:bg-[#e59525] text-white px-4 rounded-xl flex items-center justify-center transition"
          >
            <Send size={18} />
          </button>
        </div>
      </div>
    </div>
  );
}
