"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import Image from "next/image";
import DOMPurify from "dompurify";
import { useChatSocket } from "@/hooks/useChatSocket";
import { useLiveKitVoice, type VoiceMessage } from "@/hooks/useLiveKitVoice";
import VoiceOverlay from "@/components/VoiceOverlay";
import { ChatbotWindowProps } from "@/types/chatbot";
import { Kimages } from "@/common/Assets/Images";

const LinkCarousel = ({ links, sendMessage }: { links: any[], sendMessage: (text: string) => void }) => {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [showLeft, setShowLeft] = useState(false);
  const [showRight, setShowRight] = useState(false);

  const checkScroll = () => {
    if (scrollRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
      setShowLeft(scrollLeft > 0);
      setShowRight(scrollLeft < scrollWidth - clientWidth - 5);
    }
  };

  useEffect(() => {
    checkScroll();
    window.addEventListener("resize", checkScroll);
    return () => window.removeEventListener("resize", checkScroll);
  }, [links]);

  const scroll = (direction: "left" | "right") => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: direction === "left" ? -200 : 200, behavior: "smooth" });
      setTimeout(checkScroll, 300);
    }
  };

  return (
    <div className="ml-12 mt-2 relative max-w-full">
      <div className="flex items-center">
        {showLeft && (
          <button
            onClick={() => scroll("left")}
            className="absolute left-[-10px] z-10 p-1 bg-white/20 backdrop-blur-md rounded-full border border-white/20 shadow-md hover:bg-white/30 text-white cursor-pointer"
          >←</button>
        )}
        <div
          ref={scrollRef}
          onScroll={checkScroll}
          className="flex flex-row gap-2 mb-2 overflow-x-auto whitespace-nowrap max-w-full pb-2 scrollbar-hide px-1 pr-11"
          style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
        >
          {links.map((link: any, i: number) => {
            const isAction = link.url && link.url.startsWith("#");
            return (
              <a
                key={i}
                href={link.url}
                target={isAction ? undefined : "_blank"}
                rel={isAction ? undefined : "noopener noreferrer"}
                onClick={(e) => {
                  e.stopPropagation();
                  if (isAction) { e.preventDefault(); sendMessage(link.label); }
                }}
                className="flex-shrink-0 inline-flex items-center justify-center w-auto py-2 px-4 bg-white/10 backdrop-blur-md border border-white/20 hover:bg-white/20 text-white text-[12px] font-medium rounded-full transition-all cursor-pointer shadow-sm active:scale-95"
              >
                {link.label?.toUpperCase()}
              </a>
            );
          })}
        </div>
        {showRight && (
          <button
            onClick={() => scroll("right")}
            className="absolute right-[11px] z-10 p-1 bg-white/20 backdrop-blur-md rounded-full border border-white/20 shadow-md hover:bg-white/30 text-white cursor-pointer"
          >→</button>
        )}
      </div>
    </div>
  );
};

const MessageBubble = ({
  msg,
  isBot,
  isLatest,
  sendMessage,
}: {
  msg: any;
  isBot: boolean;
  isLatest: boolean;
  sendMessage: (t: string) => void;
}) => {
  const [showContent, setShowContent] = useState(!isBot || !isLatest);

  useEffect(() => {
    if (isBot && isLatest && !showContent) {
      const timer = setTimeout(() => setShowContent(true), 1500);
      return () => clearTimeout(timer);
    }
  }, [isBot, isLatest, showContent]);

  return (
    <div className="mb-6">
      <div className={`flex items-start ${isBot ? "flex-row" : "flex-row-reverse"} gap-3`}>
        {isBot && (
          <div className="w-9 h-9 flex-shrink-0 rounded-full overflow-hidden border border-white/20">
            <Image src={Kimages.chatIcon} alt="K" width={36} height={36} className="object-cover" />
          </div>
        )}
        <div className={`flex flex-col ${isBot ? "items-start" : "items-end"} max-w-[85%]`}>
          <div
            className="px-4 py-3 backdrop-blur-md border border-white/20 shadow-lg text-white"
            style={{
              background: "transparent",
              borderRadius: isBot ? "12px 12px 12px 0px" : "12px 12px 0px 12px",
              padding: "12px 16px",
            }}
          >
            {isBot && !showContent ? (
              <div className="flex gap-2 items-center h-5 px-1">
                <span className="text-[15px] font-medium text-white/70 tracking-tight">Typing</span>
                <div className="flex gap-1.5 pt-1">
                  <span className="w-1 h-1 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s] [animation-delay:-0.3s]" />
                  <span className="w-1 h-1 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s] [animation-delay:-0.15s]" />
                  <span className="w-1 h-1 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s]" />
                </div>
              </div>
            ) : (
              <div className="text-[15px] leading-relaxed font-light" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(msg.html) }} />
            )}
          </div>
          <span className="text-[11px] text-white/60 mt-1.5 font-medium px-1">
            {new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
          </span>
        </div>
      </div>
      {isBot && showContent && msg.links?.length > 0 && (
        <LinkCarousel links={msg.links} sendMessage={sendMessage} />
      )}
    </div>
  );
};

const MicIcon = ({ size = 20 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 640 640" fill="currentColor">
    <path d="M272 64C280.8 64 288 71.2 288 80L288 528C288 536.8 280.8 544 272 544C263.2 544 256 536.8 256 528L256 80C256 71.2 263.2 64 272 64zM464 128C472.8 128 480 135.2 480 144L480 464C480 472.8 472.8 480 464 480C455.2 480 448 472.8 448 464L448 144C448 135.2 455.2 128 464 128zM176 160C184.8 160 192 167.2 192 176L192 432C192 440.8 184.8 448 176 448C167.2 448 160 440.8 160 432L160 176C160 167.2 167.2 160 176 160zM368 192C376.8 192 384 199.2 384 208L384 400C384 408.8 376.8 416 368 416C359.2 416 352 408.8 352 400L352 208C352 199.2 359.2 192 368 192zM80 256C88.8 256 96 263.2 96 272L96 336C96 344.8 88.8 352 80 352C71.2 352 64 344.8 64 336L64 272C64 263.2 71.2 256 80 256zM560 256C568.8 256 576 263.2 576 272L576 336C576 344.8 568.8 352 560 352C551.2 352 544 344.8 544 336L544 272C544 263.2 551.2 256 560 256z" />
  </svg>
);

export default function ChatbotWindow({ onClose }: ChatbotWindowProps) {
  const { messages, typing, connect, sendMessage, saveVoiceMessages } = useChatSocket();
  const [input, setInput] = useState("");
  const [savedVoiceMessages, setSavedVoiceMessages] = useState<VoiceMessage[]>([]);
  const chatEndRef = useRef<HTMLDivElement | null>(null);

  // When user says "start fresh" or "continue" in voice → auto-send to text WebSocket
  const handleVoiceCommand = useCallback((command: string) => {
    if (command === "start_fresh") {
      setSavedVoiceMessages([]);
      sendMessage("START FRESH");
    } else if (command === "continue") {
      sendMessage("CONTINUE");
    }
  }, [sendMessage]);

  const {
    voiceState,
    audioLevel,
    voiceMessages,
    interimText,
    startConversation,
    stopConversation,
    stopAndSend,
    interruptAndListen,
  } = useLiveKitVoice(handleVoiceCommand);

  const isVoiceMode = voiceState !== "idle";

  useEffect(() => { connect(); }, [connect]);

  useEffect(() => {
    requestAnimationFrame(() => {
      chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
    });
  }, [messages, typing, savedVoiceMessages]);

  // When voice ends: show messages in chat + persist them to DB
  const handleStopConversation = useCallback(() => {
    if (voiceMessages.length > 0) {
      setSavedVoiceMessages((prev) => [...prev, ...voiceMessages]);
      // Save to backend so they appear in session history on next load
      saveVoiceMessages(voiceMessages.map((m) => ({ sender: m.sender, text: m.text })));
    }
    stopConversation();
  }, [voiceMessages, stopConversation, saveVoiceMessages]);

  const handleMicClick = () => {
    if (!isVoiceMode) {
      startConversation();
    } else {
      handleStopConversation();
    }
  };

  // Tap action depends on current state
  const handleVoiceTap = () => {
    if (voiceState === "listening") stopAndSend();
    else if (voiceState === "speaking") interruptAndListen();
  };

  const handleSend = () => {
    if (!input.trim()) return;
    sendMessage(input.trim());
    setInput("");
  };

  return (
    <div className="w-full h-full flex flex-col overflow-hidden font-sans relative">
      {/* Background */}
      <div
        className="absolute inset-0 z-0"
        style={{
          backgroundImage: `url(${Kimages.bgChatbot})`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        }}
      />

      {/* Header */}
      <header
        className="flex items-center justify-between px-6 h-[60px] flex-shrink-0 relative z-30 backdrop-blur-md border-b border-white/20"
        style={{ background: "rgba(133, 113, 77, 0.20)" }}
      >
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-full overflow-hidden flex items-center justify-center bg-white/10">
            <Image src={Kimages.chatIcon} width={32} height={32} alt="Logo" className="w-full h-full object-cover" />
          </div>
          <h1 className="text-[17px] font-bold text-white tracking-wide">Karma Group</h1>
        </div>
        <div className="flex items-center">
          <button onClick={onClose} className="text-white text-xl font-light cursor-pointer hover:opacity-80 px-2 transition-opacity">✕</button>
        </div>
      </header>

      {/* Body — messages + input + voice overlay */}
      <div className="relative flex-1 flex flex-col overflow-hidden">

        {/* Messages */}
        <div className="flex-1 overflow-y-auto px-4 py-3 flex flex-col relative z-10 scrollbar-hide">
          <div className="flex flex-col mt-auto">
            {messages.map((msg: any, index) => {
              const isBot = msg.sender?.toLowerCase() === "bot";
              const isLatest = index === messages.length - 1;
              return (
                <MessageBubble key={`chat-${index}`} msg={msg} isBot={isBot} isLatest={isLatest} sendMessage={sendMessage} />
              );
            })}
            {savedVoiceMessages.map((vm, index) => (
              <MessageBubble
                key={`voice-${index}`}
                msg={{ html: vm.text, links: [] }}
                isBot={vm.sender === "bot"}
                isLatest={false}
                sendMessage={sendMessage}
              />
            ))}
            {typing && (
              <div className="flex flex-row items-start gap-2 mb-2">
                <div className="w-7 h-7 flex-shrink-0 rounded-full overflow-hidden border border-white/20">
                  <Image src={Kimages.chatIcon} alt="K" width={28} height={28} className="object-cover" />
                </div>
                <div
                  className="backdrop-blur-md border border-white/20 shadow-sm"
                  style={{ background: "transparent", borderRadius: "10px 10px 10px 0px", padding: "8px 12px" }}
                >
                  <div className="flex gap-1.5 items-center h-4">
                    <span className="w-1.5 h-1.5 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s] [animation-delay:-0.3s]" />
                    <span className="w-1.5 h-1.5 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s] [animation-delay:-0.15s]" />
                    <span className="w-1.5 h-1.5 bg-white/50 rounded-full animate-bounce [animation-duration:1.2s]" />
                  </div>
                </div>
              </div>
            )}
          </div>
          <div ref={chatEndRef} />
        </div>

        {/* Input area */}
        <div className="px-4 py-3 relative z-10 flex items-center gap-3">
          <div
            className="flex-1 flex items-center backdrop-blur-md gap-3"
            style={{
              height: "50px",
              padding: "12px 18px",
              borderRadius: "59px",
              border: "1px solid rgba(255, 255, 255, 0.20)",
              background: "rgba(255, 255, 255, 0.10)",
            }}
          >
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleSend();
                }
              }}
              placeholder="Enter Message"
              rows={1}
              className="w-full max-h-[120px] resize-none overflow-y-auto border-none bg-transparent text-white text-[15px] focus:outline-none focus:ring-0 py-0 placeholder:text-white/80"
            />
          </div>

          {/* Mic button */}
          <button
            onClick={handleMicClick}
            title="Start voice"
            className="w-12 h-12 flex-shrink-0 rounded-full flex items-center justify-center transition-all active:scale-95 shadow-lg cursor-pointer bg-white/20 hover:bg-white/30 text-white"
          >
            <MicIcon size={20} />
          </button>

          {/* Send button */}
          <button
            onClick={handleSend}
            className="w-12 h-12 flex-shrink-0 bg-[#85714D] hover:bg-[#b0915a] rounded-full flex items-center justify-center cursor-pointer transition-all active:scale-95 shadow-lg group"
          >
            <Image
              src={Kimages.sendIcon}
              width={22}
              height={22}
              alt="Send"
              className="group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform"
            />
          </button>
        </div>

        {/* Voice overlay — covers messages + input while voice is active */}
        {isVoiceMode && (
          <VoiceOverlay
            voiceState={voiceState}
            audioLevel={audioLevel}
            interimText={interimText}
            onStop={handleStopConversation}
            onTap={handleVoiceTap}
          />
        )}
      </div>
    </div>
  );
}
