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

const emptyForm = {
  patient_id: '',
  doctor_id: '',
  appointment_date: '',
  appointment_time: '',
  status: 'scheduled',
};

export default function Appointments() {
  const { user } = useAuth();
  const isReceptionist = user?.role === 'receptionist';
  const [appointments, setAppointments] = useState([]);
  const [patients, setPatients] = useState([]);
  const [doctors, setDoctors] = useState([]);
  const [form, setForm] = useState(emptyForm);
  const [editingId, setEditingId] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    try {
      const apptRes = await api.get('/appointments');
      setAppointments(apptRes.data);

      if (isReceptionist) {
        const [patRes, docRes] = await Promise.all([
          api.get('/patients'),
          api.get('/auth/doctors'),
        ]);
        setPatients(patRes.data);
        setDoctors(docRes.data);
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load appointments.');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    try {
      if (editingId) {
        await api.put(`/appointments/${editingId}`, form);
      } else {
        await api.post('/appointments', form);
      }
      setForm(emptyForm);
      setEditingId(null);
      setShowForm(false);
      fetchData();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed.');
    }
  };

  const handleEdit = (appt) => {
    setForm({
      patient_id: appt.patient_id,
      doctor_id: appt.doctor_id,
      appointment_date: appt.appointment_date?.split('T')[0],
      appointment_time: appt.appointment_time?.slice(0, 5),
      status: appt.status,
    });
    setEditingId(appt.id);
    setShowForm(true);
  };

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

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

  const statusClass = (status) => `status-badge status-${status}`;

  return (
    <div className="page">
      <header className="page-header">
        <div>
          <h1>Appointment Management</h1>
          <p>{isReceptionist ? 'Schedule and manage patient appointments' : 'Your assigned appointments'}</p>
        </div>
        {isReceptionist && (
          <button
            type="button"
            className="btn btn-primary"
            onClick={() => {
              setShowForm(!showForm);
              if (showForm) {
                setForm(emptyForm);
                setEditingId(null);
              }
            }}
          >
            {showForm ? 'Close Form' : '+ New Appointment'}
          </button>
        )}
      </header>

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

      {showForm && isReceptionist && (
        <div className="card form-card">
          <h2>{editingId ? 'Update Appointment' : 'Create Appointment'}</h2>
          <form onSubmit={handleSubmit} className="form-grid">
            <div className="form-group">
              <label>Patient</label>
              <select name="patient_id" value={form.patient_id} onChange={handleChange} required>
                <option value="">Select patient</option>
                {patients.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.full_name}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label>Doctor</label>
              <select name="doctor_id" value={form.doctor_id} onChange={handleChange} required>
                <option value="">Select doctor</option>
                {doctors.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.full_name}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label>Date</label>
              <input
                name="appointment_date"
                type="date"
                value={form.appointment_date}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Time</label>
              <input
                name="appointment_time"
                type="time"
                value={form.appointment_time}
                onChange={handleChange}
                required
              />
            </div>
            {editingId && (
              <div className="form-group">
                <label>Status</label>
                <select name="status" value={form.status} onChange={handleChange}>
                  <option value="scheduled">Scheduled</option>
                  <option value="completed">Completed</option>
                  <option value="cancelled">Cancelled</option>
                </select>
              </div>
            )}
            <div className="form-actions full-width">
              <button type="submit" className="btn btn-primary">
                {editingId ? 'Update' : 'Create'} Appointment
              </button>
            </div>
          </form>
        </div>
      )}

      <div className="card">
        {loading ? (
          <p className="text-muted">Loading...</p>
        ) : appointments.length === 0 ? (
          <p className="text-muted">No appointments found.</p>
        ) : (
          <div className="table-responsive">
            <table>
              <thead>
                <tr>
                  <th>Patient</th>
                  <th>Doctor</th>
                  <th>Date</th>
                  <th>Time</th>
                  <th>Status</th>
                  {isReceptionist && <th>Actions</th>}
                </tr>
              </thead>
              <tbody>
                {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={statusClass(a.status)}>{a.status}</span>
                    </td>
                    {isReceptionist && (
                      <td className="actions">
                        {a.status !== 'cancelled' && (
                          <button type="button" className="btn btn-sm btn-outline" onClick={() => handleEdit(a)}>
                            Edit
                          </button>
                        )}
                        {a.status === 'scheduled' && (
                          <button type="button" className="btn btn-sm btn-warning" onClick={() => handleCancel(a.id)}>
                            Cancel
                          </button>
                        )}
                        <button type="button" className="btn btn-sm btn-danger" onClick={() => handleDelete(a.id)}>
                          Delete
                        </button>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
