"use client";

import { useState } from "react";
import { z } from "zod";
import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
import { createPatient, CreatePatientInput } from "@/app/actions/patient";
import StepIndicator from "./StepIndicator";
import Step1Personal from "./Step1Personal";
import Step2Medical from "./Step2Medical";
import Step3Medications, { MedicationItem } from "./Step3Medications";
import Step4Doctor from "./Step4Doctor";
import SuccessView from "./SuccessView";

interface FormData {
  name: string;
  firstName: string;
  phone: string;
  dob: string;
  gender: "MALE" | "FEMALE" | "OTHER";
  alzheimerType: string;
  progress: number;
  allergies: string;
  otherIllnesses: string;
  medications: MedicationItem[];
  wilaya: string;
  doctorId: string;
  skipDoctor: boolean;
}

const step1Schema = z.object({
  name: z.string().min(1, "Name is required"),
  firstName: z.string().min(1, "First name is required"),
  phone: z.string().optional(),
  dob: z.string().min(1, "Date of birth is required"),
  gender: z.enum(["MALE", "FEMALE", "OTHER"], {
    required_error: "Gender is required",
  }),
});

const step2Schema = z.object({
  alzheimerType: z.string().min(1, "Alzheimer type is required"),
  progress: z.number().min(1).max(100),
  allergies: z.string().optional(),
  otherIllnesses: z.string().optional(),
});

const step3Schema = z.object({
  medications: z.array(
    z.object({
      drugName: z.string().min(1, "Drug name is required"),
      dosage: z.string().min(1, "Dosage is required"),
      // Real time in HH:mm format (from input type="time")
      timing: z.string().min(1, "Time of medication is required"),
      notes: z.string().optional(),
    })
  ),
});

const step4Schema = z.object({
  wilaya: z.string().min(1, "Wilaya is required"),
  skipDoctor: z.boolean(),
  doctorId: z.string().optional(),
}).refine((data) => data.skipDoctor || (data.doctorId && data.doctorId.length > 0), {
  message: "Please select a doctor or skip this step",
  path: ["doctorId"],
});

const stepSchemas = [step1Schema, step2Schema, step3Schema, step4Schema];

function getStepErrors(step: number, data: FormData): Record<string, string> {
  const schema = stepSchemas[step - 1];
  const result = schema.safeParse(
    step === 1
      ? { name: data.name, firstName: data.firstName, phone: data.phone, dob: data.dob, gender: data.gender }
      : step === 2
      ? { alzheimerType: data.alzheimerType, progress: data.progress, allergies: data.allergies, otherIllnesses: data.otherIllnesses }
      : step === 3
      ? { medications: data.medications }
      : { wilaya: data.wilaya, doctorId: data.doctorId, skipDoctor: data.skipDoctor }
  );

  if (result.success) return {};

  const errors: Record<string, string> = {};
  const flattened = result.error.flatten().fieldErrors;
  for (const [key, msgs] of Object.entries(flattened)) {
    if (msgs && msgs[0]) errors[key] = msgs[0];
  }
  return errors;
}

export default function MultiStepForm() {
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState<FormData>({
    name: "",
    firstName: "",
    phone: "",
    dob: "",
    gender: "MALE",
    alzheimerType: "",
    progress: 1,
    allergies: "",
    otherIllnesses: "",
    medications: [],
    wilaya: "",
    doctorId: "",
    skipDoctor: false,
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string>("");
  const [patientId, setPatientId] = useState<string | null>(null);

  function updateField(field: string, value: string | number) {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  }

  function handleNext() {
    const stepErrors = getStepErrors(step, formData);
    if (Object.keys(stepErrors).length > 0) {
      setErrors(stepErrors);
      return;
    }
    setErrors({});
    setStep((s) => Math.min(s + 1, 4));
  }

  function handleBack() {
    setErrors({});
    setStep((s) => Math.max(s - 1, 1));
  }

  async function handleSubmit() {
    const stepErrors = getStepErrors(step, formData);
    if (Object.keys(stepErrors).length > 0) {
      setErrors(stepErrors);
      return;
    }

    setIsSubmitting(true);
    setSubmitError("");

    const payload: CreatePatientInput = {
      name: formData.name,
      firstName: formData.firstName,
      phone: formData.phone || undefined,
      dob: new Date(formData.dob),
      gender: formData.gender,
      alzheimerType: formData.alzheimerType,
      progress: formData.progress,
      allergies: formData.allergies || undefined,
      otherIllnesses: formData.otherIllnesses || undefined,
      doctorId: formData.skipDoctor || !formData.doctorId ? undefined : formData.doctorId,
      medications: formData.medications.map((med) => ({
        drugName: med.drugName,
        dosage: med.dosage,
        timing: med.timing,
        notes: med.notes || undefined,
      })),
    };

    try {
      const result = await createPatient(payload);
      if (result.success && result.patientId) {
        setPatientId(result.patientId);
      } else {
        setSubmitError(result.error || "Failed to create patient.");
      }
    } catch (err) {
      setSubmitError(
        err instanceof Error ? err.message : "An unexpected error occurred."
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  if (patientId) {
    return <SuccessView patientId={patientId} />;
  }

  return (
    <div className="rounded-xl border border-zinc-800 bg-zinc-900 p-5 sm:p-8">
      <StepIndicator currentStep={step} />

      <div className="mb-6">
        {step === 1 && (
          <Step1Personal
            data={{
              name: formData.name,
              firstName: formData.firstName,
              phone: formData.phone,
              dob: formData.dob,
              gender: formData.gender,
            }}
            errors={errors}
            onChange={updateField}
          />
        )}
        {step === 2 && (
          <Step2Medical
            data={{
              alzheimerType: formData.alzheimerType,
              progress: formData.progress,
              allergies: formData.allergies,
              otherIllnesses: formData.otherIllnesses,
            }}
            errors={errors}
            onChange={updateField}
          />
        )}
        {step === 3 && (
          <Step3Medications
            medications={formData.medications}
            onChange={(meds) => {
              setFormData((prev) => ({ ...prev, medications: meds }));
              if (errors.medications) {
                setErrors((prev) => {
                  const next = { ...prev };
                  delete next.medications;
                  return next;
                });
              }
            }}
          />
        )}
        {step === 4 && (
          <Step4Doctor
            wilaya={formData.wilaya}
            doctorId={formData.doctorId}
            skipDoctor={formData.skipDoctor}
            errors={errors}
            onChangeWilaya={(w) => updateField("wilaya", w)}
            onSelectDoctor={(id) => updateField("doctorId", id)}
            onToggleSkip={(skip) => {
              setFormData((prev) => ({ ...prev, skipDoctor: skip, doctorId: skip ? "" : prev.doctorId }));
              if (errors.doctorId) {
                setErrors((prev) => {
                  const next = { ...prev };
                  delete next.doctorId;
                  return next;
                });
              }
            }}
          />
        )}
      </div>

      {submitError && (
        <div className="mb-4 rounded-lg border border-red-800 bg-red-900/20 p-3 text-sm text-red-300">
          {submitError}
        </div>
      )}

      <div className="flex items-center justify-between border-t border-zinc-800 pt-5">
        <button
          type="button"
          onClick={handleBack}
          disabled={step === 1 || isSubmitting}
          className="inline-flex items-center gap-1.5 rounded-lg bg-zinc-800 px-4 py-2.5 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700 disabled:opacity-40"
        >
          <ChevronLeft className="h-4 w-4" />
          Back
        </button>

        {step < 4 ? (
          <button
            type="button"
            onClick={handleNext}
            className="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-indigo-500"
          >
            Next
            <ChevronRight className="h-4 w-4" />
          </button>
        ) : (
          <button
            type="button"
            onClick={handleSubmit}
            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" />
                Creating...
              </>
            ) : (
              <>
                Create Patient
                <ChevronRight className="h-4 w-4" />
              </>
            )}
          </button>
        )}
      </div>
    </div>
  );
}
