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

const Reports = () => {
  const [patientReport, setPatientReport] = useState(null);
  const [doctorReport, setDoctorReport] = useState(null);
  const [appointmentReport, setAppointmentReport] = useState(null);
  const [loading, setLoading] = useState(true);

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

  const fetchReports = async () => {
    try {
      const [patientRes, doctorRes, appointmentRes] = await Promise.all([
        reportsAPI.getPatientsReport(),
        reportsAPI.getDoctorsReport(),
        reportsAPI.getAppointmentsReport()
      ]);
      setPatientReport(patientRes.data);
      setDoctorReport(doctorRes.data);
      setAppointmentReport(appointmentRes.data);
    } catch (error) {
      console.error('Error fetching reports:', error);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div>
      <div className="page-header">
        <h1>Reports</h1>
        <p>View hospital statistics and reports</p>
      </div>

      <div className="report-grid">
        {/* Patient Report */}
        <div className="report-card">
          <h3>📊 Patient Statistics</h3>
          <div className="report-item">
            <span className="label">Total Patients</span>
            <span className="value">{patientReport?.totalPatients || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">New This Month</span>
            <span className="value">{patientReport?.newPatientsThisMonth || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">Male Patients</span>
            <span className="value">{patientReport?.genderDistribution?.male || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">Female Patients</span>
            <span className="value">{patientReport?.genderDistribution?.female || 0}</span>
          </div>
          
          <h4 style={{ marginTop: '16px', marginBottom: '8px', color: '#666' }}>Blood Group Distribution</h4>
          {patientReport?.bloodGroupStats?.map((item, index) => (
            <div key={index} className="report-item">
              <span className="label">{item._id || 'Unknown'}</span>
              <span className="value">{item.count}</span>
            </div>
          ))}
        </div>

        {/* Doctor Report */}
        <div className="report-card">
          <h3>👨‍⚕️ Doctor Statistics</h3>
          <div className="report-item">
            <span className="label">Total Doctors</span>
            <span className="value">{doctorReport?.totalDoctors || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">Avg. Experience</span>
            <span className="value">{doctorReport?.avgExperience?.toFixed(1) || 0} years</span>
          </div>
          
          <h4 style={{ marginTop: '16px', marginBottom: '8px', color: '#666' }}>Specialty Distribution</h4>
          {doctorReport?.specialtyStats?.slice(0, 5).map((item, index) => (
            <div key={index} className="report-item">
              <span className="label">{item._id || 'Unknown'}</span>
              <span className="value">{item.count}</span>
            </div>
          ))}
          
          <h4 style={{ marginTop: '16px', marginBottom: '8px', color: '#666' }}>Department Distribution</h4>
          {doctorReport?.departmentStats?.slice(0, 5).map((item, index) => (
            <div key={index} className="report-item">
              <span className="label">{item._id || 'Unknown'}</span>
              <span className="value">{item.count}</span>
            </div>
          ))}
        </div>

        {/* Appointment Report */}
        <div className="report-card">
          <h3>📅 Appointment Statistics</h3>
          <div className="report-item">
            <span className="label">Total Appointments</span>
            <span className="value">{appointmentReport?.totalAppointments || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">This Month</span>
            <span className="value">{appointmentReport?.appointmentsThisMonth || 0}</span>
          </div>
          <div className="report-item">
            <span className="label">Scheduled</span>
            <span className="value" style={{ color: '#ff9900' }}>
              {appointmentReport?.statusDistribution?.scheduled || 0}
            </span>
          </div>
          <div className="report-item">
            <span className="label">Completed</span>
            <span className="value" style={{ color: '#00cc66' }}>
              {appointmentReport?.statusDistribution?.completed || 0}
            </span>
          </div>
          <div className="report-item">
            <span className="label">Cancelled</span>
            <span className="value" style={{ color: '#cc3300' }}>
              {appointmentReport?.statusDistribution?.cancelled || 0}
            </span>
          </div>
          
          <h4 style={{ marginTop: '16px', marginBottom: '8px', color: '#666' }}>Last 7 Days</h4>
          {appointmentReport?.last7Days?.map((item, index) => (
            <div key={index} className="report-item">
              <span className="label">{item.date}</span>
              <span className="value">{item.count}</span>
            </div>
          ))}
        </div>

        {/* Top Doctors */}
        <div className="report-card">
          <h3>🏆 Top Doctors</h3>
          {appointmentReport?.topDoctors?.length > 0 ? (
            appointmentReport.topDoctors.map((doctor, index) => (
              <div key={index} className="report-item">
                <span className="label">
                  {index + 1}. Dr. {doctor.name}
                </span>
                <span className="value">{doctor.count} appointments</span>
              </div>
            ))
          ) : (
            <p style={{ color: '#666', textAlign: 'center', padding: '20px' }}>
              No appointment data available
            </p>
          )}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="stats-grid" style={{ marginTop: '30px' }}>
        <div className="stat-card">
          <h3>Total Patients</h3>
          <div className="value">{patientReport?.totalPatients || 0}</div>
        </div>
        <div className="stat-card">
          <h3>Total Doctors</h3>
          <div className="value accent">{doctorReport?.totalDoctors || 0}</div>
        </div>
        <div className="stat-card">
          <h3>Total Appointments</h3>
          <div className="value warning">{appointmentReport?.totalAppointments || 0}</div>
        </div>
        <div className="stat-card">
          <h3>Completion Rate</h3>
          <div className="value danger">
            {appointmentReport?.totalAppointments > 0
              ? Math.round(
                  (appointmentReport.statusDistribution.completed /
                    appointmentReport.totalAppointments) *
                    100
                )
              : 0}
            %
          </div>
        </div>
      </div>
    </div>
  );
};

export default Reports;
