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

export default function Reports() {
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [report, setReport] = useState(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleGenerate = async (e) => {
    e.preventDefault();
    setError('');
    setReport(null);

    if (!startDate || !endDate) {
      setError('Please select both start and end dates.');
      return;
    }

    if (startDate > endDate) {
      setError('Start date must be before or equal to end date.');
      return;
    }

    setLoading(true);
    try {
      const res = await api.get('/reports/summary', {
        params: { start_date: startDate, end_date: endDate },
      });
      setReport(res.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="page">
      <header className="page-header">
        <div>
          <h1>Report Generation</h1>
          <p>Filter appointments and patients attended by date range</p>
        </div>
      </header>

      <div className="card form-card">
        <form onSubmit={handleGenerate} className="report-filter-form">
          <div className="form-group">
            <label htmlFor="start_date">Start Date</label>
            <input
              id="start_date"
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="end_date">End Date</label>
            <input
              id="end_date"
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              required
            />
          </div>
          <button type="submit" className="btn btn-primary" disabled={loading}>
            {loading ? 'Generating...' : 'Generate Report'}
          </button>
        </form>
      </div>

      {error && <div className="alert alert-error">{error}</div>}

      {report && (
        <>
          <div className="stats-grid">
            <div className="stat-card highlight">
              <span className="stat-label">Total Appointments</span>
              <span className="stat-value">{report.total_appointments}</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">Completed</span>
              <span className="stat-value">{report.total_completed}</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">Cancelled</span>
              <span className="stat-value">{report.total_cancelled}</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">Patients Attended</span>
              <span className="stat-value">{report.patients_attended?.length || 0}</span>
            </div>
          </div>

          <div className="card">
            <h2>
              Patients Attended ({report.start_date} to {report.end_date})
            </h2>
            {report.patients_attended?.length === 0 ? (
              <p className="text-muted">No patients attended in this period.</p>
            ) : (
              <div className="table-responsive">
                <table>
                  <thead>
                    <tr>
                      <th>Name</th>
                      <th>Gender</th>
                      <th>Phone</th>
                      <th>Report Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {report.patients_attended.map((p) => (
                      <tr key={`${p.id}-${p.report_date}`}>
                        <td>{p.full_name}</td>
                        <td>{p.gender}</td>
                        <td>{p.phone_number}</td>
                        <td>{p.report_date?.split('T')[0]}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          <div className="card">
            <h2>Appointments in Period</h2>
            {report.appointments?.length === 0 ? (
              <p className="text-muted">No appointments in this period.</p>
            ) : (
              <div className="table-responsive">
                <table>
                  <thead>
                    <tr>
                      <th>Patient</th>
                      <th>Doctor</th>
                      <th>Date</th>
                      <th>Time</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {report.appointments.map((a) => (
                      <tr key={a.id}>
                        <td>{a.patient_name}</td>
                        <td>{a.doctor_name}</td>
                        <td>{a.appointment_date?.split('T')[0]}</td>
                        <td>{a.appointment_time?.slice(0, 5)}</td>
                        <td>
                          <span className={`status-badge status-${a.status}`}>
                            {a.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
