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

function MedicalReports() {
  const [appointments, setAppointments] = useState([]);
  const [reports, setReports] = useState([]);
  const [form, setForm] = useState({
    appointmentId: '',
    diagnosis: '',
    prescription: '',
    reportDate: new Date().toISOString().slice(0, 10),
  });
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  const loadData = async () => {
    try {
      const [apptRes, reportRes] = await Promise.all([
        api.get('/appointments'),
        api.get('/medical-reports'),
      ]);
      const eligible = apptRes.data.appointments.filter(
        (a) => a.status !== 'cancelled' && !a.hasReport,
      );
      setAppointments(eligible);
      setReports(reportRes.data.reports);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load data');
    } finally {
      setLoading(false);
    }
  };

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

  const handleChange = (e) => {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError('');
    setMessage('');

    try {
      await api.post('/medical-reports', {
        appointmentId: Number(form.appointmentId),
        diagnosis: form.diagnosis,
        prescription: form.prescription,
        reportDate: form.reportDate,
      });
      setMessage('Medical report saved');
      setForm({
        appointmentId: '',
        diagnosis: '',
        prescription: '',
        reportDate: new Date().toISOString().slice(0, 10),
      });
      loadData();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save report');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-5xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-6">Medical Report Management</h1>

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

      <section className="bg-white rounded-lg shadow-md p-6 mb-8">
        <h2 className="text-lg font-semibold text-slate-800 mb-4">Add medical report</h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Assigned appointment</label>
            <select
              name="appointmentId"
              required
              value={form.appointmentId}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            >
              <option value="">Select appointment</option>
              {appointments.map((a) => (
                <option key={a.id} value={a.id}>
                  {a.patientName} — {a.appointmentDate} {a.appointmentTime?.slice(0, 5)} ({a.status})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Diagnosis</label>
            <textarea
              name="diagnosis"
              rows={3}
              required
              value={form.diagnosis}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Prescription</label>
            <textarea
              name="prescription"
              rows={3}
              required
              value={form.prescription}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Report date</label>
            <input
              name="reportDate"
              type="date"
              required
              value={form.reportDate}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2 max-w-xs"
            />
          </div>
          <button
            type="submit"
            disabled={submitting}
            className="bg-teal-600 text-white font-medium px-4 py-2 rounded hover:bg-teal-700 disabled:opacity-50"
          >
            {submitting ? 'Saving...' : 'Save report'}
          </button>
        </form>
      </section>

      <section>
        <h2 className="text-lg font-semibold text-slate-800 mb-4">Saved medical reports</h2>
        {loading ? (
          <p className="text-slate-500">Loading...</p>
        ) : reports.length === 0 ? (
          <p className="text-slate-500">No medical reports yet.</p>
        ) : (
          <div className="space-y-4">
            {reports.map((r) => (
              <article key={r.id} className="bg-white rounded-lg border border-slate-200 p-5">
                <div className="flex flex-wrap justify-between gap-2 mb-3">
                  <div>
                    <p className="font-semibold text-slate-800">{r.patientName}</p>
                    <p className="text-sm text-slate-500">Dr. {r.doctorName}</p>
                  </div>
                  <p className="text-sm text-slate-500">Report date: {r.reportDate}</p>
                </div>
                <p className="text-sm text-slate-700">
                  <span className="font-medium">Diagnosis:</span> {r.diagnosis}
                </p>
                <p className="text-sm text-slate-700 mt-2">
                  <span className="font-medium">Prescription:</span> {r.prescription}
                </p>
              </article>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

export default MedicalReports;
