"use client";

import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  MessageCircle,
  X,
  Send,
  Loader2,
  Sparkles,
  Trash2,
} from "lucide-react";

interface Message {
  id: string;
  text: string;
  sender: "user" | "bot";
  timestamp: Date;
  isTyping?: boolean;
}

export default function ChatWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [conversationId, setConversationId] = useState(() => {
    // Generate or retrieve conversation ID
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem("chatSessionId");
      if (stored) return stored;
      const newId = crypto.randomUUID();
      localStorage.setItem("chatSessionId", newId);
      return newId;
    }
    return "default";
  });

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // Focus input when chat opens
  useEffect(() => {
    if (isOpen) {
      inputRef.current?.focus();
    }
  }, [isOpen]);

  // Helper function to decode HTML entities
  const decodeHtmlEntities = (text: string): string => {
    if (!text || typeof text !== "string") return text;
    const textarea = document.createElement("textarea");
    textarea.innerHTML = text;
    return textarea.value;
  };

  // Load messages from localStorage
  useEffect(() => {
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem("chatMessages");
      if (stored) {
        try {
          const parsed = JSON.parse(stored);
          setMessages(
            parsed.map((m: Message) => ({
              ...m,
              text: decodeHtmlEntities(m.text), // Decode HTML entities when loading
              timestamp: new Date(m.timestamp),
            })),
          );
        } catch (e) {
          console.error("Failed to load chat history", e);
        }
      } else {
        // Add welcome message
        setMessages([
          {
            id: "welcome",
            text: "Hi! I'm Dennis's AI assistant. Ask me anything about his skills, projects, or experience! 🚀",
            sender: "bot",
            timestamp: new Date(),
          },
        ]);
      }
    }
  }, []);

  // Save messages to localStorage
  useEffect(() => {
    if (typeof window !== "undefined" && messages.length > 0) {
      localStorage.setItem("chatMessages", JSON.stringify(messages));
    }
  }, [messages]);

  const handleSend = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      text: inputValue.trim(),
      sender: "user",
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInputValue("");
    setIsLoading(true);

    // Get last 10 messages for context
    const history = messages.slice(-10).map((m) => ({
      role: m.sender === "user" ? "user" : "assistant",
      content: m.text,
    }));

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

      if (!response.ok) {
        const errorText = await response.text().catch(() => "Unknown error");
        console.error("Chat API error:", {
          status: response.status,
          statusText: response.statusText,
          error: errorText,
        });
        throw new Error(
          `Failed to get response: ${response.status} - ${errorText.substring(0, 100)}`,
        );
      }

      const data = await response.json();

      // Log response for debugging (only in development)
      if (process.env.NODE_ENV === "development") {
        console.log("Chat API response:", data);
      }

      // Decode HTML entities in the reply
      let replyText =
        data.reply || "Sorry, I couldn't process that. Please try again.";

      // Decode HTML entities client-side (double safety)
      replyText = decodeHtmlEntities(replyText);

      const botMessage: Message = {
        id: (Date.now() + 1).toString(),
        text: replyText,
        sender: "bot",
        timestamp: new Date(),
      };

      setMessages((prev) => [...prev, botMessage]);
    } catch (error) {
      console.error("Chat error:", error);

      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        text: "Sorry, I'm having trouble connecting right now. Please try again later or use the contact form below.",
        sender: "bot",
        timestamp: new Date(),
      };

      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const clearChat = () => {
    // Reset session ID
    const newId = crypto.randomUUID();
    setConversationId(newId);
    if (typeof window !== "undefined") {
      localStorage.setItem("chatSessionId", newId);
      localStorage.removeItem("chatMessages");
    }

    setMessages([
      {
        id: "welcome",
        text: "Conversation restarted! Ask me anything about Dennis! 🚀",
        sender: "bot",
        timestamp: new Date(),
      },
    ]);
  };

  return (
    <>
      {/* Chat Button */}
      <AnimatePresence>
        {!isOpen && (
          <motion.div
            role="button"
            tabIndex={0}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            onClick={() => setIsOpen(true)}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                setIsOpen(true);
              }
            }}
            className="fixed bottom-4 left-4 md:bottom-6 md:left-6 z-30 bg-stone-800/80 backdrop-blur-md text-stone-50 p-3.5 rounded-full shadow-[0_8px_20px_rgba(41,37,36,0.2)] hover:bg-stone-800 hover:scale-105 transition-all duration-300 group cursor-pointer border border-white/10 ring-1 ring-white/20"
            aria-label="Open chat"
          >
            <MessageCircle size={24} />
            <span className="absolute top-0 right-0 w-3 h-3 bg-stone-400 rounded-full animate-pulse shadow-sm border-2 border-stone-800" />

            {/* Tooltip */}
            <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-3 px-3 py-1.5 bg-stone-900/90 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-[100] shadow-xl backdrop-blur-sm">
              Chat with AI
            </span>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Chat Window */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            data-chat-widget
            initial={{ opacity: 0, y: 20, scale: 0.95, filter: "blur(10px)" }}
            animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}
            exit={{ opacity: 0, y: 20, scale: 0.95, filter: "blur(10px)" }}
            transition={{ type: "spring", damping: 30, stiffness: 400 }}
            className="fixed bottom-20 left-4 right-4 md:bottom-24 md:left-6 md:right-auto z-30 md:w-[380px] h-[60vh] md:h-[550px] max-h-[600px] bg-[#fdfcf8]/30 backdrop-blur-2xl saturate-150 rounded-2xl shadow-[0_12px_40px_rgba(41,37,36,0.15)] flex flex-col overflow-hidden border border-white/40 ring-1 ring-white/50"
          >
            {/* Header */}
            <div className="bg-white/20 backdrop-blur-md text-stone-800 p-4 flex items-center justify-between border-b border-white/20">
              <div className="flex items-center gap-3">
                <div className="relative">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-stone-100/80 to-white/80 flex items-center justify-center ring-1 ring-white shadow-sm backdrop-blur-sm">
                    <Sparkles size={18} className="text-stone-600" />
                  </div>
                  <span className="absolute bottom-0 right-0 w-2.5 h-2.5 bg-emerald-400 rounded-full border-2 border-white shadow-sm" />
                </div>
                <div className="min-w-0 flex-1">
                  <h3 className="font-bold text-sm truncate text-stone-900 tracking-tight">
                    Assistant
                  </h3>
                  <p className="text-[11px] font-medium text-stone-500 truncate">
                    Powered by AI
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-1">
                <button
                  onClick={clearChat}
                  className="p-2 hover:bg-stone-200/40 rounded-full transition-colors text-stone-500 hover:text-red-500"
                  title="Clear conversation"
                >
                  <Trash2 size={16} />
                </button>
                <button
                  onClick={() => setIsOpen(false)}
                  className="p-2 hover:bg-stone-200/40 rounded-full transition-colors text-stone-500 hover:text-stone-900"
                  aria-label="Close chat"
                >
                  <X size={20} />
                </button>
              </div>
            </div>

            {/* Messages */}
            <div className="flex-1 overflow-y-auto scrollbar-hide p-4 space-y-4 bg-transparent">
              {messages.map((message) => (
                <motion.div
                  key={message.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className={`flex ${message.sender === "user" ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-[85%] rounded-2xl px-4 py-3 backdrop-blur-md shadow-sm ${
                      message.sender === "user"
                        ? "bg-stone-800/90 text-stone-50 ring-1 ring-white/10"
                        : "bg-white/70 text-stone-800 border border-white/50 ring-1 ring-white/40"
                    }`}
                  >
                    <p className={`text-sm whitespace-pre-wrap break-words leading-relaxed ${
                      message.sender === "user" ? "text-stone-50 font-light" : "text-stone-800 font-medium"
                    }`}>
                      {message.text}
                    </p>
                    <p
                      className={`text-[10px] mt-1.5 ${
                        message.sender === "user"
                          ? "text-stone-400"
                          : "text-stone-500"
                      }`}
                    >
                      {message.timestamp.toLocaleTimeString([], {
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </p>
                  </div>
                </motion.div>
              ))}

              {/* Typing Indicator */}
              {isLoading && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex justify-start"
                >
                  <div className="bg-white/60 backdrop-blur-md border border-white/40 rounded-2xl px-4 py-3 shadow-sm ring-1 ring-white/40">
                    <div className="flex gap-1.5">
                      <motion.div
                        className="w-1.5 h-1.5 bg-stone-500 rounded-full"
                        animate={{ y: [0, -6, 0] }}
                        transition={{
                          duration: 0.6,
                          repeat: Infinity,
                          delay: 0,
                        }}
                      />
                      <motion.div
                        className="w-1.5 h-1.5 bg-stone-500 rounded-full"
                        animate={{ y: [0, -6, 0] }}
                        transition={{
                          duration: 0.6,
                          repeat: Infinity,
                          delay: 0.1,
                        }}
                      />
                      <motion.div
                        className="w-1.5 h-1.5 bg-stone-500 rounded-full"
                        animate={{ y: [0, -6, 0] }}
                        transition={{
                          duration: 0.6,
                          repeat: Infinity,
                          delay: 0.2,
                        }}
                      />
                    </div>
                  </div>
                </motion.div>
              )}

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

            {/* Input */}
            <div className="p-4 bg-white/20 backdrop-blur-xl border-t border-white/20">
              <div className="flex gap-2">
                <input
                  ref={inputRef}
                  type="text"
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="Ask anything..."
                  disabled={isLoading}
                  className="flex-1 px-4 py-3 text-sm bg-white/50 backdrop-blur-sm text-stone-800 rounded-xl border border-white/40 focus:outline-none focus:ring-2 focus:ring-stone-200/50 focus:border-stone-400/50 focus:bg-white/70 disabled:opacity-50 disabled:cursor-not-allowed placeholder:text-stone-500 transition-all shadow-inner"
                />
                <button
                  onClick={handleSend}
                  disabled={!inputValue.trim() || isLoading}
                  className="p-3 bg-stone-800 text-stone-50 rounded-xl hover:bg-stone-700 hover:shadow-lg hover:scale-105 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 shadow-md flex items-center justify-center aspect-square"
                  aria-label="Send message"
                >
                  {isLoading ? (
                    <Loader2 size={18} className="animate-spin" />
                  ) : (
                    <Send size={18} />
                  )}
                </button>
              </div>

              {/* Quick Actions */}
              <div className="flex gap-2 mt-3 overflow-x-auto pb-1 scrollbar-hide mask-fade-right">
                {[
                  "Skills 🛠️",
                  "Projects 🚀",
                  "Contact 📧",
                ].map((suggestion, index) => (
                  <button
                    key={index}
                    onClick={() => {
                      setInputValue(suggestion.replace(/ .*/, '')); // Strip emoji for search if needed, or keep
                      inputRef.current?.focus();
                    }}
                    disabled={isLoading}
                    className="px-3 py-1.5 text-xs font-medium bg-white/40 backdrop-blur-md text-stone-700 rounded-lg hover:bg-white/60 hover:text-stone-900 border border-white/40 transition-all whitespace-nowrap disabled:opacity-50 flex-shrink-0 shadow-sm"
                  >
                    {suggestion}
                  </button>
                ))}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
