'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { Message, Conversation } from '@/lib/db';
import { MessageBubble, isSameDay, getDateLabel } from './MessageBubble';
import { DeleteModal } from './DeleteModal';

function getAvatarColor(name: string): string {
  const colors = ['#1faa59', '#8b5cf6', '#0ea5e9', '#f59e0b', '#f1647c'];
  let hash = 0;
  for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
  return colors[Math.abs(hash) % colors.length];
}

function getInitials(name: string): string {
  return name.split(' ').filter(Boolean).map((w) => w[0]).join('').toUpperCase().slice(0, 2);
}

interface ConversationPanelProps {
  conversation: Conversation | null;
  onDelete: (id: number) => void;
  onBackMobile: () => void;
}

export function ConversationPanel({ conversation, onDelete, onBackMobile }: ConversationPanelProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [mode, setMode] = useState<'AI' | 'HUMAN'>('AI');
  const [newMessage, setNewMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  const [showQuickPanel, setShowQuickPanel] = useState(false);
  const [quickReplies, setQuickReplies] = useState<Array<{ id: string; shortcut: string; text: string }>>([]);

  useEffect(() => {
    const fetchQuickReplies = async () => {
      try {
        const res = await fetch('/api/settings');
        const data = await res.json();
        if (res.ok) setQuickReplies(data.quick_replies || []);
      } catch (err) {
        console.error('Error fetching quick replies:', err);
      }
    };
    fetchQuickReplies();
  }, []);

  useEffect(() => {
    if (!conversation) {
      setMessages([]);
      setMode('AI');
      return;
    }
    setMode(conversation.mode);
    fetchMessages();
    const interval = setInterval(fetchMessages, 2000);
    return () => clearInterval(interval);
  }, [conversation?.id, conversation?.mode]);

  useEffect(() => {
    const scrollToBottom = () => {
      if (scrollRef.current) {
        scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
      }
    };
    scrollToBottom();
    const timer = setTimeout(scrollToBottom, 60);
    return () => clearTimeout(timer);
  }, [messages]);

  const fetchMessages = async () => {
    if (!conversation?.id) return;
    try {
      const res = await fetch(`/api/messages/${conversation.id}`);
      const data = await res.json();
      setMessages(data);
    } catch (err) {
      console.error('Error fetching messages:', err);
    }
  };

  const fetchMode = async () => {
    if (!conversation?.id) return;
    try {
      const res = await fetch(`/api/mode/${conversation.id}`);
      const data = await res.json();
      if (data.mode && data.mode !== mode) setMode(data.mode);
    } catch (err) {
      console.error('Error fetching mode:', err);
    }
  };

  useEffect(() => {
    // Solo depende del ID — no de 'mode' para evitar restart innecesario
    if (!conversation?.id) return;
    const modeInterval = setInterval(fetchMode, 3000);
    return () => clearInterval(modeInterval);
  }, [conversation?.id]);

  const handleSendMessage = useCallback(async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!newMessage.trim() || !conversation?.id) return;

    setLoading(true);
    setError('');

    try {
      const res = await fetch(`/api/messages/${conversation.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: newMessage }),
      });

      if (res.ok) {
        setNewMessage('');
        // Reset textarea height
        const textarea = document.getElementById('messageInput') as HTMLTextAreaElement;
        if (textarea) { textarea.style.height = 'auto'; }
        await fetchMessages();
      } else {
        const data = await res.json();
        setError(data.error || 'Error al enviar');
      }
    } catch {
      setError('Error de conexión al enviar');
    } finally {
      setLoading(false);
    }
  }, [newMessage, conversation?.id]);

  const handleDelete = async () => {
    if (!conversation) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/conversations/${conversation.id}`, { method: 'DELETE' });
      if (res.ok) {
        setShowDeleteModal(false);
        onDelete(conversation.id);
      } else {
        setError('Error al eliminar la conversación');
      }
    } catch {
      setError('Error de conexión al intentar eliminar');
    } finally {
      setDeleting(false);
    }
  };

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

  if (!conversation) {
    return (
      <div id="emptyChat" className="empty-chat">
        <div className="orb orb-pulse">
          <svg width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.6" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M8 10h8M8 14h5M21 12a8 8 0 01-11.6 7.1L3 21l1.9-6.4A8 8 0 1121 12z" />
          </svg>
        </div>
        <h3>Selecciona una conversación</h3>
        <p>Elige un chat de la bandeja para ver el historial y alternar entre modo IA y humano.</p>
        <div className="empty-hints">
          <span className="empty-hint-pill">💬 Mensajes en tiempo real</span>
          <span className="empty-hint-pill">🤖 Modo IA / 👤 Humano</span>
          <span className="empty-hint-pill">⚡ Respuestas rápidas</span>
        </div>
      </div>
    );
  }

  const displayName = conversation.name || conversation.phone.split('@')[0];

  return (
    <>
      <header className="chat-header" id="chatHeader">
        <div className="chat-contact">
          <button type="button" className="back-mobile" id="backMobile" onClick={onBackMobile}>Chats</button>
          <div className="avatar avatar-sm" id="chatAvatar" style={{ background: getAvatarColor(displayName) }}>
            {getInitials(displayName)}
          </div>
          <div>
            <h3 id="chatName">{displayName}</h3>
            <p id="chatPhone">{conversation.phone.split('@')[0]}</p>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <div className="mode-switcher">
            <span id="modeLabel">{mode === 'AI' ? 'Modo IA' : 'Modo Humano'}</span>
            <button
              type="button"
              className={`toggle ${mode === 'AI' ? 'ai' : 'human'}`}
              id="modeToggle"
              aria-label="Cambiar modo"
              onClick={() => handleModeChange(mode === 'AI' ? 'HUMAN' : 'AI')}
            />
          </div>
          <button
            onClick={() => setShowDeleteModal(true)}
            className="icon-btn"
            title="Borrar conversación"
            style={{ border: 'none', background: 'transparent' }}
          >
            <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        </div>
      </header>

      <div className="messages" id="messagesWrap" ref={scrollRef}>
        {messages.map((msg, i) => {
          const prev = messages[i - 1];
          const showSep = !prev || !isSameDay(prev.created_at, msg.created_at);
          return (
            <MessageBubble
              key={msg.id}
              message={msg}
              showDateSeparator={showSep}
              dateLabel={showSep ? getDateLabel(msg.created_at) : undefined}
            />
          );
        })}
      </div>

      <div className="composer" id="composerArea">
        <div className={`ai-banner ${mode === 'AI' ? 'show' : ''}`} id="aiBanner">
          <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M13 2L4.5 13.5H11l-1 8.5 8.5-11.5H12l1-8.5z" />
          </svg>
          <span>Modo IA activo. El bot responde automaticamente.</span>
        </div>

        {showQuickPanel && mode === 'HUMAN' && (
          <div className="panel" style={{ marginBottom: '14px', padding: '16px', borderRadius: 'var(--radius)', maxHeight: '200px', overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px', fontSize: '0.75rem', fontWeight: 800, color: 'var(--text-muted)' }}>
              <span style={{ color: 'var(--accent)' }}>⚡ Respuestas Rápidas</span>
              <button type="button" onClick={() => setShowQuickPanel(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)' }}>Cerrar</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: '8px' }}>
              {quickReplies.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => { setNewMessage(item.text); setShowQuickPanel(false); }}
                  className="quick-card"
                  style={{ textAlign: 'left', cursor: 'pointer', margin: 0 }}
                >
                  <span className="shortcut">{item.shortcut}</span>
                  <p style={{ margin: 0, textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>{item.text}</p>
                </button>
              ))}
            </div>
          </div>
        )}

        <form onSubmit={handleSendMessage} className={`composer-form ${mode === 'AI' ? 'hidden' : ''}`} id="composerForm">
          <button
            type="button"
            onClick={() => setShowQuickPanel(!showQuickPanel)}
            className="icon-btn"
            style={{ width: '46px', height: '46px', borderRadius: 'var(--radius-sm)', border: showQuickPanel ? '1px solid var(--accent)' : '1px solid var(--border)', color: showQuickPanel ? 'var(--accent)' : 'var(--text-dim)' }}
            title="Respuestas Rápidas"
          >
            ⚡
          </button>
          <textarea
            id="messageInput"
            rows={1}
            value={newMessage}
            onChange={(e) => {
              setNewMessage(e.target.value);
              // Auto-resize
              const t = e.currentTarget;
              t.style.height = 'auto';
              t.style.height = `${Math.min(t.scrollHeight, 120)}px`;
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
              }
            }}
            placeholder="Escribe como agente humano… (Enter para enviar)"
            disabled={loading}
          />
          <button type="submit" className="send-btn" aria-label="Enviar" disabled={loading || !newMessage.trim()}>
            {loading ? (
              <div className="spinner-epic" style={{ width: '16px', height: '16px', borderWidth: '2px', borderTopColor: '#fff' }} />
            ) : (
              <svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
              </svg>
            )}
          </button>
        </form>
      </div>

      <DeleteModal isOpen={showDeleteModal} onClose={() => setShowDeleteModal(false)} onConfirm={handleDelete} loading={deleting} />
    </>
  );
}
