// frontend/src/pages/EditContactPage.tsx
import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import apiClient from '../services/api';

interface Contact {
  name: string;
  email: string | null;
  phone: string | null;
  notes: string | null;
}

const EditContactPage: React.FC = () => {
  const navigate = useNavigate();
  const { contactId } = useParams<{ contactId: string }>();

  const [contact, setContact] = useState<Contact | null>(null);
  const [loading, setLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!contactId) {
      setError("ID do contato não encontrado na URL.");
      setLoading(false);
      return;
    }
    
    const fetchContactDetails = async () => {
      setLoading(true);
      try {
        const response = await apiClient.get<Contact>(`/contacts/${contactId}`);
        setContact(response.data);
      } catch (err) {
        setError('Não foi possível carregar os dados do contato.');
      } finally {
        setLoading(false);
      }
    };
    fetchContactDetails();
  }, [contactId]);
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!contact || !contact.name.trim()) {
      setError('O campo "Nome" é obrigatório.');
      return;
    }

    setIsSubmitting(true);
    setError(null);

    try {
      await apiClient.put(`/contacts/${contactId}`, contact);
      alert('Contato atualizado com sucesso!');
      navigate('/contacts');
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Falha ao atualizar o contato.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    if (contact) {
      setContact({ ...contact, [e.target.name]: e.target.value });
    }
  };

  if (loading) return <p>Carregando contato para edição...</p>;
  if (error) return <p style={{ color: 'red' }}>Erro: {error}</p>;

  // --- CORREÇÃO PRINCIPAL AQUI ---
  // Só renderiza o formulário se 'contact' não for nulo.
  return (
    <div style={{ maxWidth: 500, margin: '0 auto', padding: 24 }}>
      <h1>Editar Contato</h1>
      
      {contact ? (
        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: 16 }}>
            <label htmlFor="name">Nome*</label>
            <input id="name" name="name" type="text" value={contact.name} onChange={handleChange} required style={{ width: '100%', padding: 8 }}/>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label htmlFor="email">Email</label>
            <input id="email" name="email" type="email" value={contact.email || ''} onChange={handleChange} style={{ width: '100%', padding: 8 }}/>
          </div>
          <div style={{ marginBottom: 16 }}>
            <label htmlFor="phone">Telefone</label>
            <input id="phone" name="phone" type="tel" value={contact.phone || ''} onChange={handleChange} style={{ width: '100%', padding: 8 }}/>
          </div>
          <div style={{ marginBottom: 24 }}>
            <label htmlFor="notes">Notas</label>
            <textarea id="notes" name="notes" value={contact.notes || ''} onChange={handleChange} style={{ width: '100%', padding: 8, minHeight: 80 }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
            <Link to="/contacts"><button type="button">Cancelar</button></Link>
            <button type="submit" disabled={isSubmitting}>{isSubmitting ? 'Atualizando...' : 'Salvar Alterações'}</button>
          </div>
        </form>
      ) : (
        <p>Não foi possível encontrar os dados do contato.</p>
      )}
    </div>
  );
};

export default EditContactPage;