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

const emptyReport = {
  appointment_id: '',
  diagnosis: '',
  prescription: '',
  report_date: new Date().toISOString().split('T')[0],
};

export default function MedicalReports() {
  const [assignedAppointments, setAssignedAppointments] = useState([]);
  const [reports, setReports] = useState([]);
  const [form, setForm] = useState(emptyReport);
  const [showForm, setShowForm] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    try {
      const [apptRes, reportRes] = await Promise.all([
        api.get('/appointments/assigned'),
        api.get('/medical-reports'),
      ]);
      setAssignedAppointments(apptRes.data);
      setReports(reportRes.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load data.');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    try {
      await api.post('/medical-reports', form);
      setSuccess('Medical report saved successfully.');
      setForm(emptyReport);
      setShowForm(false);
      fetchData();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save report.');
    }
  };

  const selectAppointment = (appt) => {
    setForm({
      ...emptyReport,
      appointment_id: appt.id,
    });
    setShowForm(true);
  };

  return (
    <div className="page">
      <header className="page-header">
        <div>
          <h1>Medical Report Management</h1>
          <p>View assigned appointments and create medical reports</p>
        </div>
        <button
          type="button"
          className="btn btn-primary"
          onClick={() => setShowForm(!showForm)}
        >
          {showForm ? 'Close Form' : '+ New Report'}
        </button>
      </header>

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

      <div className="card">
        <h2>Assigned Appointments (Scheduled)</h2>
        {loading ? (
          <p className="text-muted">Loading...</p>
        ) : assignedAppointments.length === 0 ? (
          <p className="text-muted">No scheduled appointments assigned to you.</p>
        ) : (
          <div className="table-responsive">
            <table>
              <thead>
                <tr>
                  <th>Patient</th>
                  <th>Date</th>
                  <th>Time</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                {assignedAppointments.map((a) => (
                  <tr key={a.id}>
                    <td>{a.patient_name}</td>
                    <td>{a.appointment_date?.split('T')[0]}</td>
                    <td>{a.appointment_time?.slice(0, 5)}</td>
                    <td>
                      <button
                        type="button"
                        className="btn btn-sm btn-primary"
                        onClick={() => selectAppointment(a)}
                      >
                        Add Report
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {showForm && (
        <div className="card form-card">
          <h2>Create Medical Report</h2>
          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label>Appointment</label>
              <select
                name="appointment_id"
                value={form.appointment_id}
                onChange={handleChange}
                required
              >
                <option value="">Select appointment</option>
                {assignedAppointments.map((a) => (
                  <option key={a.id} value={a.id}>
                    {a.patient_name} — {a.appointment_date?.split('T')[0]} {a.appointment_time?.slice(0, 5)}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label>Diagnosis</label>
              <textarea
                name="diagnosis"
                value={form.diagnosis}
                onChange={handleChange}
                rows={3}
                required
                placeholder="Enter diagnosis..."
              />
            </div>
            <div className="form-group">
              <label>Prescription</label>
              <textarea
                name="prescription"
                value={form.prescription}
                onChange={handleChange}
                rows={3}
                required
                placeholder="Enter prescription..."
              />
            </div>
            <div className="form-group">
              <label>Report Date</label>
              <input
                name="report_date"
                type="date"
                value={form.report_date}
                onChange={handleChange}
                required
              />
            </div>
            <button type="submit" className="btn btn-primary">
              Save Medical Report
            </button>
          </form>
        </div>
      )}

      <div className="card">
        <h2>Saved Medical Reports</h2>
        {reports.length === 0 ? (
          <p className="text-muted">No medical reports yet.</p>
        ) : (
          <div className="table-responsive">
            <table>
              <thead>
                <tr>
                  <th>Patient</th>
                  <th>Doctor</th>
                  <th>Diagnosis</th>
                  <th>Prescription</th>
                  <th>Report Date</th>
                </tr>
              </thead>
              <tbody>
                {reports.map((r) => (
                  <tr key={r.id}>
                    <td>{r.patient_name}</td>
                    <td>{r.doctor_name}</td>
                    <td className="text-wrap">{r.diagnosis}</td>
                    <td className="text-wrap">{r.prescription}</td>
                    <td>{r.report_date?.split('T')[0]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
