import type { FC } from 'react';
import { useEffect, useState, useCallback, useRef } from 'react';
import { RefreshCw, MessageSquare, Phone, Search, User, Bot, Headphones, UserPlus, X, Send, ChevronDown } from 'lucide-react';
import Layout from '../components/Layout';
import { Card, Button, Input, EmptyState, Skeleton, toast, Badge, Modal } from '../components/ui';
import { odooApi, type WacrmConversation, type WacrmMessage } from '../services/odoo';

interface Member {
  id: string;
  name: string;
  email?: string;
  avatar_url?: string;
  role: string;
}

const WacrmMessages: FC = () => {
  const [conversations, setConversations] = useState<WacrmConversation[]>([]);
  const [messages, setMessages] = useState<WacrmMessage[]>([]);
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<WacrmConversation | null>(null);
  const [assignOpen, setAssignOpen] = useState(false);
  const [assigning, setAssigning] = useState(false);

  const [replyText, setReplyText] = useState('');
  const [sendingReply, setSendingReply] = useState(false);
  const [currentAgentId, setCurrentAgentId] = useState(() => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('skeen_current_agent_id') || '';
    }
    return '';
  });

  // Refs para evitar loops y dependency churn
  const selectedRef = useRef<WacrmConversation | null>(null);
  const searchRef = useRef(search);
  const userSelectedRef = useRef(false);

  useEffect(() => {
    selectedRef.current = selected;
  }, [selected]);

  useEffect(() => {
    searchRef.current = search;
  }, [search]);

  useEffect(() => {
    if (currentAgentId && typeof window !== 'undefined') {
      localStorage.setItem('skeen_current_agent_id', currentAgentId);
    }
  }, [currentAgentId]);

  const loadConversations = useCallback(async () => {
    try {
      const res = await odooApi.getWacrmConversations(searchRef.current);
      if (res.status === 'success') {
        setConversations(res.conversations);
        const currentSelected = selectedRef.current;
        if (currentSelected) {
          const updated = res.conversations.find((c) => c.external_id === currentSelected.external_id);
          if (updated && updated.external_id !== currentSelected.external_id) {
            // Solo actualizar si realmente cambió la referencia (datos nuevos)
            setSelected(updated);
          }
        } else if (!userSelectedRef.current && res.conversations.length > 0) {
          setSelected(res.conversations[0]);
        }
      }
    } catch (err) {
      toast.error('Error al cargar conversaciones');
      console.error(err);
    }
  }, []);

  const loadMessages = useCallback(async (conversationId: string) => {
    try {
      const res = await odooApi.getWacrmMessages(undefined, conversationId);
      if (res.status === 'success') {
        setMessages(res.messages.reverse());
      }
    } catch (err) {
      toast.error('Error al cargar mensajes');
      console.error(err);
    }
  }, []);

  const loadMembers = useCallback(async () => {
    try {
      const res = await odooApi.getWacrmMembers();
      if (res.status === 'success') {
        setMembers(res.members);
      }
    } catch (err) {
      console.error('Error cargando agentes:', err);
    }
  }, []);

  const sync = async () => {
    try {
      setSyncing(true);
      const res = await odooApi.syncWacrm();
      if (res.status === 'success') {
        toast.success(`Sincronizado: ${JSON.stringify(res.result)}`);
        await loadConversations();
      }
    } catch (err) {
      toast.error('Error al sincronizar con WACRM');
      console.error(err);
    } finally {
      setSyncing(false);
    }
  };

  // Carga inicial
  useEffect(() => {
    let mounted = true;
    const init = async () => {
      setLoading(true);
      await Promise.all([loadConversations(), loadMembers()]);
      if (mounted) setLoading(false);
    };
    init();
    return () => {
      mounted = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Cuando cambia la búsqueda, recargar lista pero no forzar selección
  useEffect(() => {
    loadConversations();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search]);

  // Cargar mensajes cuando cambia la conversación seleccionada
  useEffect(() => {
    if (selected) {
      loadMessages(selected.external_id);
    }
  }, [selected, loadMessages]);

  // Auto-sync cada 15 segundos
  useEffect(() => {
    const interval = setInterval(() => {
      loadConversations();
      const currentSelected = selectedRef.current;
      if (currentSelected) {
        loadMessages(currentSelected.external_id);
      }
    }, 15000);
    return () => clearInterval(interval);
  }, [loadConversations, loadMessages]);

  const handleSelect = useCallback((c: WacrmConversation) => {
    userSelectedRef.current = true;
    setSelected(c);
  }, []);

  const handleSendReply = async () => {
    if (!selected || !replyText.trim()) return;
    if (!currentAgentId) {
      toast.error('Selecciona tu identidad de agente antes de responder');
      return;
    }
    try {
      setSendingReply(true);
      await odooApi.sendWacrmMessage({
        conversation_id: selected.external_id,
        text: replyText.trim(),
        assigned_agent_id: currentAgentId,
      });
      toast.success('Mensaje enviado');
      setReplyText('');
      await loadMessages(selected.external_id);
      await loadConversations();
    } catch (err) {
      toast.error('Error al enviar mensaje');
      console.error(err);
    } finally {
      setSendingReply(false);
    }
  };

  const handleAssign = async (memberId: string | null) => {
    if (!selected) return;
    try {
      setAssigning(true);
      await odooApi.assignWacrmConversation(selected.external_id, memberId);
      toast.success(memberId ? 'Conversación asignada' : 'Conversación desasignada');
      await loadConversations();
      setAssignOpen(false);
    } catch (err) {
      toast.error('Error al asignar conversación');
      console.error(err);
    } finally {
      setAssigning(false);
    }
  };

  const senderIcon = (type: string) => {
    if (type === 'bot') return <Bot size={14} className="text-#3E2C1C" />;
    if (type === 'agent') return <Headphones size={14} className="text-blue-600" />;
    return <User size={14} className="text-[#7A5C44]" />;
  };

  const senderLabel = (type: string) => {
    if (type === 'bot') return 'Sofía (Bot)';
    if (type === 'agent') return 'Agente';
    return 'Cliente';
  };

  const assignedMember = members.find((m) => m.id === selected?.assigned_agent_id);

  return (
    <Layout title="WACRM — Mensajes" subtitle="Conversaciones de WhatsApp sincronizadas">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4 sm:mb-6">
        <div className="relative w-full sm:max-w-sm">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-[#A87B5D]" />
          <Input
            placeholder="Buscar conversación..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-10"
          />
        </div>
        <div className="flex items-center gap-3">
          <div className="relative">
            <select
              value={currentAgentId}
              onChange={(e) => setCurrentAgentId(e.target.value)}
              className="appearance-none bg-homenest-cream-light border border-[#E9D5B7] text-homenest-bark text-sm rounded-lg pl-3 pr-8 py-2 focus:outline-none focus:ring-2 focus:ring-[#3E2C1C]"
            >
              <option value="">Responder como...</option>
              {members.map((m) => (
                <option key={m.id} value={m.id}>{m.name}</option>
              ))}
            </select>
            <ChevronDown size={14} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[#A87B5D] pointer-events-none" />
          </div>
          <Button onClick={sync} loading={syncing}>
            <RefreshCw size={16} className="mr-2" />
            Sincronizar
          </Button>
        </div>
      </div>

      {loading ? (
        <Skeleton count={6} className="h-20 w-full" />
      ) : conversations.length === 0 ? (
        <EmptyState
          title="Sin conversaciones"
          subtitle="No hay conversaciones sincronizadas. Presiona Sincronizar para traer datos de WACRM."
          icon={<MessageSquare size={28} />}
          actionLabel="Sincronizar"
          onAction={sync}
        />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6 h-[calc(100vh-220px)] min-h-[400px]">
          {/* Lista de conversaciones */}
          <Card className="lg:col-span-1 overflow-hidden flex flex-col">
            <Card.Body className="p-0 overflow-y-auto flex-1">
              <div className="divide-y">
                {conversations.map((c) => (
                  <button
                    key={c.external_id}
                    onClick={() => handleSelect(c)}
                    className={`w-full text-left p-3 sm:p-4 transition hover:bg-[#FEF3C7] ${
                      selected?.external_id === c.external_id ? 'bg-[#FEF3C7]' : ''
                    }`}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-homenest-bark truncate">{c.contact_name || 'Desconocido'}</p>
                        <p className="text-xs text-[#7A5C44] flex items-center mt-0.5">
                          <Phone size={10} className="mr-1" />
                          {c.contact_phone || '—'}
                        </p>
                      </div>
                      {c.unread_count > 0 && (
                        <Badge variant="primary">{c.unread_count}</Badge>
                      )}
                    </div>
                    <p className="text-xs text-[#7A5C44] mt-1 truncate">{c.last_message_text || 'Sin mensajes'}</p>
                    <div className="flex items-center justify-between mt-1">
                      <p className="text-[10px] text-[#A87B5D]">{c.last_message_at || c.created_at || ''}</p>
                      {c.assigned_agent_id && (
                        <span className="text-[10px] px-1.5 py-0.5 bg-blue-50 text-blue-600 rounded-full truncate max-w-[120px]">
                          Asignado
                        </span>
                      )}
                    </div>
                  </button>
                ))}
              </div>
            </Card.Body>
          </Card>

          {/* Mensajes */}
          <Card className="lg:col-span-2 overflow-hidden flex flex-col">
            <Card.Body className="p-0 flex flex-col h-full">
              {selected ? (
                <>
                  <div className="p-4 border-b border-[#F5EBD8] bg-[#FEF3C7] flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-homenest-bark">{selected.contact_name || 'Desconocido'}</p>
                      <p className="text-xs text-[#7A5C44]">{selected.contact_phone}</p>
                      {assignedMember && (
                        <p className="text-xs text-blue-600 mt-0.5">
                          Asignado a: {assignedMember.name}
                        </p>
                      )}
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setAssignOpen(true)}
                      className="shrink-0"
                    >
                      <UserPlus size={14} className="mr-1.5" />
                      {selected.assigned_agent_id ? 'Reasignar' : 'Asignar'}
                    </Button>
                  </div>
                  <div className="flex-1 overflow-y-auto p-4 space-y-3">
                    {messages.length === 0 ? (
                      <p className="text-center text-sm text-[#A87B5D] py-8">No hay mensajes en esta conversación</p>
                    ) : (
                      messages.map((m) => (
                        <div
                          key={m.external_id}
                          className={`flex ${
                            m.sender_type === 'customer' ? 'justify-start' : 'justify-end'
                          }`}
                        >
                          <div
                            className={`max-w-[85%] sm:max-w-[70%] rounded-2xl px-4 py-2.5 text-sm ${
                              m.sender_type === 'customer'
                                ? 'bg-homenest-cream-light border border-[#E9D5B7] text-homenest-bark'
                                : 'bg-homenest-bark text-white'
                            }`}
                          >
                            <div className="flex items-center gap-1.5 mb-1 opacity-80">
                              {senderIcon(m.sender_type)}
                              <span className="text-[10px] font-medium">{senderLabel(m.sender_type)}</span>
                            </div>
                            <p>{m.content_text}</p>
                            {m.media_url && (
                              <a
                                href={m.media_url}
                                target="_blank"
                                rel="noreferrer"
                                className="text-xs underline mt-1 block truncate"
                              >
                                Ver medio
                              </a>
                            )}
                            <p className="text-[10px] mt-1 opacity-60 text-right">{m.created_at}</p>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                  {/* Input de respuesta */}
                  <div className="p-3 border-t border-[#F5EBD8] bg-[#FEF3C7]">
                    <div className="flex items-end gap-2">
                      <Input
                        value={replyText}
                        onChange={(e) => setReplyText(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' && !e.shiftKey) {
                            e.preventDefault();
                            handleSendReply();
                          }
                        }}
                        placeholder={currentAgentId ? 'Escribe tu respuesta...' : 'Selecciona tu identidad de agente'}
                        disabled={!currentAgentId || sendingReply}
                        className="flex-1"
                      />
                      <Button
                        onClick={handleSendReply}
                        loading={sendingReply}
                        disabled={!currentAgentId || !replyText.trim()}
                      >
                        <Send size={16} className="mr-1.5" />
                        Enviar
                      </Button>
                    </div>
                    {!currentAgentId && (
                      <p className="text-xs text-amber-600 mt-2">Selecciona "Responder como..." para poder responder mensajes.</p>
                    )}
                  </div>
                </>
              ) : (
                <div className="flex-1 flex items-center justify-center">
                  <p className="text-sm text-[#A87B5D]">Selecciona una conversación</p>
                </div>
              )}
            </Card.Body>
          </Card>
        </div>
      )}

      {/* Modal de asignación */}
      <Modal
        isOpen={assignOpen}
        onClose={() => setAssignOpen(false)}
        title="Asignar conversación"
        maxWidth="sm"
      >
        <div className="space-y-2 max-h-[60vh] overflow-y-auto">
          {selected?.assigned_agent_id && (
            <button
              onClick={() => handleAssign(null)}
              disabled={assigning}
              className="w-full flex items-center gap-3 p-3 rounded-lg border border-red-100 bg-red-50 hover:bg-red-100 transition text-left"
            >
              <X size={18} className="text-red-600" />
              <span className="text-sm font-medium text-red-700">Desasignar conversación</span>
            </button>
          )}
          {members.length === 0 ? (
            <p className="text-sm text-[#7A5C44] py-4 text-center">No hay agentes disponibles</p>
          ) : (
            members.map((member) => (
              <button
                key={member.id}
                onClick={() => handleAssign(member.id)}
                disabled={assigning || selected?.assigned_agent_id === member.id}
                className={`w-full flex items-center gap-3 p-3 rounded-lg border transition text-left ${
                  selected?.assigned_agent_id === member.id
                    ? 'border-blue-200 bg-blue-50'
                    : 'border-[#F5EBD8] hover:bg-[#FEF3C7]'
                }`}
              >
                <div className="w-8 h-8 rounded-full bg-[#F5EBD8] flex items-center justify-center text-xs font-medium text-homenest-bark shrink-0">
                  {member.name.charAt(0).toUpperCase()}
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-medium text-homenest-bark truncate">{member.name}</p>
                  <p className="text-xs text-[#7A5C44] truncate">{member.role}</p>
                </div>
              </button>
            ))
          )}
        </div>
      </Modal>
    </Layout>
  );
};

export default WacrmMessages;
