'use client';

/* eslint-disable react-hooks/set-state-in-effect */

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useApp } from '@/context/AppContext';
import { motion, AnimatePresence } from 'motion/react';
import { 
  MessageSquare, 
  X, 
  Send, 
  Sparkles, 
  Bot, 
  User, 
  Maximize2, 
  Minimize2, 
  RefreshCw, 
  ChevronDown,
  ShieldAlert
} from 'lucide-react';

interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  text: string;
  timestamp: string;
}

// Pure helper function declared outside component rendering path
function generateUniqueId(prefix: string): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    try {
      return `${prefix}-${crypto.randomUUID()}`;
    } catch {
      // fallback
    }
  }
  return `${prefix}-${Math.floor(Math.random() * 1000000)}`;
}

function getFormattedTime(): string {
  try {
    return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  } catch {
    return '00:00';
  }
}

export default function ChatBot() {
  const { currentUser, theme } = useApp();
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  // Determine if active user is admin (computed directly to prevent nested state cycles)
  const adminAuth = typeof window !== 'undefined' && localStorage.getItem('vgb_admin_auth') === 'true';
  const isUserAdminEmail = currentUser?.email?.toLowerCase() === 'labawkjohn@gmail.com';
  const isAdmin = !!(adminAuth || isUserAdminEmail);

  // Unique key for storage based on user identity for private conversation partition
  const getStorageKey = useCallback(() => {
    if (isAdmin) return 'vgb_chat_history_admin';
    if (currentUser?.email) return `vgb_chat_history_${currentUser.email.toLowerCase()}`;
    return 'vgb_chat_history_guest';
  }, [isAdmin, currentUser]);

  // Set default intro message based on roles
  const setDefaultGreeting = useCallback(() => {
    const greetingText = isAdmin
      ? 'Welcome, Operator John. I am your Administrative Operations Co-pilot. I can assist you with compiling invoices, analyzing order cues, writing catalog presets descriptions, or draft custom SLA responses. How can I facilitate your work today?'
      : `Hello! I am your Master Digital Creative AI Assistant. I am here to help you browse our custom Canva/CapCut preset bundles, set up social program monetization, configure virtual wallets, or plan bespoke design & cinematic editing requests. How can I help you today?`;

    setMessages([
      {
        id: 'system-init',
        role: 'assistant',
        text: greetingText,
        timestamp: getFormattedTime(),
      },
    ]);
  }, [isAdmin]);

  // Load chat history on mount or identity change
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem(getStorageKey());
      if (stored) {
        try {
          setMessages(JSON.parse(stored));
        } catch (e) {
          console.error('Error loading chat history:', e);
          setDefaultGreeting();
        }
      } else {
        setDefaultGreeting();
      }
    }
  }, [getStorageKey, setDefaultGreeting]);

  // Save history to localstorage whenever messages update
  useEffect(() => {
    if (messages.length > 0 && typeof window !== 'undefined') {
      localStorage.setItem(getStorageKey(), JSON.stringify(messages));
    }
  }, [messages, getStorageKey]);

  // Scroll to bottom when messages update
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, isOpen, isMinimized]);

  // Default suggested questions
  const getSuggestedQuestions = () => {
    if (isAdmin) {
      return [
        'How can I write custom response notes for clients orders?',
        'Suggest products specifications for a new Canva preset package.',
        'Draft a professional delivery confirmation email template.'
      ];
    }
    return [
      'What premium CapCut & Canva presets do you offer?',
      'How does the Social Monetization setup service work?',
      'How do I request a custom design/video editing project?'
    ];
  };

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

    const newUserMessage: ChatMessage = {
      id: generateUniqueId('m'),
      role: 'user',
      text: textToSend.trim(),
      timestamp: getFormattedTime(),
    };

    setMessages((prev) => [...prev, newUserMessage]);
    setInputText('');
    setIsLoading(true);
    setErrorMsg('');

    try {
      // Prepare full message history for the LLM
      const updatedHistory = [...messages, newUserMessage];
      // Limit to last 15 messages to prevent overloading payload
      const slicedHistory = updatedHistory.slice(-15).map(m => ({
        role: m.role,
        text: m.text
      }));

      const res = await fetch('/api/gemini/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: slicedHistory,
          userEmail: currentUser?.email || 'guest',
          isAdmin: isAdmin,
        }),
      });

      const data = await res.json();
      if (!res.ok || data.error) {
        throw new Error(data.error || 'Server responded with an error');
      }

      const botReply: ChatMessage = {
        id: generateUniqueId('bot'),
        role: 'assistant',
        text: data.response,
        timestamp: getFormattedTime(),
      };

      setMessages((prev) => [...prev, botReply]);
    } catch (e: any) {
      console.error('Failed to receive response from custom chatbot route:', e);
      setErrorMsg(e?.message || 'Connection lost. Please verify your internet and try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleClearHistory = () => {
    if (window.confirm('Are you sure you want to completely clear your private chat conversation?')) {
      localStorage.removeItem(getStorageKey());
      setDefaultGreeting();
    }
  };

  const isDark = theme === 'dark';

  if (!isMounted) return null;

  return (
    <div className="fixed bottom-6 right-6 z-50 font-sans" id="chatbot-global-container">
      <AnimatePresence>
        {/* Floating Bubble */}
        {!isOpen && (
          <motion.button
            id="chatbot-trigger-bubble"
            onClick={() => setIsOpen(true)}
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.8, opacity: 0 }}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            className={`w-14 h-14 rounded-full flex items-center justify-center cursor-pointer shadow-xl relative z-50 border ${
              isAdmin 
                ? 'bg-gradient-to-tr from-purple-600 to-pink-500 border-purple-400/50 hover:shadow-purple-500/25' 
                : 'bg-gradient-to-tr from-cyan-500 to-indigo-600 border-cyan-400/50 hover:shadow-cyan-500/25'
            }`}
          >
            {isAdmin ? (
              <Bot className="w-6.5 h-6.5 text-white animate-pulse" />
            ) : (
              <MessageSquare className="w-6.5 h-6.5 text-white" />
            )}
            <div className={`absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full border-2 border-white dark:border-slate-950 ${
              isAdmin ? 'bg-pink-400 animate-ping' : 'bg-cyan-400 animate-pulse'
            }`} />
          </motion.button>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {/* Chat window */}
        {isOpen && (
          <motion.div
            id="chatbot-window-panel"
            initial={{ opacity: 0, y: 30, scale: 0.95 }}
            animate={{ 
              opacity: 1, 
              y: 0, 
              scale: 1,
              height: isMinimized ? '56px' : '580px',
              width: '380px'
            }}
            exit={{ opacity: 0, y: 30, scale: 0.95 }}
            transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            className={`rounded-2xl border flex flex-col overflow-hidden shadow-2xl backdrop-blur-xl transition-all duration-300 ${
              isDark 
                ? 'border-white/10 bg-[#070514]/75 text-white shadow-black/80' 
                : 'border-slate-205 bg-white/95 text-slate-800 shadow-slate-200/50'
            }`}
          >
            {/* Header */}
            <div 
              className={`px-4 py-3.5 flex items-center justify-between border-b ${
                isAdmin
                  ? 'bg-gradient-to-r from-purple-950/40 via-pink-950/20 to-purple-950/40 border-purple-500/10'
                  : 'bg-gradient-to-r from-cyan-950/40 via-indigo-950/20 to-cyan-950/40 border-cyan-500/10'
              }`}
            >
              <div className="flex items-center gap-2.5">
                <div className={`w-8.5 h-8.5 rounded-xl border flex items-center justify-center shadow-inner ${
                  isAdmin 
                    ? 'bg-purple-500/10 border-purple-500/30 text-purple-400' 
                    : 'bg-cyan-500/10 border-cyan-500/30 text-cyan-400'
                }`}>
                  {isAdmin ? <Bot className="w-5 h-5" /> : <Sparkles className="w-4.5 h-4.5" />}
                </div>
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider flex items-center gap-1.5">
                    {isAdmin ? 'Operation Co-pilot' : 'Creative AI'}
                    {isAdmin && (
                      <span className="text-[8px] bg-purple-500/20 text-purple-300 font-mono px-1.5 py-0.5 rounded uppercase">
                        Admin Mode
                      </span>
                    )}
                  </h3>
                  <p className="text-[10px] text-slate-400 font-medium">
                    {isAdmin ? 'Secure private gateway' : 'Private design assistant'}
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-1">
                {/* Clear conversations */}
                <button
                  type="button"
                  title="Clear conversation history"
                  onClick={handleClearHistory}
                  className="p-1.5 rounded-lg hover:bg-white/10 text-slate-400 hover:text-slate-100 transition-colors cursor-pointer"
                >
                  <RefreshCw className="w-3.5 h-3.5" />
                </button>

                {/* Minimize toggler */}
                <button
                  type="button"
                  onClick={() => setIsMinimized(!isMinimized)}
                  className="p-1.5 rounded-lg hover:bg-white/10 text-slate-400 hover:text-slate-100 transition-colors cursor-pointer"
                >
                  {isMinimized ? <Maximize2 className="w-3.5 h-3.5" /> : <Minimize2 className="w-3.5 h-3.5" />}
                </button>

                {/* Close toggler */}
                <button
                  type="button"
                  onClick={() => setIsOpen(false)}
                  className="p-1.5 rounded-lg hover:bg-white/10 text-slate-400 hover:text-red-400 transition-colors cursor-pointer"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
            </div>

            {/* Chat Content Body */}
            {!isMinimized && (
              <>
                {/* Conversation area */}
                <div className="flex-1 overflow-y-auto p-4 space-y-4 scrollbar-thin">
                  {messages.map((m) => {
                    const isAssistant = m.role === 'assistant';
                    return (
                      <div
                        key={m.id}
                        className={`flex gap-2.5 max-w-[85%] ${
                          isAssistant ? 'self-start mr-auto' : 'self-end ml-auto flex-row-reverse'
                        }`}
                      >
                        {/* Avatar bubble representation */}
                        <div className={`w-7.5 h-7.5 rounded-lg flex items-center justify-center shrink-0 border text-[10px] font-bold ${
                          isAssistant
                            ? isAdmin
                              ? 'bg-purple-500/10 border-purple-500/20 text-purple-400'
                              : 'bg-cyan-500/10 border-cyan-500/20 text-cyan-400'
                            : 'bg-indigo-500/10 border-indigo-500/25 text-indigo-400'
                        }`}>
                          {isAssistant ? (
                            isAdmin ? <Bot className="w-4 h-4" /> : <Sparkles className="w-3.5 h-3.5" />
                          ) : (
                            <User className="w-3.5 h-3.5" />
                          )}
                        </div>

                        <div className="space-y-0.5">
                          <div
                            className={`p-3 rounded-2xl text-xs leading-normal select-text whitespace-pre-wrap ${
                              isAssistant
                                ? isDark
                                  ? 'bg-[#100c25]/50 border border-white/5 shadow-xs text-slate-200'
                                  : 'bg-slate-100 text-slate-800'
                                : 'bg-gradient-to-r from-cyan-600 to-indigo-600 border border-cyan-500/20 text-white'
                            }`}
                          >
                            {m.text}
                          </div>
                          <div className={`text-[8.5px] text-slate-500 ${isAssistant ? 'text-left pl-1.5' : 'text-right pr-1.5'} font-mono`}>
                            {m.timestamp}
                          </div>
                        </div>
                      </div>
                    );
                  })}

                  {/* Loading placeholder block */}
                  {isLoading && (
                    <div className="flex gap-2.5 max-w-[80%] self-start mr-auto">
                      <div className={`w-7.5 h-7.5 rounded-lg flex items-center justify-center border animate-spin overflow-hidden ${
                        isAdmin 
                          ? 'bg-purple-500/10 border-purple-500/30 text-purple-400' 
                          : 'bg-cyan-500/10 border-cyan-500/30 text-cyan-400'
                      }`}>
                        <Sparkles className="w-3.5 h-3.5 animate-pulse" />
                      </div>
                      <div className={`p-3.5 rounded-2xl text-xs flex items-center gap-1.5 ${
                        isDark ? 'bg-slate-950/40 border border-white/5 text-slate-400' : 'bg-slate-100 text-slate-500'
                      }`}>
                        <span>Thinking...</span>
                        <div className="flex gap-1">
                          <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
                          <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                          <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Error indicators */}
                  {errorMsg && (
                    <div className="p-3 bg-red-500/10 border border-red-500/20 rounded-xl flex items-start gap-2 text-xs text-red-400">
                      <ShieldAlert className="w-4 h-4 shrink-0 mt-0.5" />
                      <div>
                        <span className="font-bold">Execution Error:</span> {errorMsg}
                      </div>
                    </div>
                  )}

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

                {/* Suggestions list */}
                {messages.length <= 1 && (
                  <div className="px-4 pb-2 pt-1 border-t border-slate-300/10">
                    <p className="text-[9px] font-bold text-slate-500 uppercase tracking-wider mb-2">Suggested Prompts:</p>
                    <div className="flex flex-col gap-1.5">
                      {getSuggestedQuestions().map((q, idx) => (
                        <button
                          key={idx}
                          type="button"
                          onClick={() => handleSendMessage(q)}
                          className={`w-full text-left p-2 rounded-xl text-[10.5px] border transition-all truncate hover-scale cursor-pointer ${
                            isDark 
                              ? 'bg-white/[0.02] border-white/5 hover:bg-white/[0.05] hover:border-cyan-500/30 text-slate-300 hover:text-white' 
                              : 'bg-slate-50 border-slate-200 hover:bg-slate-100 hover:border-cyan-500/30 text-slate-600 hover:text-slate-950'
                          }`}
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Footnotes message partition */}
                {!currentUser && !isAdmin && (
                  <div className="px-4 py-1.5 bg-yellow-500/5 border-t border-yellow-500/15 text-[9px] text-yellow-500/80 text-center font-medium leading-normal flex items-center justify-center gap-1">
                    🔓 <span>Chatting as Guest. <a href="/login" className="underline font-bold hover:text-yellow-400">Sign in</a> to secure conversations privately across sessions.</span>
                  </div>
                )}

                {currentUser && !isAdmin && (
                  <div className="px-4 py-1.5 bg-cyan-500/5 border-t border-cyan-500/15 text-[9px] text-cyan-400 text-center font-mono leading-normal">
                    🔒 Private secure chat channel isolated for account: {currentUser.email}
                  </div>
                )}

                {isAdmin && (
                  <div className="px-4 py-1.5 bg-purple-500/5 border-t border-purple-500/15 text-[9px] text-purple-400 text-center font-mono leading-normal">
                    🛡️ Secure sandbox operations node authorized for system root
                  </div>
                )}

                {/* Compose Form footer */}
                <form 
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleSendMessage(inputText);
                  }}
                  className="p-3 border-t border-slate-300/10 flex gap-2 items-center"
                >
                  <input
                    type="text"
                    required
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    placeholder="Type your message securely..."
                    disabled={isLoading}
                    className={`flex-1 px-3.5 py-2.5 rounded-xl border text-xs outline-none transition-all ${
                      isDark
                        ? 'bg-slate-950/55 border-white/5 text-white focus:border-cyan-500/40 focus:bg-slate-950'
                        : 'bg-slate-50 border-slate-200 text-slate-900 focus:border-cyan-500/40 focus:bg-white'
                    }`}
                  />
                  <button
                    type="submit"
                    disabled={isLoading || !inputText.trim()}
                    className={`p-2.5 rounded-xl text-white transform active:scale-95 transition-all shadow-md cursor-pointer disabled:opacity-40 shrink-0 ${
                      isAdmin 
                        ? 'bg-gradient-to-tr from-purple-600 to-pink-500 hover:from-purple-500 hover:to-pink-400' 
                        : 'bg-gradient-to-tr from-cyan-500 to-indigo-600 hover:from-cyan-400 hover:to-indigo-500'
                    }`}
                  >
                    <Send className="w-3.5 h-3.5" />
                  </button>
                </form>
              </>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
