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

type Page = 'dashboard' | 'habits' | 'admin' | 'tasks' | 'health' | 'progress';

interface DashboardProps {
  onNavigate: (page: Page) => void;
}

const Dashboard: React.FC<DashboardProps> = ({ onNavigate }) => {
  const { user, logout, token } = useAuth();
  const [stats, setStats] = useState({
    totalHabits: 0,
    completedToday: 0,
    pendingToday: 0
  });
  const [taskStats, setTaskStats] = useState({
    today_tasks: 0,
    today_completed: 0
  });
  const [healthStats, setHealthStats] = useState({
    current_weight: null as number | null
  });

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

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

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

      if (response.ok) {
        const data = await response.json();
        setStats({
          totalHabits: data.total_habits,
          completedToday: data.completed_today,
          pendingToday: data.pending_today
        });
      }
    } catch (error) {
      console.error('Erro ao carregar stats:', error);
    }
  };

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

      if (response.ok) {
        const data = await response.json();
        setTaskStats({
          today_tasks: data.today_tasks,
          today_completed: data.today_completed
        });
      }
    } catch (error) {
      console.error('Erro ao carregar stats de tarefas:', error);
    }
  };

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

      if (response.ok) {
        const data = await response.json();
        setHealthStats({
          current_weight: data.current_weight
        });
      }
    } catch (error) {
      console.error('Erro ao carregar stats de saúde:', error);
    }
  };

  return (
    <div className="dashboard">
      <header className="dashboard-header">
        <div className="header-content">
          <h1>🚀 VIDA180</h1>
          <div className="user-menu">
            <span className="user-name">Olá, {user?.username}!</span>
            
            {/* BOTÃO ADMIN - SÓ APARECE PARA SUPERADMIN */}
            {user?.is_superadmin && (
              <button onClick={() => onNavigate('admin')} className="admin-button">
                👨‍💼 Painel Admin
              </button>
            )}
            
            <button onClick={logout} className="logout-button">
              Sair
            </button>
          </div>
        </div>
      </header>

      <main className="dashboard-main">
        <div className="dashboard-container">
          <section className="welcome-section">
            <h2>Bem-vindo de volta! 💪</h2>
            <DailyMessage userId={user?.id || 'demo-user'} />
          </section>

          <section className="stats-grid">
            <div className="stat-card">
              <div className="stat-icon">🔥</div>
              <div className="stat-content">
                <h3>Sequência</h3>
                <p className="stat-value">7 dias</p>
                <span className="stat-label">Continue assim!</span>
              </div>
            </div>

            <div className="stat-card">
              <div className="stat-icon">✅</div>
              <div className="stat-content">
                <h3>Tarefas Hoje</h3>
                <p className="stat-value">{taskStats.today_completed}/{taskStats.today_tasks}</p>
                <span className="stat-label">
                  {taskStats.today_tasks - taskStats.today_completed > 0
                    ? `Faltam ${taskStats.today_tasks - taskStats.today_completed}`
                    : 'Tudo completo! 🎉'}
                </span>
              </div>
            </div>

            <div className="stat-card">
              <div className="stat-icon">🎯</div>
              <div className="stat-content">
                <h3>Hábitos</h3>
                <p className="stat-value">{stats.completedToday}/{stats.totalHabits}</p>
                <span className="stat-label">
                  {stats.pendingToday > 0 
                    ? `Faltam ${stats.pendingToday}` 
                    : 'Todos completos! 🎉'}
                </span>
              </div>
            </div>

            <div className="stat-card">
              <div className="stat-icon">📊</div>
              <div className="stat-content">
                <h3>Peso Atual</h3>
                <p className="stat-value">
                  {healthStats.current_weight ? `${healthStats.current_weight} kg` : '-- kg'}
                </p>
                <span className="stat-label">
                  {healthStats.current_weight ? 'Continue assim!' : 'Registre hoje'}
                </span>
              </div>
            </div>
          </section>

          <section className="main-areas">
            <div className="area-card">
              <h3>📝 Tarefas</h3>
              <p>Organize seu dia e conquiste seus objetivos</p>
              <button className="area-button" onClick={() => onNavigate('tasks')}>
                Ver Tarefas
              </button>
            </div>

            <div className="area-card">
              <h3>🎯 Hábitos</h3>
              <p>Construa rotinas poderosas para transformação</p>
              <button className="area-button" onClick={() => onNavigate('habits')}>
                Ver Hábitos
              </button>
            </div>

            <div className="area-card">
              <h3>💪 Saúde</h3>
              <p>Acompanhe peso, medidas e evolução física</p>
              <button className="area-button" onClick={() => onNavigate('health')}>
                Ver Métricas
              </button>
            </div>

            <div className="area-card">
              <h3>📈 Progresso</h3>
              <p>Visualize sua jornada de transformação</p>
              <button className="area-button" onClick={() => onNavigate('progress')}>
                Ver Gráficos
              </button>
            </div>
          </section>
        </div>
      </main>
    </div>
  );
};

export default Dashboard;
