// frontend/src/pages/ImportGoogleContactsPage.tsx

import React, { useEffect, useState, useMemo } from 'react';
import { useAuth } from '../context/AuthContext';
import apiClient from '../services/api';
import { useNavigate } from 'react-router-dom';

// Interfaces (sem alteração)
interface GoogleContact { name: string; email?: string; phone?: string; }
interface ImportResponse { message: string; imported: number; skipped: number; }

const ImportGoogleContactsPage: React.FC = () => {
    const { isLoggedIn, token } = useAuth();
    const navigate = useNavigate();

    // Estados (sem alteração)
    const [allContacts, setAllContacts] = useState<GoogleContact[]>([]);
    const [selectedContacts, setSelectedContacts] = useState<Set<GoogleContact>>(new Set());
    const [searchTerm, setSearchTerm] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isImporting, setIsImporting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // useEffect para buscar dados (sem alteração)
    useEffect(() => {
        const fetchGoogleContacts = async () => {
            if (!isLoggedIn || !token) {
              setIsLoading(false);
              return;
            }
            
            setIsLoading(true);
            setError(null);
            try {
                const response = await apiClient.get<GoogleContact[]>('/contacts/from-google/', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                setAllContacts(response.data);
            } catch (err: any) {
                console.error("Falha ao buscar contatos do Google:", err);
                if (err.response?.status === 401) {
                    setError("Sua sessão do Google expirou. Por favor, faça login novamente.");
                } else {
                    setError("Não foi possível carregar os contatos do Google.");
                }
            } finally {
                setIsLoading(false);
            }
        };
        fetchGoogleContacts();
    }, [isLoggedIn, token]);

    // Lógica de filtro e handlers (sem alteração)
    const filteredContacts = useMemo(() => {
        if (!searchTerm) return allContacts;
        return allContacts.filter(contact =>
            contact.name.toLowerCase().includes(searchTerm.toLowerCase())
        );
    }, [allContacts, searchTerm]);

    const handleSelectContact = (contact: GoogleContact, isChecked: boolean) => {
        const newSelection = new Set(selectedContacts);
        if (isChecked) newSelection.add(contact);
        else newSelection.delete(contact);
        setSelectedContacts(newSelection);
    };

    const handleImport = async (contactsToImport: GoogleContact[]) => {
        if (contactsToImport.length === 0) {
            alert("Por favor, selecione ao menos um contato para importar.");
            return;
        }
        setIsImporting(true);
        try {
            const response = await apiClient.post<ImportResponse>('/contacts/import-from-google/', contactsToImport, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            alert(`Importação concluída! ${response.data.imported} contatos importados, ${response.data.skipped} já existiam.`);
            navigate('/contacts');
        } catch (err: any) {
            console.error("Erro ao importar contatos:", err);
            alert("Falha na importação: " + (err.response?.data?.detail || "Erro desconhecido"));
        } finally {
            setIsImporting(false);
        }
    };
    
    // --- JSX CORRIGIDO E REESTRUTURADO ---
    return (
        <div>
            <h2>Importar Contatos do Google</h2>
            
            {isLoggedIn ? (
                // Se estiver logado, então verificamos os outros estados
                <>
                    {isLoading && <p>Carregando contatos da sua conta Google...</p>}
                    {error && <p style={{ color: 'red' }}>{error}</p>}
                    
                    {!isLoading && !error && (
                        <div>
                            {/* Barra de Ações: Busca e Botões */}
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                                <input
                                    type="text"
                                    placeholder="Pesquisar contatos..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    style={{ padding: '8px', width: '300px' }}
                                />
                                <div style={{ display: 'flex', gap: '8px' }}>
                                    <button onClick={() => handleImport(Array.from(selectedContacts))} disabled={isImporting || selectedContacts.size === 0}>
                                        {isImporting ? 'Importando...' : `Importar Selecionados (${selectedContacts.size})`}
                                    </button>
                                    <button onClick={() => handleImport(allContacts)} disabled={isImporting || allContacts.length === 0}>
                                        {isImporting ? 'Importando...' : 'Importar Todos'}
                                    </button>
                                </div>
                            </div>

                            {/* Lista de Contatos */}
                            <div style={{ maxHeight: '60vh', overflowY: 'auto', border: '1px solid #ccc', padding: '10px', borderRadius: '4px' }}>
                                {filteredContacts.length > 0 ? (
                                    <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                                        {filteredContacts.map((contact, index) => (
                                            <li key={index} style={{ display: 'flex', alignItems: 'center', padding: '8px', borderBottom: '1px solid #eee' }}>
                                                <input
                                                    type="checkbox"
                                                    checked={selectedContacts.has(contact)}
                                                    onChange={(e) => handleSelectContact(contact, e.target.checked)}
                                                    style={{ marginRight: '12px' }}
                                                />
                                                <span>{contact.name} - {contact.email || 'Sem email'}</span>
                                            </li>
                                        ))}
                                    </ul>
                                ) : (
                                    <p>Nenhum contato encontrado na sua conta Google (ou para o termo buscado).</p>
                                )}
                            </div>
                        </div>
                    )}
                </>
            ) : (
                // Se não estiver logado, mostra a mensagem de login
                <p>Por favor, faça login para importar seus contatos.</p>
            )}
        </div>
    );
};

export default ImportGoogleContactsPage;