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

function Report() {
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [data, setData] = useState(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleGenerate = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    setData(null);

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

  return (
    <div className="max-w-6xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-2">Hospital Reports</h1>
      <p className="text-slate-600 mb-6">
        Filter appointments and patients attended between selected dates.
      </p>

      <form onSubmit={handleGenerate} className="bg-white rounded-lg shadow-md p-6 mb-8 flex flex-wrap gap-4 items-end">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Start date</label>
          <input
            type="date"
            required
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            className="border border-slate-300 rounded px-3 py-2"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">End date</label>
          <input
            type="date"
            required
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            className="border border-slate-300 rounded px-3 py-2"
          />
        </div>
        <button
          type="submit"
          disabled={loading}
          className="bg-teal-600 text-white font-medium px-5 py-2 rounded hover:bg-teal-700 disabled:opacity-50"
        >
          {loading ? 'Generating...' : 'Generate report'}
        </button>
      </form>

      {error && (
        <p className="mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">
          {error}
        </p>
      )}

      {data && (
        <div className="space-y-8">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <div className="bg-white rounded-lg border border-slate-200 p-5">
              <p className="text-sm text-slate-500">Total appointments</p>
              <p className="text-3xl font-bold text-slate-800 mt-1">{data.summary.totalAppointments}</p>
            </div>
            <div className="bg-white rounded-lg border border-slate-200 p-5">
              <p className="text-sm text-slate-500">Completed</p>
              <p className="text-3xl font-bold text-green-700 mt-1">{data.summary.totalCompleted}</p>
            </div>
            <div className="bg-white rounded-lg border border-slate-200 p-5">
              <p className="text-sm text-slate-500">Cancelled</p>
              <p className="text-3xl font-bold text-red-700 mt-1">{data.summary.totalCancelled}</p>
            </div>
            <div className="bg-white rounded-lg border border-slate-200 p-5">
              <p className="text-sm text-slate-500">Patients attended</p>
              <p className="text-3xl font-bold text-teal-700 mt-1">{data.summary.patientsAttended}</p>
            </div>
          </div>

          <section>
            <h2 className="text-lg font-semibold text-slate-800 mb-3">
              Appointments ({data.startDate} to {data.endDate})
            </h2>
            {data.appointments.length === 0 ? (
              <p className="text-slate-500 text-sm">No appointments in this period.</p>
            ) : (
              <div className="overflow-x-auto bg-white rounded-lg border border-slate-200">
                <table className="w-full text-sm text-left">
                  <thead className="bg-slate-50 text-slate-600">
                    <tr>
                      <th className="px-4 py-2">Patient</th>
                      <th className="px-4 py-2">Doctor</th>
                      <th className="px-4 py-2">Date</th>
                      <th className="px-4 py-2">Time</th>
                      <th className="px-4 py-2">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-200">
                    {data.appointments.map((a) => (
                      <tr key={a.id}>
                        <td className="px-4 py-2">{a.patient_name}</td>
                        <td className="px-4 py-2">{a.doctor_name}</td>
                        <td className="px-4 py-2">{a.appointment_date}</td>
                        <td className="px-4 py-2">{String(a.appointment_time).slice(0, 5)}</td>
                        <td className="px-4 py-2 capitalize">{a.status}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>

          <section>
            <h2 className="text-lg font-semibold text-slate-800 mb-3">Patients attended</h2>
            {data.patientsAttended.length === 0 ? (
              <p className="text-slate-500 text-sm">No completed visits in this period.</p>
            ) : (
              <ul className="bg-white rounded-lg border border-slate-200 divide-y divide-slate-200">
                {data.patientsAttended.map((p) => (
                  <li key={p.id} className="px-4 py-3 text-sm flex justify-between">
                    <span className="font-medium text-slate-800">{p.patient_name}</span>
                    <span className="text-slate-500">{p.phone}</span>
                  </li>
                ))}
              </ul>
            )}
          </section>

          <section>
            <h2 className="text-lg font-semibold text-slate-800 mb-3">Medical reports</h2>
            {data.medicalReports.length === 0 ? (
              <p className="text-slate-500 text-sm">No medical reports in this period.</p>
            ) : (
              <div className="space-y-3">
                {data.medicalReports.map((r) => (
                  <article key={r.id} className="bg-white rounded-lg border border-slate-200 p-4 text-sm">
                    <p className="font-medium text-slate-800">
                      {r.patient_name} — Dr. {r.doctor_name} ({r.report_date})
                    </p>
                    <p className="mt-1 text-slate-600">Diagnosis: {r.diagnosis}</p>
                    <p className="mt-1 text-slate-600">Prescription: {r.prescription}</p>
                  </article>
                ))}
              </div>
            )}
          </section>
        </div>
      )}
    </div>
  );
}

export default Report;
