'use client';

import { useState, useEffect, useRef } from 'react';

interface SimMessage {
  id: number;
  conversation_id: number;
  role: 'user' | 'assistant' | 'human';
  content: string;
  created_at: number;
}

interface SimConvo {
  id: number;
  phone: string;
  name: string;
  mode: 'AI' | 'HUMAN';
}

export function SimulatorPanel() {
  const [convo, setConvo] = useState<SimConvo | null>(null);
  const [messages, setMessages] = useState<SimMessage[]>([]);
  const [mode, setMode] = useState<'AI' | 'HUMAN'>('AI');
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const endRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    endRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 1. Cargar metadatos de la conversación de simulación
  const fetchConvoDetails = async () => {
    try {
      const res = await fetch('/api/simulator');
      const data = await res.json();
      if (data.id) {
        setConvo(data);
        setMode(data.mode);
      }
    } catch (err) {
      console.error('Error fetching simulator convo:', err);
    } finally {
      setFetching(false);
    }
  };

  // 2. Cargar mensajes de la base de datos para esta conversación
  const fetchMessages = async () => {
    if (!convo?.id) return;
    try {
      const res = await fetch(`/api/messages/${convo.id}`);
      const data = await res.json();
      if (Array.isArray(data)) {
        setMessages(data);
      }
    } catch (err) {
      console.error('Error fetching messages for simulator:', err);
    }
  };

  // 3. Sincronizar el modo en tiempo real
  const fetchMode = async () => {
    if (!convo?.id) return;
    try {
      const res = await fetch(`/api/mode/${convo.id}`);
      const data = await res.json();
      if (data.mode && data.mode !== mode) {
        setMode(data.mode);
      }
    } catch (err) {
      console.error('Error fetching mode for simulator:', err);
    }
  };

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

  useEffect(() => {
    if (!convo?.id) return;
    fetchMessages();
    
    // Polling de mensajes (2s) y modo (3s)
    const msgInterval = setInterval(fetchMessages, 2000);
    const modeInterval = setInterval(fetchMode, 3000);
    
    return () => {
      clearInterval(msgInterval);
      clearInterval(modeInterval);
    };
  }, [convo?.id, mode]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Cambiar el modo de la conversación (AI / HUMAN)
  const handleModeChange = async (newMode: 'AI' | 'HUMAN') => {
    if (!convo?.id) return;
    try {
      const res = await fetch(`/api/mode/${convo.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode: newMode }),
      });
      if (res.ok) {
        setMode(newMode);
      }
    } catch (err) {
      console.error('Error updating mode in simulator:', err);
    }
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || loading || !convo?.id) return;

    const userMsg = input.trim();
    setInput('');
    setLoading(true);

    // Optimistic insert (para UI responsiva)
    const tempId = Date.now();
    const optimisticMsg: SimMessage = {
      id: tempId,
      conversation_id: convo.id,
      role: 'user',
      content: userMsg,
      created_at: Math.floor(Date.now() / 1000)
    };
    setMessages(prev => [...prev, optimisticMsg]);

    try {
      const res = await fetch('/api/simulator', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: userMsg })
      });
      
      if (res.ok) {
        // Recargar mensajes para obtener el ID real de la base de datos
        await fetchMessages();
      }
    } catch (err) {
      console.error(err);
      const errorMsg: SimMessage = {
        id: Date.now() + 1,
        conversation_id: convo.id,
        role: 'assistant',
        content: '❌ Error de red al simular envío.',
        created_at: Math.floor(Date.now() / 1000)
      };
      setMessages(prev => [...prev, errorMsg]);
    } finally {
      setLoading(false);
    }
  };

  if (fetching) {
    return (
      <div style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'center', background: 'var(--bg)', height: '100%' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '12px' }}>
          <div className="spinner-epic" style={{ width: '36px', height: '36px', borderWidth: '3px' }} />
          <span style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>Cargando simulador...</span>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', width: '100%', background: 'var(--bg)' }}>
      {/* Header del Simulador */}
      <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', background: 'var(--panel-bg)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '16px' }}>
        <div>
          <h2 style={{ fontSize: '1.15rem', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '8px', margin: 0 }}>
            🧪 Simulador de Clientes
          </h2>
          <p style={{ fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '4px', margin: 0 }}>
            Escribe un mensaje para simular un cliente de WhatsApp. La IA responderá si su modo está activo.
          </p>
        </div>

        {/* Interruptor de Modo */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', background: 'var(--bg)', padding: '6px 12px', borderRadius: '8px', border: '1px solid var(--border)' }}>
          <span style={{ fontSize: '0.8rem', fontWeight: 600, color: 'var(--text)' }}>
            {mode === 'AI' ? '🤖 Autorespuesta IA' : '👤 Control Humano'}
          </span>
          <button
            type="button"
            className={`toggle ${mode === 'AI' ? 'ai' : 'human'}`}
            onClick={() => handleModeChange(mode === 'AI' ? 'HUMAN' : 'AI')}
            style={{ width: '40px', height: '22px', borderRadius: '11px', position: 'relative', border: 'none', cursor: 'pointer', outline: 'none' }}
          />
        </div>
      </div>

      {/* Área de Mensajes */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '24px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
        {messages.length === 0 && (
          <div style={{ margin: 'auto', textAlign: 'center', color: 'var(--text-muted)', maxWidth: '360px', padding: '24px' }}>
            <p style={{ fontSize: '2.5rem', marginBottom: '16px', margin: 0 }}>👋</p>
            <h4 style={{ color: 'var(--text)', fontSize: '1rem', fontWeight: 600, marginBottom: '8px', margin: 0 }}>¡Bienvenido al simulador!</h4>
            <p style={{ fontSize: '0.82rem', lineHeight: 1.5, margin: 0 }}>
              Prueba a escribir un mensaje como: <br />
              <em style={{ color: 'var(--accent)', fontStyle: 'normal' }}>"Hola, me interesa agendar una demo. Mi correo es juan@agencia.com de la agencia Creativa"</em>
            </p>
          </div>
        )}
        
        {messages.map((m) => {
          const isClient = m.role === 'user';
          const isAi = m.role === 'assistant';
          
          return (
            <div
              key={m.id}
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: isClient ? 'flex-end' : 'flex-start',
                width: '100%'
              }}
            >
              {/* Badge indicando quién responde */}
              <span style={{ fontSize: '0.68rem', color: 'var(--text-muted)', marginBottom: '4px', padding: '0 4px' }}>
                {isClient ? 'Cliente Simulado' : isAi ? '🤖 IA (IgnacIA)' : '👤 Agente Humano'}
              </span>
              
              <div
                style={{
                  maxWidth: '75%',
                  padding: '12px 16px',
                  borderRadius: '12px',
                  background: isClient ? 'var(--accent)' : isAi ? 'var(--panel-bg)' : 'var(--violet-soft)',
                  color: isClient ? '#fff' : 'var(--text)',
                  border: isClient ? 'none' : isAi ? '1px solid var(--border)' : '1px solid var(--violet-border)',
                  boxShadow: 'var(--shadow-sm)'
                }}
              >
                <div style={{ whiteSpace: 'pre-wrap', fontSize: '0.9rem', lineHeight: 1.5 }}>
                  {m.content}
                </div>
              </div>
            </div>
          );
        })}
        {loading && (
          <div style={{ alignSelf: 'flex-start', display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
            <span style={{ fontSize: '0.68rem', color: 'var(--text-muted)', marginBottom: '4px', padding: '0 4px' }}>
              Procesando mensaje...
            </span>
            <div style={{ background: 'var(--panel-bg)', padding: '12px 16px', borderRadius: '12px', border: '1px solid var(--border)' }}>
              <span style={{ fontSize: '0.9rem', color: 'var(--text-muted)' }}>Escribiendo...</span>
            </div>
          </div>
        )}
        <div ref={endRef} />
      </div>

      {/* Banner informativo de modo */}
      <div style={{ padding: '8px 24px', borderTop: '1px solid var(--border)', background: 'var(--bg-soft)', fontSize: '0.78rem', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: '8px' }}>
        <span style={{ color: mode === 'AI' ? 'var(--accent)' : 'var(--violet)' }}>●</span>
        <span>
          {mode === 'AI' 
            ? 'La IA responderá automáticamente aquí y en el chat general.' 
            : 'Modo Humano activo. Las respuestas deben enviarse desde la pestaña "Chats".'
          }
        </span>
      </div>

      {/* Input de Envío */}
      <div style={{ padding: '16px 24px', borderTop: '1px solid var(--border)', background: 'var(--panel-bg)' }}>
        <form onSubmit={handleSend} style={{ display: 'flex', gap: '12px' }}>
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Simular mensaje del cliente..."
            style={{
              flex: 1,
              padding: '12px 16px',
              borderRadius: 'var(--radius)',
              border: '1px solid var(--border)',
              background: 'var(--bg)',
              color: 'var(--text)',
              outline: 'none',
              fontSize: '0.9rem'
            }}
            disabled={loading}
          />
          <button
            type="submit"
            disabled={!input.trim() || loading}
            style={{
              padding: '0 20px',
              background: 'var(--accent)',
              color: '#fff',
              border: 'none',
              borderRadius: 'var(--radius)',
              fontWeight: 600,
              cursor: (!input.trim() || loading) ? 'not-allowed' : 'pointer',
              opacity: (!input.trim() || loading) ? 0.5 : 1,
              fontSize: '0.9rem',
              transition: 'opacity 0.2s'
            }}
          >
            Enviar
          </button>
        </form>
      </div>
    </div>
  );
}
