// CAMINHO: frontend/src/pages/ContactListPage.tsx

import React, { useEffect, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import apiClient from '../services/api';
import CreateConnectionModal from '../components/CreateConnectionModal';

function useDebounce(value: string, delay: number) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
}

interface Contact {
  id: string;
  name: string;
  email: string | null;
  phone: string | null;
  notes: string | null;
}

interface DeleteAllResponse {
  message: string;
  deleted_contacts: number;
}

const ContactListPage: React.FC = () => {
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [sourceContact, setSourceContact] = useState<Contact | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  
  const debouncedSearchTerm = useDebounce(searchTerm, 300);
  const navigate = useNavigate();

  const fetchContacts = useCallback(async (searchQuery: string) => {
    setLoading(true);
    try {
      const response = await apiClient.get<Contact[]>('/contacts/', {
        params: { 
          search: searchQuery,
          limit: 1000
        } 
      });
      setContacts(response.data);
      setError(null);
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Falha ao buscar contatos.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchContacts(debouncedSearchTerm);
  }, [debouncedSearchTerm, fetchContacts]);

  const handleEdit = (contactId: string) => navigate(`/contacts/edit/${contactId}`);

  const handleDelete = async (contactId: string, contactName: string) => {
    const displayName = contactName || "este contato";
    if (window.confirm(`Tem certeza que deseja deletar "${displayName}"?`)) {
      try {
        await apiClient.delete(`/contacts/${contactId}`);
        alert(`Contato "${displayName}" deletado com sucesso.`);
        fetchContacts(debouncedSearchTerm);
      } catch (err: any) {
        alert(err.response?.data?.detail || 'Falha ao deletar o contato.');
      }
    }
  };

  const handleDeleteAll = async () => {
    if (window.confirm("ATENÇÃO! Esta ação é irreversível e irá apagar TODOS os seus contatos e conexões. Deseja continuar?")) {
      if (window.confirm("ÚLTIMO AVISO: Tem certeza ABSOLUTA?")) {
        try {
          const response = await apiClient.delete<DeleteAllResponse>('/contacts/all');
          alert(`${response.data.deleted_contacts} contatos foram apagados com sucesso.`);
          setSearchTerm("");
          fetchContacts("");
        } catch (err: any) {
          alert(err.response?.data?.detail || 'Falha ao apagar todos os contatos.');
        }
      }
    }
  };
  
  const openCreateConnectionModal = (contact: Contact) => {
    setSourceContact(contact);
    setIsModalOpen(true);
  };

  const closeCreateConnectionModal = () => {
    setIsModalOpen(false);
    setSourceContact(null);
  };

  const handleCreateConnection = async (
    sourceId: string, targetId: string, typeId: number, notes: string
  ) => {
    try {
      await apiClient.post('/conexoes/', {
        contato_origem_id: sourceId,
        contato_destino_id: targetId,
        tipo_conexao_id: typeId,
        notes: notes,
      });
      alert('Conexão criada com sucesso!');
      closeCreateConnectionModal();
    } catch (err: any) {
      console.error('Erro ao criar conexão:', err);
      alert(err.response?.data?.detail || 'Falha ao criar a conexão.');
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <h1>Meus Contatos</h1>
        <div style={{ display: 'flex', gap: '12px' }}>
          {contacts.length > 0 && !loading && (
            <button 
              onClick={handleDeleteAll}
              style={{ backgroundColor: '#e63946', color: 'white', border: 'none', padding: '10px 15px', borderRadius: '4px', cursor: 'pointer' }}
            >
              Apagar Todos
            </button>
          )}
          <button onClick={() => navigate('/contacts/add')}>
            + Adicionar Contato
          </button>
        </div>
      </div>

      <div style={{ marginBottom: 24 }}>
        <input
          type="text"
          placeholder="Pesquisar por nome ou email..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ width: '100%', padding: '10px', boxSizing: 'border-box', borderRadius: '4px', border: '1px solid #ccc' }}
        />
      </div>
      
      {loading ? <p>Carregando...</p> : 
       error ? <p style={{ color: 'red' }}>Erro: {error}</p> :
       contacts.length === 0 && debouncedSearchTerm ? <p>Nenhum contato encontrado para "{debouncedSearchTerm}".</p> :
       contacts.length === 0 ? <p>Você ainda não tem contatos. <Link to="/import-google-contacts">Importar do Google</Link></p> : (
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#f0f0f0' }}>
              <th style={{ padding: 12, textAlign: 'left' }}>Nome</th>
              <th style={{ padding: 12, textAlign: 'left' }}>Email</th>
              <th style={{ padding: 12, textAlign: 'left' }}>Telefone</th>
              <th style={{ padding: 12, textAlign: 'left' }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {contacts.map((contact) => (
              <tr key={contact.id} style={{ borderBottom: '1px solid #ddd' }}>
                <td style={{ padding: 12 }}><strong>{contact.name || '(Sem nome)'}</strong></td>
                <td style={{ padding: 12 }}>{contact.email || '-'}</td>
                <td style={{ padding: 12 }}>{contact.phone || '-'}</td>
                <td style={{ padding: 12, display: 'flex', gap: 8 }}>
                  <button onClick={() => openCreateConnectionModal(contact)} title="Criar Conexão">🔗</button>
                  <button onClick={() => handleEdit(contact.id)} title="Editar">✏️</button>
                  <button onClick={() => handleDelete(contact.id, contact.name)} title="Deletar">🗑️</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {isModalOpen && (
        <CreateConnectionModal
          isOpen={isModalOpen}
          onClose={closeCreateConnectionModal}
          onConnect={handleCreateConnection}
          // A prop 'contacts' foi removida, pois o modal agora é independente
          sourceContact={sourceContact}
        />
      )}
    </div>
  );
};

export default ContactListPage;