// packages/frontend/src/components/CelebrityProfile.jsx

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { getCelebrityById, updateCelebrity, deleteCelebrity } from '../services/api';
import EditableField from './EditableField';
import './CelebrityProfile.css';

function CelebrityProfile() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [celebrity, setCelebrity] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (id) {
      setLoading(true);
      getCelebrityById(id)
        .then((data) => {
          if (data.birth_date) {
            data.birth_date = data.birth_date.split('T')[0];
          }
          setCelebrity(data);
        })
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    } else {
      navigate('/');
    }
  }, [id, navigate]);

  const handleFieldSave = async (fieldName, newValue) => {
    let valueToSend = newValue === '' ? null : newValue;
    if (fieldName === 'boobs_are_natural') {
      valueToSend = newValue === 'true';
    }
    const payload = { [fieldName]: valueToSend };

    try {
      const updatedCelebrity = await updateCelebrity(id, payload);
      setCelebrity((prev) => ({ ...prev, [fieldName]: newValue }));
      console.log('Salvataggio riuscito:', updatedCelebrity);
    } catch (err) {
      console.error(`Errore durante il salvataggio del campo ${fieldName}:`, err);
      throw err;
    }
  };

  const handleDelete = async () => {
    if (window.confirm(`Sei sicuro di voler eliminare ${celebrity.name}? L'azione è irreversibile.`)) {
      try {
        await deleteCelebrity(id);
        alert(`${celebrity.name} è stato eliminato con successo.`);
        navigate('/');
      } catch (err) {
        setError(`Errore durante l'eliminazione: ${err.message}`);
      }
    }
  };

  if (loading) return <article aria-busy="true">Caricamento profilo...</article>;
  if (error && !celebrity) return <article><p className="error-message">Errore: {error}</p></article>;
  if (!celebrity) return <p>Nessuna celebrità trovata.</p>;

  const genderOptions = [{ value: 'female', label: 'Female' }, { value: 'male', label: 'Male' }, { value: 'other', label: 'Other' }];
  const braSystemOptions = [{ value: 'US', label: 'US' }, { value: 'UK', label: 'UK' }, { value: 'EU', label: 'EU' }, { value: 'FR', label: 'FR' }, { value: 'AU', label: 'AU' }, { value: 'IT', label: 'IT' }, { value: 'JP', label: 'JP' }];
  const shoeSystemOptions = [{ value: 'EU', label: 'EU' }, { value: 'US', label: 'US' }, { value: 'UK', label: 'UK' }];
  const booleanOptions = [{ value: 'true', label: 'Sì' }, { value: 'false', label: 'No' }];

  return (
    <div className="profile-container">
      <aside className="profile-sidebar">
        <figure>
          <img src={`https://i.pravatar.cc/400?u=${id}`} alt={celebrity.name} />
          <figcaption>
            <EditableField label="Nome" name="name" value={celebrity.name} onSave={handleFieldSave} />
          </figcaption>
        </figure>
        <div className="profile-actions">
          <Link to="/" role="button" className="secondary outline">Torna alla Lista</Link>
          <button onClick={handleDelete} className="secondary">Elimina Profilo</button>
        </div>
      </aside>

      <main className="profile-content">
        {error && <p className="error-message">Errore: {error}</p>}
        
        <details open>
          <summary><h3>Dati Anagrafici</h3></summary>
          <div className="profile-grid">
            <EditableField label="Data di nascita" name="birth_date" value={celebrity.birth_date} type="date" onSave={handleFieldSave} />
            <EditableField label="Luogo di nascita" name="birth_place" value={celebrity.birth_place} onSave={handleFieldSave} />
            <EditableField label="Nazionalità" name="nationality" value={celebrity.nationality} onSave={handleFieldSave} />
            <EditableField label="Genere" name="gender" value={celebrity.gender} type="select" options={genderOptions} onSave={handleFieldSave} />
            <EditableField label="Sessualità" name="sexuality" value={celebrity.sexuality} onSave={handleFieldSave} />
          </div>
          <EditableField label="Sito Ufficiale" name="official_website" value={celebrity.official_website} type="url" onSave={handleFieldSave} />
        </details>

        <details>
          <summary><h3>Aspetto Fisico</h3></summary>
          <div className="profile-grid">
            <EditableField label="Etnia" name="ethnicity" value={celebrity.ethnicity} onSave={handleFieldSave} />
            <EditableField label="Colore Capelli" name="hair_color" value={celebrity.hair_color} onSave={handleFieldSave} />
            <EditableField label="Colore Occhi" name="eye_color" value={celebrity.eye_color} onSave={handleFieldSave} />
            <EditableField label="Corporatura" name="body_type" value={celebrity.body_type} onSave={handleFieldSave} />
          </div>
        </details>
        
        <details>
          <summary><h3>Misure Corporee</h3></summary>
          <div className="profile-grid">
            <EditableField label="Altezza (cm)" name="height_cm" value={celebrity.height_cm} type="number" onSave={handleFieldSave} />
            <EditableField label="Peso (kg)" name="weight_kg" value={celebrity.weight_kg} type="number" onSave={handleFieldSave} />
            <EditableField label="Seno (cm)" name="bust_cm" value={celebrity.bust_cm} type="number" onSave={handleFieldSave} />
            <EditableField label="Vita (cm)" name="waist_cm" value={celebrity.waist_cm} type="number" onSave={handleFieldSave} />
            <EditableField label="Fianchi (cm)" name="hips_cm" value={celebrity.hips_cm} type="number" onSave={handleFieldSave} />
            {celebrity.gender === 'male' && <EditableField label="Torace (cm)" name="chest_circumference_cm" value={celebrity.chest_circumference_cm} type="number" onSave={handleFieldSave} />}
            <EditableField label="Misura Scarpe" name="shoe_size" value={celebrity.shoe_size} type="number" onSave={handleFieldSave} />
            <EditableField label="Sistema Scarpe" name="shoe_size_system" value={celebrity.shoe_size_system} type="select" options={shoeSystemOptions} onSave={handleFieldSave} />
          </div>
        </details>

        {celebrity.gender !== 'male' && (
          <details>
            <summary><h3>Reggiseno</h3></summary>
            <div className="profile-grid">
              <EditableField label="Misura Fascia" name="bra_band_size" value={celebrity.bra_band_size} type="number" onSave={handleFieldSave} />
              <EditableField label="Coppa" name="bra_cup_size" value={celebrity.bra_cup_size} onSave={handleFieldSave} />
              <EditableField label="Sistema" name="bra_size_system" value={celebrity.bra_size_system} type="select" options={braSystemOptions} onSave={handleFieldSave} />
              <EditableField label="Seno Naturale?" name="boobs_are_natural" value={String(celebrity.boobs_are_natural)} type="select" options={booleanOptions} onSave={handleFieldSave} />
            </div>
          </details>
        )}
        
        <details>
          <summary><h3>Biografia</h3></summary>
          <EditableField label="Note biografiche" name="biography" value={celebrity.biography} type="textarea" onSave={handleFieldSave} />
        </details>

      </main>
    </div>
  );
}

export default CelebrityProfile;