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

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

const Progress: React.FC<ProgressProps> = ({ onBack }) => {
  const { token } = useAuth();
  const [habitStats, setHabitStats] = useState<any>(null);
  const [taskStats, setTaskStats] = useState<any>(null);
  const [healthStats, setHealthStats] = useState<any>(null);

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

  useEffect(() => {
    loadAllStats();
  }, []);

  const loadAllStats = async () => {
    try {
      // Carregar estatísticas de hábitos
      const habitsRes = await fetch(`${backendUrl}/api/v1/habits/stats`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (habitsRes.ok) {
        setHabitStats(await habitsRes.json());
      }

      // Carregar estatísticas de tarefas
      const tasksRes = await fetch(`${backendUrl}/api/v1/tasks/stats/summary`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (tasksRes.ok) {
        setTaskStats(await tasksRes.json());
      }

      // Carregar estatísticas de saúde
      const healthRes = await fetch(`${backendUrl}/api/v1/health/stats/summary`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (healthRes.ok) {
        setHealthStats(await healthRes.json());
      }
    } catch (error) {
      console.error('Erro ao carregar estatísticas:', error);
    }
  };

  const calculateCompletionRate = (completed: number, total: number) => {
    if (total === 0) return 0;
    return Math.round((completed / total) * 100);
  };

  return (
    <div className="progress-page">
      <header className="progress-header">
        <button onClick={onBack} className="back-button">← Voltar</button>
        <h1>📈 Progresso e Estatísticas</h1>
      </header>

      <div className="progress-container">
        {/* Hábitos */}
        <section className="progress-section">
          <h2>🎯 Hábitos</h2>
          {habitStats ? (
            <div className="stats-grid">
              <div className="stat-card">
                <div className="stat-icon">📊</div>
                <div className="stat-content">
                  <h3>Total de Hábitos</h3>
                  <p className="stat-number">{habitStats.total_habits}</p>
                </div>
              </div>
              <div className="stat-card">
                <div className="stat-icon">✅</div>
                <div className="stat-content">
                  <h3>Completados Hoje</h3>
                  <p className="stat-number">{habitStats.completed_today}</p>
                </div>
              </div>
              <div className="stat-card">
                <div className="stat-icon">⏳</div>
                <div className="stat-content">
                  <h3>Pendentes Hoje</h3>
                  <p className="stat-number">{habitStats.pending_today}</p>
                </div>
              </div>
              <div className="stat-card completion">
                <div className="stat-icon">🎯</div>
                <div className="stat-content">
                  <h3>Taxa de Conclusão</h3>
                  <p className="stat-number">
                    {calculateCompletionRate(habitStats.completed_today, habitStats.total_habits)}%
                  </p>
                </div>
              </div>
            </div>
          ) : (
            <p className="loading">Carregando...</p>
          )}
        </section>

        {/* Tarefas */}
        <section className="progress-section">
          <h2>📝 Tarefas</h2>
          {taskStats ? (
            <div className="stats-grid">
              <div className="stat-card">
                <div className="stat-icon">📊</div>
                <div className="stat-content">
                  <h3>Total de Tarefas</h3>
                  <p className="stat-number">{taskStats.total_tasks}</p>
                </div>
              </div>
              <div className="stat-card pending">
                <div className="stat-icon">⏳</div>
                <div className="stat-content">
                  <h3>Pendentes</h3>
                  <p className="stat-number">{taskStats.pending}</p>
                </div>
              </div>
              <div className="stat-card progress">
                <div className="stat-icon">🔄</div>
                <div className="stat-content">
                  <h3>Em Progresso</h3>
                  <p className="stat-number">{taskStats.in_progress}</p>
                </div>
              </div>
              <div className="stat-card completed">
                <div className="stat-icon">✅</div>
                <div className="stat-content">
                  <h3>Concluídas</h3>
                  <p className="stat-number">{taskStats.completed}</p>
                </div>
              </div>
              <div className="stat-card today">
                <div className="stat-icon">📅</div>
                <div className="stat-content">
                  <h3>Tarefas Hoje</h3>
                  <p className="stat-number">{taskStats.today_completed}/{taskStats.today_tasks}</p>
                </div>
              </div>
              <div className="stat-card completion">
                <div className="stat-icon">🎯</div>
                <div className="stat-content">
                  <h3>Taxa de Conclusão</h3>
                  <p className="stat-number">
                    {calculateCompletionRate(taskStats.completed, taskStats.total_tasks)}%
                  </p>
                </div>
              </div>
            </div>
          ) : (
            <p className="loading">Carregando...</p>
          )}
        </section>

        {/* Saúde */}
        <section className="progress-section">
          <h2>💪 Saúde</h2>
          {healthStats ? (
            <div className="stats-grid">
              <div className="stat-card">
                <div className="stat-icon">⚖️</div>
                <div className="stat-content">
                  <h3>Peso Atual</h3>
                  <p className="stat-number">
                    {healthStats.current_weight ? `${healthStats.current_weight} kg` : '--'}
                  </p>
                </div>
              </div>
              <div className="stat-card">
                <div className="stat-icon">📏</div>
                <div className="stat-content">
                  <h3>Altura</h3>
                  <p className="stat-number">
                    {healthStats.current_height ? `${healthStats.current_height} cm` : '--'}
                  </p>
                </div>
              </div>
              <div className="stat-card">
                <div className="stat-icon">📊</div>
                <div className="stat-content">
                  <h3>% Gordura</h3>
                  <p className="stat-number">
                    {healthStats.current_body_fat ? `${healthStats.current_body_fat}%` : '--'}
                  </p>
                </div>
              </div>
              <div className={`stat-card ${healthStats.weight_change && healthStats.weight_change > 0 ? 'positive' : 'negative'}`}>
                <div className="stat-icon">📈</div>
                <div className="stat-content">
                  <h3>Variação de Peso</h3>
                  <p className="stat-number">
                    {healthStats.weight_change 
                      ? `${healthStats.weight_change > 0 ? '+' : ''}${healthStats.weight_change.toFixed(1)} kg`
                      : '--'
                    }
                  </p>
                </div>
              </div>
              <div className="stat-card">
                <div className="stat-icon">📋</div>
                <div className="stat-content">
                  <h3>Total de Registros</h3>
                  <p className="stat-number">{healthStats.total_measurements}</p>
                </div>
              </div>
            </div>
          ) : (
            <p className="loading">Carregando...</p>
          )}
        </section>

        {/* Mensagem motivacional */}
        <section className="motivation-section">
          <div className="motivation-card">
            <h2>💪 Continue Assim!</h2>
            <p>
              Você está no caminho certo para transformar sua vida! 
              Cada pequeno passo conta na sua jornada de 180 dias.
            </p>
            <p className="motivation-quote">
              "O sucesso é a soma de pequenos esforços repetidos dia após dia." 🚀
            </p>
          </div>
        </section>
      </div>
    </div>
  );
};

export default Progress;

