import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  createPatient,
  getPatient,
  updatePatient,
  type PatientInput,
  formatPatientName,
} from "../api/patientApi";

export default function PatientForm() {
  const navigate = useNavigate();
  const { patientId } = useParams();
  const isEditing = !!patientId;

  const [loading, setLoading] = useState(isEditing);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Form state
  const [formData, setFormData] = useState<PatientInput>({
    firstName: "",
    lastName: "",
    mrn: "",
    dateOfBirth: "",
    gender: undefined,
    email: "",
    phone: "",
    address: "",
    diagnosis: "",
    curveType: "",
    medicalHistory: "",
    referringPhysician: "",
    insuranceInfo: "",
    notes: "",
  });

  useEffect(() => {
    if (isEditing) {
      loadPatient();
    }
  }, [patientId]);

  async function loadPatient() {
    try {
      const { patient } = await getPatient(parseInt(patientId!));
      setFormData({
        firstName: patient.first_name,
        lastName: patient.last_name,
        mrn: patient.mrn || "",
        dateOfBirth: patient.date_of_birth || "",
        gender: patient.gender || undefined,
        email: patient.email || "",
        phone: patient.phone || "",
        address: patient.address || "",
        diagnosis: patient.diagnosis || "",
        curveType: patient.curve_type || "",
        medicalHistory: patient.medical_history || "",
        referringPhysician: patient.referring_physician || "",
        insuranceInfo: patient.insurance_info || "",
        notes: patient.notes || "",
      });
    } catch (err: any) {
      setError(err.message || "Failed to load patient");
    } finally {
      setLoading(false);
    }
  }

  function handleChange(
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!formData.firstName.trim() || !formData.lastName.trim()) {
      setError("First name and last name are required");
      return;
    }

    setSaving(true);
    try {
      if (isEditing) {
        await updatePatient(parseInt(patientId!), formData);
        navigate(`/patients/${patientId}`);
      } else {
        const { patient } = await createPatient(formData);
        navigate(`/patients/${patient.id}`);
      }
    } catch (err: any) {
      setError(err.message || "Failed to save patient");
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return <div className="bf-loading">Loading patient...</div>;
  }

  return (
    <div className="bf-patient-form-page">
      <div className="bf-form-header">
        <button
          className="bf-back-btn"
          onClick={() => navigate(isEditing ? `/patients/${patientId}` : "/patients")}
        >
          ← Back
        </button>
        <h1>{isEditing ? "Edit Patient" : "Add New Patient"}</h1>
      </div>

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

      <form onSubmit={handleSubmit} className="bf-patient-form">
        {/* Basic Information */}
        <section className="bf-form-section">
          <h2>Basic Information</h2>
          <div className="bf-form-grid">
            <div className="bf-form-group">
              <label htmlFor="firstName">First Name *</label>
              <input
                type="text"
                id="firstName"
                name="firstName"
                value={formData.firstName}
                onChange={handleChange}
                required
                placeholder="Enter first name"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="lastName">Last Name *</label>
              <input
                type="text"
                id="lastName"
                name="lastName"
                value={formData.lastName}
                onChange={handleChange}
                required
                placeholder="Enter last name"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="mrn">Medical Record Number (MRN)</label>
              <input
                type="text"
                id="mrn"
                name="mrn"
                value={formData.mrn}
                onChange={handleChange}
                placeholder="Enter MRN (optional)"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="dateOfBirth">Date of Birth</label>
              <input
                type="date"
                id="dateOfBirth"
                name="dateOfBirth"
                value={formData.dateOfBirth}
                onChange={handleChange}
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="gender">Gender</label>
              <select
                id="gender"
                name="gender"
                value={formData.gender || ""}
                onChange={handleChange}
              >
                <option value="">Select gender</option>
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
              </select>
            </div>
          </div>
        </section>

        {/* Contact Information */}
        <section className="bf-form-section">
          <h2>Contact Information</h2>
          <div className="bf-form-grid">
            <div className="bf-form-group">
              <label htmlFor="email">Email</label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder="Enter email address"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="phone">Phone</label>
              <input
                type="tel"
                id="phone"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                placeholder="Enter phone number"
              />
            </div>

            <div className="bf-form-group bf-form-group-full">
              <label htmlFor="address">Address</label>
              <input
                type="text"
                id="address"
                name="address"
                value={formData.address}
                onChange={handleChange}
                placeholder="Enter address"
              />
            </div>
          </div>
        </section>

        {/* Medical Information */}
        <section className="bf-form-section">
          <h2>Medical Information</h2>
          <div className="bf-form-grid">
            <div className="bf-form-group">
              <label htmlFor="diagnosis">Diagnosis</label>
              <input
                type="text"
                id="diagnosis"
                name="diagnosis"
                value={formData.diagnosis}
                onChange={handleChange}
                placeholder="e.g., Idiopathic Scoliosis"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="curveType">Curve Type</label>
              <select
                id="curveType"
                name="curveType"
                value={formData.curveType || ""}
                onChange={handleChange}
              >
                <option value="">Select curve type</option>
                <option value="A1">A1 - 3 curves, main thoracic</option>
                <option value="A2">A2 - 3 curves, thoracolumbar</option>
                <option value="A3">A3 - 3 curves, false double major</option>
                <option value="B1">B1 - 3 curves, combined</option>
                <option value="B2">B2 - 3 curves, double major</option>
                <option value="C1">C1 - 2 curves, main thoracic</option>
                <option value="C2">C2 - 2 curves, main lumbar</option>
                <option value="E1">E1 - Single curve, thoracic</option>
                <option value="E2">E2 - Single curve, thoracolumbar</option>
              </select>
            </div>

            <div className="bf-form-group">
              <label htmlFor="referringPhysician">Referring Physician</label>
              <input
                type="text"
                id="referringPhysician"
                name="referringPhysician"
                value={formData.referringPhysician}
                onChange={handleChange}
                placeholder="Enter physician name"
              />
            </div>

            <div className="bf-form-group">
              <label htmlFor="insuranceInfo">Insurance Information</label>
              <input
                type="text"
                id="insuranceInfo"
                name="insuranceInfo"
                value={formData.insuranceInfo}
                onChange={handleChange}
                placeholder="Enter insurance details"
              />
            </div>

            <div className="bf-form-group bf-form-group-full">
              <label htmlFor="medicalHistory">Medical History</label>
              <textarea
                id="medicalHistory"
                name="medicalHistory"
                value={formData.medicalHistory}
                onChange={handleChange}
                rows={4}
                placeholder="Enter relevant medical history..."
              />
            </div>

            <div className="bf-form-group bf-form-group-full">
              <label htmlFor="notes">Notes</label>
              <textarea
                id="notes"
                name="notes"
                value={formData.notes}
                onChange={handleChange}
                rows={3}
                placeholder="Additional notes..."
              />
            </div>
          </div>
        </section>

        {/* Form Actions */}
        <div className="bf-form-actions">
          <button
            type="button"
            className="bf-btn bf-btn-outline"
            onClick={() => navigate(isEditing ? `/patients/${patientId}` : "/patients")}
          >
            Cancel
          </button>
          <button type="submit" className="bf-btn bf-btn-primary" disabled={saving}>
            {saving ? "Saving..." : isEditing ? "Update Patient" : "Create Patient"}
          </button>
        </div>
      </form>
    </div>
  );
}
