// frontend/src/pages/AddContactPage.tsx
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import apiClient from '../services/api';

const AddContactPage: React.FC = () => {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [notes, setNotes] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) { setError('O campo "Nome" é obrigatório.'); return; }
    setIsSubmitting(true);
    setError(null);
    try {
      await apiClient.post('/contacts/', { name, email, phone, notes });
      alert('Contato criado com sucesso!');
      navigate('/contacts');
    } catch (err: any) {
      let displayError = 'Falha ao criar o contato.';
      if (err.response?.data?.detail) {
        displayError = Array.isArray(err.response.data.detail) ? err.response.data.detail[0].msg : err.response.data.detail;
      }
      setError(displayError);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div>
      <h1>Adicionar Novo Contato</h1>
      <form onSubmit={handleSubmit}>
        {error && <p style={{ color: 'red' }}>{error}</p>}
        <div style={{ marginBottom: 16 }}><label htmlFor="name" style={{ display: 'block' }}>Nome*</label><input id="name" type="text" value={name} onChange={(e) => setName(e.target.value)} required style={{ width: '100%', padding: 8 }}/></div>
        <div style={{ marginBottom: 16 }}><label htmlFor="email" style={{ display: 'block' }}>Email</label><input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} style={{ width: '100%', padding: 8 }}/></div>
        <div style={{ marginBottom: 16 }}><label htmlFor="phone" style={{ display: 'block' }}>Telefone</label><input id="phone" type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} style={{ width: '100%', padding: 8 }}/></div>
        <div style={{ marginBottom: 24 }}><label htmlFor="notes" style={{ display: 'block' }}>Notas</label><textarea id="notes" value={notes} onChange={(e) => setNotes(e.target.value)} 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 ? 'Salvando...' : 'Salvar'}</button></div>
      </form>
    </div>
  );
};

export default AddContactPage;