'use client';

import React, { useEffect, useState, useRef } from 'react';
import { MessageSquare, X, Send, User, Bot, Loader2, Sparkles, Phone, Mail, ArrowRight } from 'lucide-react';

interface Message {
  id: number;
  sessionId: string;
  senderType: 'customer' | 'ai' | 'agent';
  message: string;
  createdAt: string;
}

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

export function ChatbotWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [session, setSession] = useState<any | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(false);

  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Initialize unique session UUID
  useEffect(() => {
    let id = localStorage.getItem('wild_dubai_chat_session_id');
    if (!id) {
      id = 'sess_' + Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
      localStorage.setItem('wild_dubai_chat_session_id', id);
    }
    setSessionId(id);
  }, []);

  // Fetch or create session once Session ID is resolved
  useEffect(() => {
    if (!sessionId) return;

    fetch(`${API_BASE_URL}/chat/sessions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId }),
    })
      .then((res) => res.json())
      .then((json) => {
        if (json.success) {
          setSession(json.data);
          fetchMessages(json.data.id);
        }
      })
      .catch((err) => console.error('Failed to init chat session:', err));
  }, [sessionId]);

  // Polling for new messages in live sessions
  useEffect(() => {
    if (!session) return;

    const interval = setInterval(() => {
      fetchMessages(session.id);
      // Fetch session status changes
      fetch(`${API_BASE_URL}/chat/sessions`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId: session.id }),
      })
        .then(res => res.json())
        .then(json => {
          if (json.success) setSession(json.data);
        })
        .catch(err => console.error('Error polling status:', err));
    }, 3000);

    return () => clearInterval(interval);
  }, [session?.id]);

  // Auto-scroll messages list
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages.length, isOpen]);

  const fetchMessages = async (id: string) => {
    try {
      const res = await fetch(`${API_BASE_URL}/chat/sessions/${id}/messages`);
      const json = await res.json();
      if (json.success) {
        setMessages(json.data);
      }
    } catch (err) {
      console.error('Error loading chat messages:', err);
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputText.trim() || !session) return;

    const text = inputText.trim();
    setInputText('');
    setLoading(true);

    // Optimistically add client message
    const tempMsg: Message = {
      id: Date.now(),
      sessionId: session.id,
      senderType: 'customer',
      message: text,
      createdAt: new Date().toISOString(),
    };
    setMessages((prev) => [...prev, tempMsg]);

    try {
      const res = await fetch(`${API_BASE_URL}/chat/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId: session.id,
          senderType: 'customer',
          message: text,
        }),
      });
      const json = await res.json();
      if (json.success) {
        await fetchMessages(session.id);
      }
    } catch (err) {
      console.error('Failed to send message:', err);
    } finally {
      setLoading(false);
    }
  };

  // Helper to send text option directly (MCQ clicks)
  const handleSendDirectOption = async (optionText: string) => {
    if (!session) return;
    setLoading(true);

    const tempMsg: Message = {
      id: Date.now(),
      sessionId: session.id,
      senderType: 'customer',
      message: optionText,
      createdAt: new Date().toISOString(),
    };
    setMessages((prev) => [...prev, tempMsg]);

    try {
      const res = await fetch(`${API_BASE_URL}/chat/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          sessionId: session.id,
          senderType: 'customer',
          message: optionText,
        }),
      });
      const json = await res.json();
      if (json.success) {
        await fetchMessages(session.id);
      }
    } catch (err) {
      console.error('Failed to send direct option:', err);
    } finally {
      setLoading(false);
    }
  };

  const lastMessage = messages[messages.length - 1];
  const isNamePrompt = lastMessage?.senderType === 'ai' && lastMessage?.message === 'Enter your name';
  const isContactPrompt = lastMessage?.senderType === 'ai' && lastMessage?.message === 'Enter your email or phone number';
  const isInterestPrompt = lastMessage?.senderType === 'ai' && lastMessage?.message === 'What type of property interest do you have?';
  
  // Show "Connecting to broker..." only if waiting for agent AND unassigned
  const showConnectingLoader = session?.status === 'waiting_agent' && !session?.assignedAgentId;

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end font-sans">
      {/* Chat Window Panel */}
      {isOpen && (
        <div className="w-80 sm:w-96 h-[500px] bg-white border border-gray-200 rounded-[2rem] shadow-[0_20px_50px_rgba(13,28,50,0.15)] flex flex-col overflow-hidden mb-4 transition-all duration-300 animate-in slide-in-from-bottom-5">
          {/* Header */}
          <div className="bg-white border-b border-gray-100 px-6 py-4 flex justify-between items-center shrink-0">
            <div className="flex items-center gap-2.5">
              <div className="relative">
                <div className="w-8 h-8 rounded-full bg-[#098E4B]/10 border border-[#098E4B]/20 flex items-center justify-center">
                  <Sparkles className="w-4 h-4 text-[#098E4B]" />
                </div>
                <div className="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 rounded-full border-2 border-white animate-pulse" />
              </div>
              <div>
                <p className="text-xs font-bold text-[#111111] tracking-wide">Wild Dubai Concierge</p>
                <p className="text-[9px] text-gray-500 font-mono tracking-wider">
                  {session?.status === 'active_agent' ? 'Sales Agent Online' : 'AI Assistant'}
                </p>
              </div>
            </div>
            <button
              onClick={() => setIsOpen(false)}
              className="p-1.5 rounded-full bg-gray-100 hover:bg-gray-200 text-gray-400 hover:text-[#111111] transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          {/* Chat Body Container */}
          <div className="flex-grow overflow-y-auto p-6 space-y-4 flex flex-col min-h-0 bg-[#FBFBFA]">
            {messages.map((m, index) => {
              const isClient = m.senderType === 'customer';
              const isAgent = m.senderType === 'agent';

              return (
                <div
                  key={m.id || index}
                  className={`flex items-start gap-2.5 max-w-[85%] ${
                    isClient ? 'self-end flex-row-reverse ml-auto' : 'self-start mr-auto'
                  }`}
                >
                  <div
                    className={`w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 ${
                      isClient
                        ? 'bg-[#098E4B] text-white shadow-sm'
                        : isAgent
                        ? 'bg-blue-500/10 border border-blue-500/30 text-blue-500'
                        : 'bg-gray-200 text-gray-600 border border-gray-200'
                    }`}
                  >
                    {isClient ? <User className="w-3.5 h-3.5" /> : <Bot className="w-3.5 h-3.5" />}
                  </div>
                  
                  <div className="flex flex-col gap-0.5">
                    <div
                      className={`px-4 py-2.5 rounded-2xl text-xs leading-relaxed shadow-sm ${
                        isClient
                          ? 'bg-[#098E4B] text-white font-semibold rounded-br-none'
                          : 'bg-white border border-gray-150 text-[#111111] rounded-bl-none font-normal'
                      }`}
                    >
                      {m.message}
                    </div>
                    {m.createdAt && (
                      <span className="text-[7px] text-gray-400 font-mono px-1">
                        {new Date(m.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    )}
                  </div>
                </div>
              );
            })}

            {/* Connecting to broker indicator */}
            {showConnectingLoader && (
              <div className="flex items-center gap-2.5 self-start max-w-[80%] bg-emerald-50 border border-emerald-100 px-4 py-3 rounded-2xl">
                <Loader2 className="w-4 h-4 text-[#098E4B] animate-spin shrink-0" />
                <span className="text-[10px] text-emerald-700 font-bold uppercase tracking-wider">
                  Connecting to Broker desk...
                </span>
              </div>
            )}

            {loading && (
              <div className="flex items-center gap-2 self-start max-w-[80%]">
                <div className="w-7 h-7 rounded-full bg-white border border-gray-200 flex items-center justify-center text-[#098E4B]">
                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                </div>
                <span className="text-[10px] text-gray-400 font-mono">Sending...</span>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Footer Routing & Inputs */}
          <div className="p-4 bg-white border-t border-gray-150 space-y-3 shrink-0 shadow-inner">
            
            {/* Step 3 property interest buttons */}
            {session?.status === 'ai_qualifying' && isInterestPrompt ? (
              <div className="flex flex-wrap gap-2 justify-center py-2 animate-in fade-in zoom-in-95 duration-200">
                {['Apartment', 'Villa', 'Penthouse', 'Land', 'Office'].map((opt) => (
                  <button
                    key={opt}
                    onClick={() => handleSendDirectOption(opt)}
                    className="px-3.5 py-2 bg-gray-100 hover:bg-[#098E4B] hover:text-white border border-gray-200 rounded-xl text-xs font-bold transition-all text-[#111111] shadow-sm"
                  >
                    {opt}
                  </button>
                ))}
              </div>
            ) : session?.status === 'closed' || showConnectingLoader ? (
              /* Qualification complete or waiting: show status banner and disable text entries */
              <div className="py-2.5 text-center text-[10px] text-gray-500 font-bold uppercase tracking-wider bg-gray-50 border border-gray-200 rounded-xl">
                {session?.status === 'closed' 
                  ? "Conversation is closed"
                  : "Inputs disabled during routing"
                }
              </div>
            ) : (
              /* Standard chat entries */
              <form onSubmit={handleSendMessage} className="flex gap-2">
                <input
                  type="text"
                  placeholder={
                    session?.status === 'ai_qualifying'
                      ? isNamePrompt
                        ? "Enter your full name..."
                        : isContactPrompt
                        ? "Enter email or phone number..."
                        : "Ask about properties, budget..."
                      : "Type your message..."
                  }
                  value={inputText}
                  onChange={(e) => setInputText(e.target.value)}
                  className="flex-1 bg-gray-50 border border-gray-200 focus:border-[#098E4B] focus:outline-none rounded-xl px-4 py-2.5 text-xs text-[#111111] placeholder-gray-400 transition-colors"
                />
                <button
                  type="submit"
                  disabled={!inputText.trim()}
                  className="p-2.5 bg-[#098E4B] hover:bg-[#07703b] disabled:bg-gray-100 disabled:text-gray-300 text-white rounded-xl transition-colors shrink-0 flex items-center justify-center"
                >
                  <Send className="w-3.5 h-3.5" />
                </button>
              </form>
            )}
          </div>
        </div>
      )}

      {/* Pulsing Widget Button Toggle */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="w-14 h-14 bg-gradient-to-r from-[#098E4B] to-[#07703b] text-white rounded-full shadow-[0_15px_30px_rgba(9,142,75,0.35)] flex items-center justify-center border border-white/20 hover:scale-105 hover:rotate-6 transition-all duration-300 relative group"
      >
        <MessageSquare className="w-6 h-6 text-white transition-transform group-hover:scale-110" />
        <span className="absolute -top-0.5 -right-0.5 w-3.5 h-3.5 bg-[#098E4B] rounded-full border-2 border-white animate-ping" />
        <span className="absolute -top-0.5 -right-0.5 w-3.5 h-3.5 bg-[#098E4B] rounded-full border-2 border-white" />
      </button>
    </div>
  );
}
