import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../services/api';
import { useAuth } from '../context/AuthContext';

export default function Dashboard() {
  const { user } = useAuth();
  const [stats, setStats] = useState({
    patients: 0,
    appointments: 0,
    completed: 0,
    reports: 0,
  });

  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    const startOfMonth = new Date();
    startOfMonth.setDate(1);
    const start = startOfMonth.toISOString().split('T')[0];

    const fetchStats = async () => {
      try {
        const promises = [
          user.role === 'receptionist'
            ? api.get('/patients').then((r) => r.data.length)
            : Promise.resolve(0),
          api.get('/appointments').then((r) => r.data),
          api.get('/reports/summary', { params: { start_date: start, end_date: today } }),
          user.role === 'doctor'
            ? api.get('/medical-reports').then((r) => r.data.length)
            : Promise.resolve(0),
        ];

        const [patientCount, appointments, reportData, reportCount] =
          await Promise.all(promises);

        setStats({
          patients: patientCount,
          appointments: appointments.length,
          completed: reportData.data.total_completed,
          reports: user.role === 'doctor' ? reportCount : reportData.data.patients_attended?.length || 0,
        });
      } catch {
        /* stats optional */
      }
    };

    fetchStats();
  }, [user.role]);

  return (
    <div className="page">
      <header className="page-header">
        <div>
          <h1>Dashboard</h1>
          <p>Welcome back, {user?.full_name}</p>
        </div>
      </header>

      <div className="stats-grid">
        {user.role === 'receptionist' && (
          <div className="stat-card">
            <span className="stat-label">Registered Patients</span>
            <span className="stat-value">{stats.patients}</span>
          </div>
        )}
        <div className="stat-card">
          <span className="stat-label">Appointments</span>
          <span className="stat-value">{stats.appointments}</span>
        </div>
        <div className="stat-card">
          <span className="stat-label">Completed (This Month)</span>
          <span className="stat-value">{stats.completed}</span>
        </div>
        <div className="stat-card">
          <span className="stat-label">
            {user.role === 'doctor' ? 'Medical Reports' : 'Patients Attended'}
          </span>
          <span className="stat-value">{stats.reports}</span>
        </div>
      </div>

      <div className="quick-actions">
        <h2>Quick Actions</h2>
        <div className="action-grid">
          {user.role === 'receptionist' && (
            <>
              <Link to="/patients" className="action-card">
                <h3>Manage Patients</h3>
                <p>Add, update, or view patient records</p>
              </Link>
              <Link to="/appointments" className="action-card">
                <h3>Appointments</h3>
                <p>Schedule and manage appointments</p>
              </Link>
            </>
          )}
          {user.role === 'doctor' && (
            <Link to="/medical-reports" className="action-card">
              <h3>Medical Reports</h3>
              <p>View appointments and save diagnoses</p>
            </Link>
          )}
          <Link to="/appointments" className="action-card">
            <h3>View Appointments</h3>
            <p>See all scheduled visits</p>
          </Link>
          <Link to="/reports" className="action-card">
            <h3>Generate Reports</h3>
            <p>Filter by date and view statistics</p>
          </Link>
        </div>
      </div>
    </div>
  );
}
