import { useState, useEffect } from 'react';
import { reportsAPI } from '../services/api';

const Dashboard = () => {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);

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

  const fetchDashboardData = async () => {
    try {
      const response = await reportsAPI.getOverview();
      setStats(response.data);
    } catch (error) {
      console.error('Error fetching dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
      </div>
    );
  }

  return (
    <div>
      <div className="page-header">
        <h1>Dashboard</h1>
        <p>Welcome to Hospital Management System</p>
      </div>

      <div className="stats-grid">
        <div className="stat-card">
          <h3>Total Patients</h3>
          <div className="value">{stats?.totalPatients || 0}</div>
        </div>
        
        <div className="stat-card">
          <h3>Total Doctors</h3>
          <div className="value accent">{stats?.totalDoctors || 0}</div>
        </div>
        
        <div className="stat-card">
          <h3>Scheduled Appointments</h3>
          <div className="value warning">{stats?.scheduledAppointments || 0}</div>
        </div>
        
        <div className="stat-card">
          <h3>Completed Appointments</h3>
          <div className="value danger">{stats?.completedAppointments || 0}</div>
        </div>
      </div>

      <div className="table-container">
        <div className="table-header">
          <h2>Recent Appointments</h2>
        </div>
        
        {stats?.recentAppointments?.length > 0 ? (
          <table>
            <thead>
              <tr>
                <th>Patient</th>
                <th>Doctor</th>
                <th>Date</th>
                <th>Time</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {stats.recentAppointments.map((appointment) => (
                <tr key={appointment._id}>
                  <td>{appointment.patient?.name || 'N/A'}</td>
                  <td>Dr. {appointment.doctor?.name || 'N/A'}</td>
                  <td>{new Date(appointment.date).toLocaleDateString()}</td>
                  <td>{appointment.time}</td>
                  <td>
                    <span className={`badge badge-${
                      appointment.status === 'completed' ? 'success' :
                      appointment.status === 'cancelled' ? 'danger' : 'warning'
                    }`}>
                      {appointment.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="empty-state">
            <p>No recent appointments</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;
