"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import Step1 from "./Step1";
import { useProjectForm } from "@/contexts/ProjectFormContext";
import { getProjectDraft, saveProjectDraft } from "@/lib/projectDrafts";

const Step2 = dynamic(() => import("./Step2"), { ssr: false });
const Step3 = dynamic(() => import("./Step3"), { ssr: false });
const Step4 = dynamic(() => import("./Step4"), { ssr: false });

const MultiStepForm = () => {
  const searchParams = useSearchParams();
  const { formData, updateForm, draftId, setDraftId, isEditing } =
    useProjectForm();
  const [step, setStep] = useState(1);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const draftParam = searchParams.get("draft");
    if (draftParam) {
      const draft = getProjectDraft(draftParam);
      if (draft) {
        updateForm(draft.formData);
        setDraftId(draft.id);
        setStep(Math.min(Math.max(draft.step, 1), 4));
      }
    }
    setReady(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  const persistDraft = (nextStep: number, patch?: Partial<typeof formData>) => {
    if (isEditing) return;
    const merged = { ...formData, ...patch };
    const saved = saveProjectDraft({
      id: draftId,
      step: nextStep,
      formData: merged,
    });
    setDraftId(saved.id);
  };

  const goNext = (fromStep: number, patch?: Partial<typeof formData>) => {
    if (patch) updateForm(patch);
    const next = fromStep + 1;
    persistDraft(next, patch);
    setStep(next);
  };

  if (!ready) return null;

  return (
    <div className="flex w-full flex-col items-center p-4">
      {step === 1 && (
        <Step1
          nextStep={(values) => goNext(1, values)}
        />
      )}
      {step === 2 && (
        <Step2 nextStep={(values) => goNext(2, values)} />
      )}
      {step === 3 && (
        <Step3 nextStep={(values) => goNext(3, values)} />
      )}
      {step === 4 && <Step4 />}
    </div>
  );
};

export default MultiStepForm;
