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

const emptyForm = {
  patientId: '',
  doctorId: '',
  appointmentDate: '',
  appointmentTime: '',
  status: 'scheduled',
};

function Appointments() {
  const user = getStoredUser();
  const isReceptionist = user?.role === 'receptionist';

  const [appointments, setAppointments] = useState([]);
  const [patients, setPatients] = useState([]);
  const [doctors, setDoctors] = useState([]);
  const [form, setForm] = useState(emptyForm);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  const loadData = async () => {
    try {
      const requests = [api.get('/appointments')];
      if (isReceptionist) {
        requests.push(api.get('/patients'), api.get('/auth/doctors'));
      }
      const results = await Promise.all(requests);
      setAppointments(results[0].data.appointments);
      if (isReceptionist) {
        setPatients(results[1].data.patients);
        setDoctors(results[2].data.doctors);
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load appointments');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleEdit = (appt) => {
    setEditId(appt.id);
    setForm({
      patientId: String(appt.patientId),
      doctorId: String(appt.doctorId),
      appointmentDate: appt.appointmentDate,
      appointmentTime: appt.appointmentTime?.slice(0, 5) || appt.appointmentTime,
      status: appt.status,
    });
    setError('');
    setMessage('');
  };

  const handleCancelEdit = () => {
    setEditId(null);
    setForm(emptyForm);
  };

  const handleCancelAppointment = async (id) => {
    if (!window.confirm('Cancel this appointment?')) return;
    try {
      await api.patch(`/appointments/${id}/cancel`);
      setMessage('Appointment cancelled');
      loadData();
    } catch (err) {
      setError(err.response?.data?.message || 'Cancel failed');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this appointment permanently?')) return;
    try {
      await api.delete(`/appointments/${id}`);
      setMessage('Appointment deleted');
      if (editId === id) handleCancelEdit();
      loadData();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
    }
  };

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

    const payload = {
      patientId: Number(form.patientId),
      doctorId: Number(form.doctorId),
      appointmentDate: form.appointmentDate,
      appointmentTime: form.appointmentTime,
      status: form.status,
    };

    try {
      if (editId) {
        await api.put(`/appointments/${editId}`, payload);
        setMessage('Appointment updated');
      } else {
        await api.post('/appointments', payload);
        setMessage('Appointment created');
      }
      setForm(emptyForm);
      setEditId(null);
      loadData();
    } catch (err) {
      setError(err.response?.data?.message || 'Save failed');
    } finally {
      setSubmitting(false);
    }
  };

  const statusClass = (status) => {
    if (status === 'completed') return 'text-green-700 bg-green-50';
    if (status === 'cancelled') return 'text-red-700 bg-red-50';
    return 'text-amber-700 bg-amber-50';
  };

  return (
    <div className="max-w-6xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-6">
        {isReceptionist ? 'Appointment Management' : 'My Appointments'}
      </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>
      )}

      {isReceptionist && (
        <section className="bg-white rounded-lg shadow-md p-6 mb-8">
          <h2 className="text-lg font-semibold text-slate-800 mb-4">
            {editId ? 'Edit appointment' : 'Book appointment'}
          </h2>
          <form onSubmit={handleSubmit} className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Patient</label>
              <select
                name="patientId"
                required
                value={form.patientId}
                onChange={handleChange}
                className="w-full border border-slate-300 rounded px-3 py-2"
              >
                <option value="">Select patient</option>
                {patients.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.fullName}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Doctor</label>
              <select
                name="doctorId"
                required
                value={form.doctorId}
                onChange={handleChange}
                className="w-full border border-slate-300 rounded px-3 py-2"
              >
                <option value="">Select doctor</option>
                {doctors.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.name}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Date</label>
              <input
                name="appointmentDate"
                type="date"
                required
                value={form.appointmentDate}
                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">Time</label>
              <input
                name="appointmentTime"
                type="time"
                required
                value={form.appointmentTime}
                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">Status</label>
              <select
                name="status"
                value={form.status}
                onChange={handleChange}
                className="w-full border border-slate-300 rounded px-3 py-2"
              >
                <option value="scheduled">Scheduled</option>
                <option value="completed">Completed</option>
                <option value="cancelled">Cancelled</option>
              </select>
            </div>
            <div className="sm:col-span-2 flex gap-2">
              <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...' : editId ? 'Update' : 'Create'}
              </button>
              {editId && (
                <button type="button" onClick={handleCancelEdit} className="border border-slate-300 px-4 py-2 rounded">
                  Cancel
                </button>
              )}
            </div>
          </form>
        </section>
      )}

      <section>
        <h2 className="text-lg font-semibold text-slate-800 mb-4">
          {isReceptionist ? 'All appointments' : 'Assigned to you'}
        </h2>
        {loading ? (
          <p className="text-slate-500">Loading...</p>
        ) : appointments.length === 0 ? (
          <p className="text-slate-500">No appointments yet.</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>
                  {isReceptionist && <th className="px-4 py-2">Actions</th>}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {appointments.map((a) => (
                  <tr key={a.id}>
                    <td className="px-4 py-2">{a.patientName}</td>
                    <td className="px-4 py-2">{a.doctorName}</td>
                    <td className="px-4 py-2">{a.appointmentDate}</td>
                    <td className="px-4 py-2">{a.appointmentTime?.slice(0, 5)}</td>
                    <td className="px-4 py-2">
                      <span className={`px-2 py-0.5 rounded text-xs font-medium capitalize ${statusClass(a.status)}`}>
                        {a.status}
                      </span>
                    </td>
                    {isReceptionist && (
                      <td className="px-4 py-2 space-x-2 whitespace-nowrap">
                        <button type="button" onClick={() => handleEdit(a)} className="text-teal-600 hover:underline">
                          Edit
                        </button>
                        {a.status !== 'cancelled' && (
                          <button
                            type="button"
                            onClick={() => handleCancelAppointment(a.id)}
                            className="text-amber-600 hover:underline"
                          >
                            Cancel
                          </button>
                        )}
                        <button type="button" onClick={() => handleDelete(a.id)} className="text-red-600 hover:underline">
                          Delete
                        </button>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}

export default Appointments;
