"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Trash2, Loader2 } from "lucide-react";
import { updatePatient, UpdatePatientInput } from "@/app/actions/family";

interface Medication {
  id?: string;
  drugName: string;
  dosage: string;
  timing: string;
  notes?: string | null;
}

interface PatientData {
  id: string;
  name: string;
  firstName: string;
  phone?: string | null;
  dob: Date;
  gender: "MALE" | "FEMALE" | "OTHER";
  alzheimerType: string;
  progress: number;
  allergies?: string | null;
  otherIllnesses?: string | null;
  doctorId?: string | null;
  medications: Medication[];
}

interface EditPatientFormProps {
  patient: PatientData;
}

const timingOptions = [
  "Morning",
  "Afternoon",
  "Evening",
  "Night",
  "Before Meal",
  "After Meal",
];

const alzheimerTypes = [
  "Early Stage Alzheimer's",
  "Middle Stage Alzheimer's",
  "Late Stage Alzheimer's",
  "Mild Cognitive Impairment",
  "Other Dementia",
];

function formatDateForInput(date: Date): string {
  const d = new Date(date);
  const month = `${d.getMonth() + 1}`.padStart(2, "0");
  const day = `${d.getDate()}`.padStart(2, "0");
  return `${d.getFullYear()}-${month}-${day}`;
}

export default function EditPatientForm({ patient }: EditPatientFormProps) {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const [formData, setFormData] = useState({
    name: patient.name,
    firstName: patient.firstName,
    phone: patient.phone ?? "",
    dob: formatDateForInput(patient.dob),
    gender: patient.gender,
    alzheimerType: patient.alzheimerType,
    progress: patient.progress,
    allergies: patient.allergies ?? "",
    otherIllnesses: patient.otherIllnesses ?? "",
    doctorId: patient.doctorId ?? "",
    medications: patient.medications.map((m) => ({
      id: m.id,
      drugName: m.drugName,
      dosage: m.dosage,
      timing: m.timing,
      notes: m.notes ?? "",
    })),
  });

  function updateField(field: string, value: string | number) {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }

  function addMedication() {
    setFormData((prev) => ({
      ...prev,
      medications: [
        ...prev.medications,
        { id: undefined, drugName: "", dosage: "", timing: "", notes: "" },
      ],
    }));
  }

  function removeMedication(index: number) {
    setFormData((prev) => ({
      ...prev,
      medications: prev.medications.filter((_, i) => i !== index),
    }));
  }

  function updateMedication(
    index: number,
    field: keyof (typeof formData.medications)[0],
    value: string
  ) {
    setFormData((prev) => ({
      ...prev,
      medications: prev.medications.map((med, i) =>
        i === index ? { ...med, [field]: value } : med
      ),
    }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setIsSubmitting(true);
    setError("");

    const payload: UpdatePatientInput = {
      id: patient.id,
      name: formData.name,
      firstName: formData.firstName,
      phone: formData.phone || undefined,
      dob: new Date(formData.dob),
      gender: formData.gender,
      alzheimerType: formData.alzheimerType,
      progress: Number(formData.progress),
      allergies: formData.allergies || undefined,
      otherIllnesses: formData.otherIllnesses || undefined,
      doctorId: formData.doctorId || undefined,
      medications: formData.medications.map((med) => ({
        id: med.id,
        drugName: med.drugName,
        dosage: med.dosage,
        timing: med.timing,
        notes: med.notes || undefined,
      })),
    };

    try {
      const result = await updatePatient(payload);
      if (!result.success) {
        setError(result.error || "Failed to update patient.");
      }
      // On success, the server action redirects
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "An unexpected error occurred."
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-6 rounded-xl border border-white/10 bg-white/5 p-6 shadow-lg backdrop-blur-md sm:p-8"
    >
      {error && (
        <div className="rounded-lg border border-red-800 bg-red-900/20 p-3 text-sm text-red-300">
          {error}
        </div>
      )}

      {/* Personal Details */}
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <div>
          <label className="mb-1.5 block text-sm font-medium text-zinc-300">
            Name <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => updateField("name", e.target.value)}
            required
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
          />
        </div>
        <div>
          <label className="mb-1.5 block text-sm font-medium text-zinc-300">
            First Name <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            value={formData.firstName}
            onChange={(e) => updateField("firstName", e.target.value)}
            required
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <div>
          <label className="mb-1.5 block text-sm font-medium text-zinc-300">
            Date of Birth <span className="text-red-400">*</span>
          </label>
          <input
            type="date"
            value={formData.dob}
            onChange={(e) => updateField("dob", e.target.value)}
            required
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
          />
        </div>
        <div>
          <label className="mb-1.5 block text-sm font-medium text-zinc-300">
            Gender <span className="text-red-400">*</span>
          </label>
          <select
            value={formData.gender}
            onChange={(e) => updateField("gender", e.target.value)}
            required
            className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
          >
            <option value="MALE">Male</option>
            <option value="FEMALE">Female</option>
            <option value="OTHER">Other</option>
          </select>
        </div>
      </div>

      <div>
        <label className="mb-1.5 block text-sm font-medium text-zinc-300">
          Phone Number
        </label>
        <input
          type="tel"
          value={formData.phone}
          onChange={(e) => updateField("phone", e.target.value)}
          className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
        />
      </div>

      {/* Medical Details */}
      <div className="rounded-xl border border-white/10 bg-white/5 p-5 backdrop-blur-sm">
        <h3 className="mb-4 text-base font-semibold text-zinc-100">
          Medical Details
        </h3>
        <div className="space-y-5">
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">
              Alzheimer Type <span className="text-red-400">*</span>
            </label>
            <select
              value={formData.alzheimerType}
              onChange={(e) => updateField("alzheimerType", e.target.value)}
              required
              className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
            >
              <option value="" disabled>
                Select type...
              </option>
              {alzheimerTypes.map((type) => (
                <option key={type} value={type}>
                  {type}
                </option>
              ))}
            </select>
          </div>

          <div>
            <div className="mb-2 flex items-center justify-between">
              <label className="text-sm font-medium text-zinc-300">
                Disease Progression <span className="text-red-400">*</span>
              </label>
              <span className="rounded-md bg-zinc-800 px-2 py-0.5 text-xs font-semibold text-indigo-400">
                {formData.progress}%
              </span>
            </div>
            <input
              type="range"
              min={1}
              max={100}
              value={formData.progress}
              onChange={(e) => updateField("progress", Number(e.target.value))}
              className="h-2 w-full cursor-pointer appearance-none rounded-lg bg-zinc-800 accent-indigo-600"
            />
            <div className="mt-1 flex justify-between text-xs text-zinc-500">
              <span>Early (1%)</span>
              <span>Advanced (100%)</span>
            </div>
          </div>

          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">
              Other Illnesses
            </label>
            <textarea
              value={formData.otherIllnesses}
              onChange={(e) => updateField("otherIllnesses", e.target.value)}
              rows={3}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
            />
          </div>

          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">
              Allergies
            </label>
            <textarea
              value={formData.allergies}
              onChange={(e) => updateField("allergies", e.target.value)}
              rows={3}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
            />
          </div>
        </div>
      </div>

      {/* Medications */}
      <div className="rounded-xl border border-white/10 bg-white/5 p-5 backdrop-blur-sm">
        <h3 className="mb-4 text-base font-semibold text-zinc-100">
          Manage Medications
        </h3>
        <div className="space-y-5">
          {formData.medications.map((med, index) => (
            <div
              key={index}
              className="rounded-xl border border-white/10 bg-white/5 p-4 backdrop-blur-sm sm:p-5"
            >
              <div className="mb-3 flex items-center justify-between">
                <span className="text-xs font-semibold uppercase tracking-wider text-zinc-500">
                  Medication #{index + 1}
                </span>
                <button
                  type="button"
                  onClick={() => removeMedication(index)}
                  className="inline-flex items-center gap-1 rounded-md bg-zinc-800 px-2.5 py-1.5 text-xs font-medium text-red-400 transition-colors hover:bg-red-900/20"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                  Remove
                </button>
              </div>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="mb-1 block text-xs font-medium text-zinc-400">
                    Drug Name <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={med.drugName}
                    onChange={(e) =>
                      updateMedication(index, "drugName", e.target.value)
                    }
                    required
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-xs font-medium text-zinc-400">
                    Dosage <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    value={med.dosage}
                    onChange={(e) =>
                      updateMedication(index, "dosage", e.target.value)
                    }
                    required
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-xs font-medium text-zinc-400">
                    Timing <span className="text-red-400">*</span>
                  </label>
                  <select
                    value={med.timing}
                    onChange={(e) =>
                      updateMedication(index, "timing", e.target.value)
                    }
                    required
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                  >
                    <option value="" disabled>
                      Select timing...
                    </option>
                    {timingOptions.map((t) => (
                      <option key={t} value={t}>
                        {t}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="mb-1 block text-xs font-medium text-zinc-400">
                    Note
                  </label>
                  <input
                    type="text"
                    value={med.notes}
                    onChange={(e) =>
                      updateMedication(index, "notes", e.target.value)
                    }
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors placeholder:text-zinc-600 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                  />
                </div>
              </div>
            </div>
          ))}

          <button
            type="button"
            onClick={addMedication}
            className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-white/20 bg-white/5 py-3 text-sm font-medium text-zinc-300 transition-colors hover:border-indigo-500/60 hover:bg-white/10 hover:text-indigo-300"
          >
            <Plus className="h-4 w-4" />
            Add Medication
          </button>
        </div>
      </div>

      <div className="flex items-center justify-end gap-3 pt-2">
        <button
          type="button"
          onClick={() => router.push("/dashboard")}
          className="rounded-lg bg-zinc-800 px-5 py-2.5 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isSubmitting}
          className="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:opacity-60"
        >
          {isSubmitting ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              Saving...
            </>
          ) : (
            "Save Changes"
          )}
        </button>
      </div>
    </form>
  );
}

