import { useState, useRef, useEffect } from "react";
import { MessageCircle, X, Send, Trash2 } from "lucide-react";
import { trackEvent, getSessionData } from "@/lib/analytics";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Progress } from "@/components/ui/progress";
import { supabase } from "@/integrations/supabase/client";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";

interface Message {
  role: "user" | "assistant";
  content: string;
}

interface LeadInfo {
  nome?: string;
  email?: string;
  whatsapp?: string;
  empresa?: string;
  perfil?: string;
  qtde_condominios?: number;
  qtde_atendentes?: number;
  dor_principal?: string;
  volume_mensal_mensagens?: number;
  volume_mensal_documentos?: number;
  departamentos?: number;
  erp_atual?: string;
  precisa_integracao_erp?: boolean;
  modulos_necessarios?: string[];
  urgencia?: string;
  decisor?: boolean;
  orcamento_preliminar?: {
    plano_base: string;
    valor_mensal: number;
    valor_setup: number;
    modulos: Array<{nome: string, valor: number}>;
  };
}

const STORAGE_KEY = 'conexcondo_chat_messages';
const STORAGE_LEAD_KEY = 'conexcondo_chat_lead';

// Carregar mensagens do localStorage
const loadMessagesFromStorage = (): Message[] => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
  } catch (error) {
    console.error('Erro ao carregar mensagens:', error);
  }
  return [{
    role: "assistant",
    content: "Olá! 👋 Sou a Dommi, assistente virtual da ConexCondo. Como posso ajudá-lo hoje?"
  }];
};

// Salvar mensagens no localStorage
const saveMessagesToStorage = (messages: Message[]) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
  } catch (error) {
    console.error('Erro ao salvar mensagens:', error);
  }
};

// Limpar histórico
const clearChatHistory = () => {
  localStorage.removeItem(STORAGE_KEY);
  localStorage.removeItem(STORAGE_LEAD_KEY);
};

const PROACTIVE_DELAY_MS = 5000; // 5 segundos
const PROACTIVE_STORAGE_KEY = 'conexcondo_chat_proactive_shown';

const ChatWidget = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>(loadMessagesFromStorage());
  const [input, setInput] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [leadInfo, setLeadInfo] = useState<LeadInfo>({});
  const [leadSaved, setLeadSaved] = useState(false);
  const [showProactiveBubble, setShowProactiveBubble] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  // Auto-salvar mensagens quando mudarem
  useEffect(() => {
    if (messages.length > 0) {
      saveMessagesToStorage(messages);
    }
  }, [messages]);

  // Salvar leadInfo quando mudar
  useEffect(() => {
    if (Object.keys(leadInfo).length > 0) {
      try {
        localStorage.setItem(STORAGE_LEAD_KEY, JSON.stringify(leadInfo));
      } catch (error) {
        console.error('Erro ao salvar lead info:', error);
      }
    }
  }, [leadInfo]);

  // Carregar leadInfo ao montar
  useEffect(() => {
    try {
      const stored = localStorage.getItem(STORAGE_LEAD_KEY);
      if (stored) {
        setLeadInfo(JSON.parse(stored));
      }
    } catch (error) {
      console.error('Erro ao carregar lead info:', error);
    }
  }, []);

  // Chat proativo - abrir automaticamente após 5 segundos
  useEffect(() => {
    // Não mostrar se já foi mostrado antes ou se o chat já está aberto
    const wasProactiveShown = sessionStorage.getItem(PROACTIVE_STORAGE_KEY);
    if (wasProactiveShown || isOpen) return;

    const timer = setTimeout(() => {
      // Verificar novamente se não está aberto
      if (!isOpen) {
        setShowProactiveBubble(true);
        sessionStorage.setItem(PROACTIVE_STORAGE_KEY, 'true');
        trackEvent('chat_proactive_shown', 'engagement', 'Chat Widget Proactive');
      }
    }, PROACTIVE_DELAY_MS);

    return () => clearTimeout(timer);
  }, [isOpen]);

  // Listen for prefilled question events from FAQ page
  useEffect(() => {
    const handlePrefill = (event: CustomEvent) => {
      if (event.detail?.question) {
        setInput(event.detail.question);
      }
    };

    window.addEventListener('chat-prefill', handlePrefill as EventListener);
    return () => {
      window.removeEventListener('chat-prefill', handlePrefill as EventListener);
    };
  }, []);

  // Extrair informações do lead da conversa
  const extractLeadInfo = (messages: Message[]): LeadInfo => {
    const conversation = messages.map(m => m.content).join('\n');
    
    const info: LeadInfo = {};
    
    // Nome - Múltiplas estratégias de extração
    // Estratégia 1: Buscar por frases completas
    let nomeMatch = conversation.match(/(?:meu nome é|me chamo|sou)\s+([A-ZÁÉÍÓÚÂÊÔÃÕÇ][a-záéíóúâêîôãõç]+(?:\s+[A-ZÁÉÍÓÚÂÊÔÃÕÇ][a-záéíóúâêîôãõç]+)*)/i);
    
    // Estratégia 2: Se não encontrar, buscar após pergunta sobre nome
    if (!nomeMatch) {
      const nomeContext = conversation.match(/qual\s+(?:o\s+|é\s+o\s+)?seu nome[^?]*\?[^\n]*[\n\r]+([A-ZÁÉÍÓÚÂÊÔÃÕÇ][a-záéíóúâêîôãõç]+(?:\s+[A-ZÁÉÍÓÚÂÊÔÃÕÇ][a-záéíóúâêîôãõç]+)*)/i);
      if (nomeContext) nomeMatch = [nomeContext[0], nomeContext[1]];
    }
    
    // Estratégia 3: Buscar mensagens curtas do usuário (provável nome)
    if (!nomeMatch) {
      const userMessages = messages.filter(m => m.role === 'user');
      for (const msg of userMessages) {
        const words = msg.content.trim().split(/\s+/);
        if (words.length >= 1 && words.length <= 3) {
          const allCapitalized = words.every(w => /^[A-ZÁÉÍÓÚÂÊÔÃÕÇ][a-záéíóúâêîôãõç]+$/.test(w));
          if (allCapitalized && msg.content.length > 2) {
            info.nome = msg.content.trim();
            break;
          }
        }
      }
    } else {
      info.nome = nomeMatch[1].trim();
    }
    
    // Email
    const emailMatch = conversation.match(/[\w.+-]+@[\w-]+\.[\w.-]+/);
    if (emailMatch) info.email = emailMatch[0];
    
    // WhatsApp - formatos: (51) 3199-8849, 5131998849, 51 3199-8849, 5192780284
    const whatsappMatch = conversation.match(/\b(?:\(?\d{2}\)?\s?)?\d{8,9}\b/);
    if (whatsappMatch) {
      const digits = whatsappMatch[0].replace(/\D/g, '');
      // Validar que tem 10 ou 11 dígitos (com DDD)
      if (digits.length >= 10 && digits.length <= 11) {
        info.whatsapp = digits;
      }
    }
    
    // Empresa
    const empresaMatch = conversation.match(/(?:empresa|trabalho na|atuo na)\s+([A-Za-zÀ-ú\s&.]+?)(?:\.|,|!|\?|$)/i);
    if (empresaMatch) info.empresa = empresaMatch[1].trim();
    
    // Perfil
    const perfilMatch = conversation.match(/(?:sou|atuo como|trabalho como|função)\s+(?:um\s+|uma\s+)?(síndico|administradora|imobiliária|zelador|gestor|gerente)/i);
    if (perfilMatch) info.perfil = perfilMatch[1].toLowerCase();
    
    // Quantidade de condomínios
    const condominiosMatch = conversation.match(/(\d+)\s+condomínios?/i);
    if (condominiosMatch) info.qtde_condominios = parseInt(condominiosMatch[1]);
    
    // Quantidade de atendentes
    const atendentesMatch = conversation.match(/(\d+)\s+(?:atendentes?|pessoas no atendimento|funcionários)/i);
    if (atendentesMatch) info.qtde_atendentes = parseInt(atendentesMatch[1]);
    
    // Dor principal - procura por palavras-chave de dor
    const dorKeywords = ['problema', 'dificuldade', 'desafio', 'dor', 'sofre', 'precisa', 'melhorar', 'demora', 'retrabalho', 'sobrecarregado'];
    for (const keyword of dorKeywords) {
      const dorMatch = conversation.match(new RegExp(`${keyword}[^.!?]*[.!?]`, 'i'));
      if (dorMatch && !info.dor_principal) {
        info.dor_principal = dorMatch[0].trim();
      }
    }

    // Volume de mensagens por mês
    const volumeMsgMatch = conversation.match(/(\d+)\s+(?:mensagens?|atendimentos?)\s+(?:por dia|diárias?|dia)/i);
    if (volumeMsgMatch) info.volume_mensal_mensagens = parseInt(volumeMsgMatch[1]) * 30;

    // Volume de documentos
    const volumeDocMatch = conversation.match(/(\d+)\s+(?:documentos?|notas? fiscais?)\s+(?:por mês|mensais?|mês)/i);
    if (volumeDocMatch) info.volume_mensal_documentos = parseInt(volumeDocMatch[1]);

    // Departamentos
    const deptMatch = conversation.match(/(\d+)\s+(?:departamentos?|setores?)/i);
    if (deptMatch) info.departamentos = parseInt(deptMatch[1]);

    // ERP atual
    const erpMatch = conversation.match(/(?:uso|usamos|temos|trabalho com)\s+(?:o\s+)?(SAMI|Imobiliar|SuperLógica|CondoMob|SIM|Systemar|Almah)/i);
    if (erpMatch) info.erp_atual = erpMatch[1];

    // Integração ERP
    if (/integra[rç]|conectar|sincronizar/i.test(conversation) && /erp|sistema/i.test(conversation)) {
      info.precisa_integracao_erp = true;
    }

    // Módulos necessários (detecta palavras-chave nas dores)
    const modulos: string[] = [];
    if (/(?:chamado|ticket|manutenção|solicitação)/i.test(conversation)) modulos.push('tickets');
    if (/(?:CRM|venda|locação|lead)/i.test(conversation)) modulos.push('crm');
    if (/(?:nota fiscal|documento|arquivo|PDF)/i.test(conversation)) modulos.push('documentos');
    if (/(?:boleto|envio|comunicado|transmissão)/i.test(conversation)) modulos.push('sender');
    if (/(?:inatividade|morador não responde|sem resposta)/i.test(conversation)) modulos.push('inatividade');
    if (/(?:cobrança|inadimplência)/i.test(conversation)) modulos.push('cobranca');
    info.modulos_necessarios = modulos.length > 0 ? modulos : undefined;

    // Urgência
    if (/(?:urgente|imediato|rápido|já|agora|hoje)/i.test(conversation)) {
      info.urgencia = 'imediata';
    } else if (/(?:30 dias|mês|próximo mês|breve)/i.test(conversation)) {
      info.urgencia = '30_dias';
    } else if (/(?:90 dias|3 meses|trimestre)/i.test(conversation)) {
      info.urgencia = '90_dias';
    }

    // Decisor
    if (/(?:tomo a decisão|decido|sou (?:o|a) responsável|decisor)/i.test(conversation)) {
      info.decisor = true;
    } else if (/(?:preciso apresentar|diretoria|aprovação|superior)/i.test(conversation)) {
      info.decisor = false;
    }

    // Extrai orçamento preliminar se mencionado na conversa
    const orcamentoMatch = conversation.match(/ORÇAMENTO PRELIMINAR[\s\S]*?Plano Base:\s*(\w+)[\s\S]*?R\$\s*([\d.,]+)\/mês/i);
    if (orcamentoMatch) {
      const modulosText = conversation.match(/Módulos Recomendados:([\s\S]*?)Setup Inicial/i);
      const modulos: Array<{nome: string, valor: number}> = [];
      if (modulosText) {
        const moduloMatches = modulosText[1].matchAll(/→\s*([^:]+):\s*R\$\s*([\d.,]+)/g);
        for (const match of moduloMatches) {
          modulos.push({
            nome: match[1].trim(),
            valor: parseFloat(match[2].replace(',', '.'))
          });
        }
      }
      const setupMatch = conversation.match(/Total Setup:\s*R\$\s*([\d.,]+)/i);
      
      info.orcamento_preliminar = {
        plano_base: orcamentoMatch[1],
        valor_mensal: parseFloat(orcamentoMatch[2].replace('.', '').replace(',', '.')),
        valor_setup: setupMatch ? parseFloat(setupMatch[1].replace('.', '').replace(',', '.')) : 0,
        modulos
      };
    }
    
    return info;
  };

  // Salvar lead quando houver informações suficientes
  const saveLeadIfQualified = async (currentMessages: Message[]) => {
    if (leadSaved) {
      console.log('✅ Lead já foi salvo anteriormente');
      return;
    }
    
    const extracted = extractLeadInfo(currentMessages);
    console.log('📊 Informações extraídas:', extracted);
    setLeadInfo(extracted);
    
    if (extracted.nome && (extracted.email || extracted.whatsapp)) {
      console.log('✅ Lead qualificado! Salvando...');
      try {
        const sessionData = getSessionData();
        const body = {
          ...extracted,
          conversa_completa: currentMessages,
          url_origem: window.location.href,
          session_id: sessionData.sessionId,
          origem: 'chat_widget',
          ...sessionData.utmParams
        };
        console.log('📤 Payload para save-lead:', body);
        
        const { data, error } = await supabase.functions.invoke('save-lead', {
          body
        });
        
        if (error) {
          console.error('❌ Erro ao salvar lead:', error);
          return;
        }
        
        setLeadSaved(true);
        console.log('✅ Lead salvo com sucesso:', data);
        trackEvent('lead_captured', 'conversion', 'Chat Widget', data?.lead?.score_qualificacao, {
          lead_id: data?.lead?.id,
          score: data?.lead?.score_qualificacao
        });
      } catch (error) {
        console.error('❌ Exceção ao salvar lead:', error);
      }
    } else {
      console.log('⚠️ Lead não qualificado ainda:', {
        temNome: !!extracted.nome,
        temEmail: !!extracted.email,
        temWhatsapp: !!extracted.whatsapp
      });
    }
  };

  // Calcular progresso da qualificação
  const calculateProgress = () => {
    const fields = ['nome', 'email', 'whatsapp', 'empresa', 'perfil', 'qtde_condominios', 'qtde_atendentes', 'dor_principal'];
    const completed = fields.filter(f => leadInfo[f as keyof LeadInfo]).length;
    return (completed / fields.length) * 100;
  };

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

    const userMessage: Message = { role: "user", content: input };
    const updatedMessages = [...messages, userMessage];
    setMessages(updatedMessages);
    setInput("");
    setIsLoading(true);
    
    trackEvent('chat_message_sent', 'engagement', 'Chat Widget', updatedMessages.length);

    try {
      const { data, error } = await supabase.functions.invoke('chat', {
        body: { messages: updatedMessages }
      });

      if (error) throw error;

      const finalMessages: Message[] = [...updatedMessages, { role: "assistant" as const, content: data.response }];
      setMessages(finalMessages);
      
      // Extrair e salvar informações do lead após cada resposta
      await saveLeadIfQualified(finalMessages);
    } catch (error) {
      console.error('Error sending message:', error);
      setMessages(prev => [...prev, { 
        role: "assistant", 
        content: "Desculpe, ocorreu um erro. Por favor, tente novamente ou entre em contato pelo WhatsApp (51) 3199-8849." 
      }]);
    } finally {
      setIsLoading(false);
    }
  };

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

  const toggleChat = () => {
    const newState = !isOpen;
    setIsOpen(newState);
    if (newState) {
      trackEvent('chat_opened', 'engagement', 'Chat Widget', undefined, {
        page: window.location.pathname
      });
    } else {
      trackEvent('chat_closed', 'engagement', 'Chat Widget', undefined, {
        messages_count: messages.length
      });
    }
  };

  const handleQuickReply = (question: string) => {
    setInput(question);
    setTimeout(() => {
      sendMessage();
    }, 100);
  };

  const quickReplies = [
    "Como contratar?",
    "Quais os preços?",
    "Integra com meu ERP?"
  ];

  // Fechar bubble proativa quando abrir o chat
  const handleOpenChat = () => {
    setShowProactiveBubble(false);
    setIsOpen(true);
    trackEvent('chat_opened', 'engagement', 'Chat Widget', undefined, {
      page: window.location.pathname,
      proactive: true
    });
  };

  return (
    <>
      {/* Chat Button com Bubble Proativa */}
      {!isOpen && (
        <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2">
          {/* Bubble de mensagem proativa */}
          {showProactiveBubble && (
            <div 
              className="relative bg-card border border-border shadow-lg rounded-lg p-3 max-w-[260px] animate-fade-in cursor-pointer"
              onClick={handleOpenChat}
            >
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setShowProactiveBubble(false);
                  trackEvent('chat_proactive_dismissed', 'engagement', 'Chat Widget Proactive');
                }}
                className="absolute -top-2 -right-2 w-5 h-5 bg-muted hover:bg-muted-foreground/20 rounded-full flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors"
              >
                <X className="w-3 h-3" />
              </button>
              <p className="text-sm text-foreground font-medium">
                👋 Olá! Posso ajudar você a reduzir 60% do tempo de atendimento?
              </p>
              <div className="absolute -bottom-2 right-6 w-4 h-4 bg-card border-r border-b border-border transform rotate-45" />
            </div>
          )}
          
          <Button
            onClick={handleOpenChat}
            data-chat-widget
            className="h-14 w-14 rounded-full shadow-lg"
            size="icon"
          >
            <MessageCircle className="h-6 w-6" />
          </Button>
        </div>
      )}

      {/* Chat Window */}
      {isOpen && (
        <Card className="fixed bottom-4 right-4 w-full max-w-md max-h-[85vh] md:max-h-[600px] shadow-2xl z-50 flex flex-col overflow-hidden mx-4 md:mx-0">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4 border-b bg-gradient-primary text-white">
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Avatar className="w-12 h-12 border-2 border-white/30">
                  <AvatarImage src="/images/dommi-avatar.png" alt="Dommi" />
                  <AvatarFallback>DM</AvatarFallback>
                </Avatar>
                <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-400 rounded-full border-2 border-white" />
              </div>
              <div>
                <CardTitle className="text-base text-white">Dommi</CardTitle>
                <p className="text-xs text-white/80">Assistente Virtual • Online</p>
              </div>
            </div>
            <div className="flex items-center gap-1">
              {leadInfo.nome && (leadInfo.email || leadInfo.whatsapp) && !leadSaved && (
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={async () => {
                    console.log('💾 Salvamento manual iniciado');
                    await saveLeadIfQualified(messages);
                  }}
                  className="text-white hover:bg-white/20 text-xs px-2"
                  title="Salvar lead manualmente"
                >
                  💾
                </Button>
              )}
              <Button
                variant="ghost"
                size="icon"
                onClick={() => {
                  if (confirm('Deseja limpar o histórico da conversa?')) {
                    clearChatHistory();
                    setMessages([{
                      role: "assistant",
                      content: "Olá! 👋 Sou a Dommi, assistente virtual da ConexCondo. Como posso ajudá-lo hoje?"
                    }]);
                    setLeadInfo({});
                    setLeadSaved(false);
                  }
                }}
                className="text-white hover:bg-white/20"
                title="Limpar histórico"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setIsOpen(false)}
                className="text-white hover:bg-white/20"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent className="flex-1 flex flex-col p-0 overflow-hidden">
            {/* Indicador de progresso da qualificação */}
            {leadInfo.nome && (
              <div className="p-3 border-b bg-muted/30">
                <div className="flex items-center justify-between text-xs text-muted-foreground mb-1.5">
                  <span className="font-medium">Qualificação do Lead</span>
                  <span>{Math.round(calculateProgress())}%</span>
                </div>
                <Progress value={calculateProgress()} className="h-1.5" />
              </div>
            )}
            <ScrollArea className="flex-1 p-4 max-h-[400px] overflow-y-auto" ref={scrollRef}>
              <div className="space-y-4">
                {messages.map((message, index) => (
                  <div
                    key={index}
                    className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
                  >
                    {message.role === 'assistant' && (
                      <Avatar className="w-8 h-8 mr-2 flex-shrink-0">
                        <AvatarImage src="/images/dommi-avatar.png" alt="Dommi" />
                        <AvatarFallback>DM</AvatarFallback>
                      </Avatar>
                    )}
                <div
                  className={`max-w-[75%] rounded-lg px-4 py-2 ${
                    message.role === 'user'
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-muted text-foreground'
                  }`}
                >
                  <p className="text-sm whitespace-pre-wrap break-words overflow-wrap-anywhere">{message.content}</p>
                </div>
                  </div>
                ))}
                {isLoading && (
                  <div className="flex items-center justify-start">
                    <Avatar className="w-8 h-8 mr-2 flex-shrink-0">
                      <AvatarImage src="/images/dommi-avatar.png" alt="Dommi" />
                      <AvatarFallback>DM</AvatarFallback>
                    </Avatar>
                    <div className="bg-muted rounded-lg px-4 py-3">
                      <div className="flex items-center space-x-2">
                        <span className="text-xs text-muted-foreground">Dommi está digitando</span>
                        <div className="flex space-x-1">
                          <div className="w-2 h-2 bg-primary/50 rounded-full animate-bounce" />
                          <div className="w-2 h-2 bg-primary/50 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
                          <div className="w-2 h-2 bg-primary/50 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </ScrollArea>
            
            {/* Quick Replies - mostra apenas na primeira mensagem */}
            {messages.length === 1 && !isLoading && (
              <div className="px-4 pb-2 border-t pt-3">
                <p className="text-xs text-muted-foreground mb-2">Perguntas populares:</p>
                <div className="flex flex-wrap gap-2">
                  {quickReplies.map((reply, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      size="sm"
                      onClick={() => handleQuickReply(reply)}
                      className="text-xs h-7"
                    >
                      {reply}
                    </Button>
                  ))}
                </div>
              </div>
            )}

            <div className="p-4 border-t">
              <div className="flex space-x-2">
                <Input
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="Digite sua mensagem..."
                  disabled={isLoading}
                  className="flex-1"
                />
                <Button
                  onClick={sendMessage}
                  disabled={isLoading || !input.trim()}
                  size="icon"
                >
                  <Send className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </>
  );
};

export default ChatWidget;
