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

const emptyForm = {
  full_name: '',
  gender: 'Male',
  date_of_birth: '',
  phone_number: '',
  address: '',
};

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

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

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

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

  const handleEdit = (patient) => {
    setForm({
      full_name: patient.full_name,
      gender: patient.gender,
      date_of_birth: patient.date_of_birth?.split('T')[0] || patient.date_of_birth,
      phone_number: patient.phone_number,
      address: patient.address,
    });
    setEditingId(patient.id);
    setShowForm(true);
  };

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

  const cancelForm = () => {
    setForm(emptyForm);
    setEditingId(null);
    setShowForm(false);
  };

  return (
    <div className="page">
      <header className="page-header">
        <div>
          <h1>Patient Management</h1>
          <p>Register and manage patient records</p>
        </div>
        <button
          type="button"
          className="btn btn-primary"
          onClick={() => {
            setShowForm(!showForm);
            if (showForm) cancelForm();
          }}
        >
          {showForm ? 'Close Form' : '+ Add Patient'}
        </button>
      </header>

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

      {showForm && (
        <div className="card form-card">
          <h2>{editingId ? 'Update Patient' : 'New Patient'}</h2>
          <form onSubmit={handleSubmit} className="form-grid">
            <div className="form-group">
              <label>Full Name</label>
              <input name="full_name" value={form.full_name} onChange={handleChange} required />
            </div>
            <div className="form-group">
              <label>Gender</label>
              <select name="gender" value={form.gender} onChange={handleChange}>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
                <option value="Other">Other</option>
              </select>
            </div>
            <div className="form-group">
              <label>Date of Birth</label>
              <input
                name="date_of_birth"
                type="date"
                value={form.date_of_birth}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label>Phone Number</label>
              <input name="phone_number" value={form.phone_number} onChange={handleChange} required />
            </div>
            <div className="form-group full-width">
              <label>Address</label>
              <textarea name="address" value={form.address} onChange={handleChange} rows={2} required />
            </div>
            <div className="form-actions full-width">
              <button type="submit" className="btn btn-primary">
                {editingId ? 'Update' : 'Save'} Patient
              </button>
              <button type="button" className="btn btn-outline" onClick={cancelForm}>
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}

      <div className="card">
        {loading ? (
          <p className="text-muted">Loading patients...</p>
        ) : patients.length === 0 ? (
          <p className="text-muted">No patients registered yet.</p>
        ) : (
          <div className="table-responsive">
            <table>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Gender</th>
                  <th>Date of Birth</th>
                  <th>Phone</th>
                  <th>Address</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {patients.map((p) => (
                  <tr key={p.id}>
                    <td>{p.full_name}</td>
                    <td>{p.gender}</td>
                    <td>{p.date_of_birth?.split('T')[0]}</td>
                    <td>{p.phone_number}</td>
                    <td>{p.address}</td>
                    <td className="actions">
                      <button type="button" className="btn btn-sm btn-outline" onClick={() => handleEdit(p)}>
                        Edit
                      </button>
                      <button type="button" className="btn btn-sm btn-danger" onClick={() => handleDelete(p.id)}>
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
