import React, { useEffect, useState } from 'react';
import { useAuth } from '../contexts/AuthContext';
import './Health.css';

interface HealthProps {
  onBack: () => void;
}

interface HealthMetric {
  id: string;
  measurement_date: string;
  weight?: number;
  height?: number;
  body_fat_percentage?: number;
  muscle_mass?: number;
  waist?: number;
  chest?: number;
  hips?: number;
  notes?: string;
}

const Health: React.FC<HealthProps> = ({ onBack }) => {
  const { token } = useAuth();
  const [metrics, setMetrics] = useState<HealthMetric[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({
    measurement_date: new Date().toISOString().split('T')[0],
    weight: '',
    height: '',
    body_fat_percentage: '',
    muscle_mass: '',
    waist: '',
    chest: '',
    hips: '',
    notes: ''
  });
  const [stats, setStats] = useState({
    current_weight: null as number | null,
    weight_change: null as number | null,
    total_measurements: 0
  });

  const backendUrl = `${window.location.protocol}//${window.location.host}`;

  useEffect(() => {
    loadMetrics();
    loadStats();
  }, []);

  const loadMetrics = async () => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/health/`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setMetrics(data);
      }
    } catch (error) {
      console.error('Erro ao carregar métricas:', error);
    }
  };

  const loadStats = async () => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/health/stats/summary`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setStats(data);
      }
    } catch (error) {
      console.error('Erro ao carregar estatísticas:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const payload: any = {
      measurement_date: formData.measurement_date,
    };

    // Adicionar apenas campos preenchidos
    if (formData.weight) payload.weight = parseFloat(formData.weight);
    if (formData.height) payload.height = parseFloat(formData.height);
    if (formData.body_fat_percentage) payload.body_fat_percentage = parseFloat(formData.body_fat_percentage);
    if (formData.muscle_mass) payload.muscle_mass = parseFloat(formData.muscle_mass);
    if (formData.waist) payload.waist = parseFloat(formData.waist);
    if (formData.chest) payload.chest = parseFloat(formData.chest);
    if (formData.hips) payload.hips = parseFloat(formData.hips);
    if (formData.notes) payload.notes = formData.notes;

    try {
      const response = await fetch(`${backendUrl}/api/v1/health/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (response.ok) {
        alert('Métrica registrada com sucesso! 🎉');
        setShowForm(false);
        setFormData({
          measurement_date: new Date().toISOString().split('T')[0],
          weight: '',
          height: '',
          body_fat_percentage: '',
          muscle_mass: '',
          waist: '',
          chest: '',
          hips: '',
          notes: ''
        });
        loadMetrics();
        loadStats();
      } else {
        const error = await response.json();
        alert(`Erro: ${error.detail || 'Não foi possível registrar'}`);
      }
    } catch (error) {
      console.error('Erro ao registrar métrica:', error);
      alert('Erro ao registrar métrica');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Deseja realmente deletar esta métrica?')) return;

    try {
      const response = await fetch(`${backendUrl}/api/v1/health/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        loadMetrics();
        loadStats();
      }
    } catch (error) {
      console.error('Erro ao deletar métrica:', error);
    }
  };

  return (
    <div className="health-page">
      <header className="health-header">
        <button onClick={onBack} className="back-button">← Voltar</button>
        <h1>💪 Métricas de Saúde</h1>
        <button onClick={() => setShowForm(!showForm)} className="add-button">
          {showForm ? '❌ Cancelar' : '➕ Registrar'}
        </button>
      </header>

      <div className="health-container">
        {/* Resumo/Stats */}
        <section className="health-stats">
          <div className="stat-box">
            <span className="stat-label">Peso Atual</span>
            <span className="stat-value">
              {stats.current_weight ? `${stats.current_weight} kg` : '--'}
            </span>
          </div>
          <div className="stat-box">
            <span className="stat-label">Variação</span>
            <span className={`stat-value ${stats.weight_change && stats.weight_change > 0 ? 'positive' : 'negative'}`}>
              {stats.weight_change 
                ? `${stats.weight_change > 0 ? '+' : ''}${stats.weight_change.toFixed(1)} kg`
                : '--'
              }
            </span>
          </div>
          <div className="stat-box">
            <span className="stat-label">Total de Registros</span>
            <span className="stat-value">{stats.total_measurements}</span>
          </div>
        </section>

        {/* Formulário */}
        {showForm && (
          <section className="health-form">
            <h2>📝 Registrar Nova Métrica</h2>
            <form onSubmit={handleSubmit}>
              <div className="form-row">
                <div className="form-group">
                  <label>Data</label>
                  <input
                    type="date"
                    value={formData.measurement_date}
                    onChange={e => setFormData({ ...formData, measurement_date: e.target.value })}
                    required
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>Peso (kg)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.weight}
                    onChange={e => setFormData({ ...formData, weight: e.target.value })}
                    placeholder="Ex: 75.5"
                  />
                </div>
                <div className="form-group">
                  <label>Altura (cm)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.height}
                    onChange={e => setFormData({ ...formData, height: e.target.value })}
                    placeholder="Ex: 175"
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>% Gordura</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.body_fat_percentage}
                    onChange={e => setFormData({ ...formData, body_fat_percentage: e.target.value })}
                    placeholder="Ex: 15.5"
                  />
                </div>
                <div className="form-group">
                  <label>Massa Muscular (kg)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.muscle_mass}
                    onChange={e => setFormData({ ...formData, muscle_mass: e.target.value })}
                    placeholder="Ex: 60"
                  />
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>Cintura (cm)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.waist}
                    onChange={e => setFormData({ ...formData, waist: e.target.value })}
                    placeholder="Ex: 85"
                  />
                </div>
                <div className="form-group">
                  <label>Peito (cm)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.chest}
                    onChange={e => setFormData({ ...formData, chest: e.target.value })}
                    placeholder="Ex: 100"
                  />
                </div>
                <div className="form-group">
                  <label>Quadril (cm)</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.hips}
                    onChange={e => setFormData({ ...formData, hips: e.target.value })}
                    placeholder="Ex: 95"
                  />
                </div>
              </div>

              <div className="form-group">
                <label>Observações</label>
                <textarea
                  value={formData.notes}
                  onChange={e => setFormData({ ...formData, notes: e.target.value })}
                  placeholder="Anote detalhes importantes..."
                  rows={3}
                />
              </div>

              <button type="submit" className="submit-button">
                💾 Salvar Métrica
              </button>
            </form>
          </section>
        )}

        {/* Lista de métricas */}
        <section className="metrics-list">
          <h2>📊 Histórico de Medições</h2>
          {metrics.length === 0 ? (
            <p className="empty-message">Nenhuma métrica registrada ainda. Comece agora! 💪</p>
          ) : (
            <div className="metrics-grid">
              {metrics.map(metric => (
                <div key={metric.id} className="metric-card">
                  <div className="metric-header">
                    <span className="metric-date">
                      {new Date(metric.measurement_date).toLocaleDateString('pt-BR')}
                    </span>
                    <button 
                      onClick={() => handleDelete(metric.id)} 
                      className="delete-btn"
                      title="Deletar"
                    >
                      🗑️
                    </button>
                  </div>
                  <div className="metric-details">
                    {metric.weight && <p>⚖️ Peso: <strong>{metric.weight} kg</strong></p>}
                    {metric.height && <p>📏 Altura: <strong>{metric.height} cm</strong></p>}
                    {metric.body_fat_percentage && <p>📊 Gordura: <strong>{metric.body_fat_percentage}%</strong></p>}
                    {metric.muscle_mass && <p>💪 Músculo: <strong>{metric.muscle_mass} kg</strong></p>}
                    {metric.waist && <p>📐 Cintura: <strong>{metric.waist} cm</strong></p>}
                    {metric.chest && <p>🎯 Peito: <strong>{metric.chest} cm</strong></p>}
                    {metric.hips && <p>📏 Quadril: <strong>{metric.hips} cm</strong></p>}
                    {metric.notes && <p className="notes">📝 {metric.notes}</p>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      </div>
    </div>
  );
};

export default Health;

