"use client";

import { useCallback, useEffect, useState } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useTranslation } from "@turbostarter/i18n";

import { Section } from "~/modules/marketing/layout/section";
import { StepIndicator } from "./step-indicator";
import { StepFindBusiness } from "./step-find-business";
import { StepConfirm } from "./step-confirm";
import { StepEmail } from "./step-email";
import { StepPayment } from "./step-payment";
import { StepSuccess } from "./step-success";

export interface BusinessData {
  place_id: string;
  name: string;
  address: string;
  rating: number;
  review_count: number;
  category: string;
  maps_url: string;
}

interface WizardState {
  business: BusinessData | null;
  email: string;
  name: string;
}

const TOTAL_STEPS = 5;

export const Wizard = () => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();

  const stepParam = searchParams.get("step");
  const sessionId = searchParams.get("session_id");

  const getInitialStep = (): number => {
    if (stepParam === "success" && sessionId) return 5;
    if (stepParam === "payment") return 4;
    const n = Number(stepParam);
    if (n >= 1 && n <= 5) return n;
    return 1;
  };

  const [step, setStep] = useState(getInitialStep);
  const [wizardState, setWizardState] = useState<WizardState>({
    business: null,
    email: "",
    name: "",
  });

  const updateStep = useCallback(
    (newStep: number) => {
      setStep(newStep);
      const params = new URLSearchParams(searchParams.toString());
      params.set("step", String(newStep));
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    },
    [searchParams, router, pathname],
  );

  const handleBusinessSelect = (business: BusinessData) => {
    setWizardState((prev) => ({ ...prev, business }));
    updateStep(2);
  };

  const handleConfirm = () => {
    updateStep(3);
  };

  const handleEmail = (email: string, name: string) => {
    setWizardState((prev) => ({ ...prev, email, name }));
    updateStep(4);
  };

  const handleBack = (toStep: number) => {
    updateStep(toStep);
  };

  return (
    <Section className="min-h-[60vh]">
      {step < 5 && (
        <StepIndicator currentStep={step} totalSteps={TOTAL_STEPS - 1} />
      )}

      {step === 1 && <StepFindBusiness onSelect={handleBusinessSelect} />}

      {step === 2 && wizardState.business && (
        <StepConfirm
          business={wizardState.business}
          onConfirm={handleConfirm}
          onBack={() => handleBack(1)}
        />
      )}

      {step === 3 && (
        <StepEmail
          initialEmail={wizardState.email}
          initialName={wizardState.name}
          onSubmit={handleEmail}
          onBack={() => handleBack(2)}
        />
      )}

      {step === 4 && wizardState.business && (
        <StepPayment
          business={wizardState.business}
          email={wizardState.email}
          onBack={() => handleBack(3)}
        />
      )}

      {step === 5 && <StepSuccess email={wizardState.email} />}
    </Section>
  );
};
