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

const emptyForm = {
  fullName: '',
  gender: 'Male',
  dateOfBirth: '',
  phone: '',
  address: '',
};

function Patients() {
  const [patients, setPatients] = 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 loadPatients = async () => {
    try {
      const response = await api.get('/patients');
      setPatients(response.data.patients);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to load patients');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleEdit = (patient) => {
    setEditId(patient.id);
    setForm({
      fullName: patient.fullName,
      gender: patient.gender,
      dateOfBirth: patient.dateOfBirth,
      phone: patient.phone,
      address: patient.address,
    });
    setError('');
    setMessage('');
  };

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

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this patient record?')) return;
    setError('');
    try {
      await api.delete(`/patients/${id}`);
      setMessage('Patient deleted successfully');
      if (editId === id) handleCancelEdit();
      loadPatients();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
    }
  };

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

    try {
      if (editId) {
        await api.put(`/patients/${editId}`, form);
        setMessage('Patient updated successfully');
      } else {
        await api.post('/patients', form);
        setMessage('Patient added successfully');
      }
      setForm(emptyForm);
      setEditId(null);
      loadPatients();
    } catch (err) {
      setError(err.response?.data?.message || 'Save failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-5xl">
      <h1 className="text-2xl font-bold text-slate-800 mb-6">Patient 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">
          {editId ? 'Edit patient' : 'Register new patient'}
        </h2>
        <form onSubmit={handleSubmit} className="grid gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-slate-700 mb-1">Full name</label>
            <input
              name="fullName"
              required
              value={form.fullName}
              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">Gender</label>
            <select
              name="gender"
              value={form.gender}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            >
              <option>Male</option>
              <option>Female</option>
              <option>Other</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Date of birth</label>
            <input
              name="dateOfBirth"
              type="date"
              required
              value={form.dateOfBirth}
              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">Phone</label>
            <input
              name="phone"
              required
              value={form.phone}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-slate-700 mb-1">Address</label>
            <textarea
              name="address"
              rows={2}
              required
              value={form.address}
              onChange={handleChange}
              className="w-full border border-slate-300 rounded px-3 py-2"
            />
          </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' : 'Add patient'}
            </button>
            {editId && (
              <button
                type="button"
                onClick={handleCancelEdit}
                className="border border-slate-300 px-4 py-2 rounded hover:bg-slate-50"
              >
                Cancel
              </button>
            )}
          </div>
        </form>
      </section>

      <section>
        <h2 className="text-lg font-semibold text-slate-800 mb-4">All patients</h2>
        {loading ? (
          <p className="text-slate-500">Loading...</p>
        ) : patients.length === 0 ? (
          <p className="text-slate-500">No patients registered 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">Name</th>
                  <th className="px-4 py-2">Gender</th>
                  <th className="px-4 py-2">DOB</th>
                  <th className="px-4 py-2">Phone</th>
                  <th className="px-4 py-2">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {patients.map((p) => (
                  <tr key={p.id}>
                    <td className="px-4 py-2">{p.fullName}</td>
                    <td className="px-4 py-2">{p.gender}</td>
                    <td className="px-4 py-2">{p.dateOfBirth}</td>
                    <td className="px-4 py-2">{p.phone}</td>
                    <td className="px-4 py-2 space-x-2">
                      <button type="button" onClick={() => handleEdit(p)} className="text-teal-600 hover:underline">
                        Edit
                      </button>
                      <button type="button" onClick={() => handleDelete(p.id)} className="text-red-600 hover:underline">
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}

export default Patients;
