/**
 * GetStartedForm - Main form component for the unified get-started flow
 *
 * Flow: Email -> OTP Verification -> Account Status -> Complete Account -> Dashboard
 */

"use client";

import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useGetStartedMachine } from "../../hooks/useGetStartedMachine";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import { getSafeRedirect } from "@/features/auth/utils/route-protection";
import {
  EmailStep,
  VerificationStep,
  AccountStatusStep,
  CompleteAccountStep,
  MigrateAccountStep,
} from "./steps";

type StepName = string;

const stepTitles: Record<string, { title: string; subtitle: string }> = {
  email: {
    title: "Get Started",
    subtitle: "Enter your email to begin",
  },
  verification: {
    title: "Verify Your Email",
    subtitle: "Enter the code we sent to your email",
  },
  accountStatus: {
    title: "Welcome",
    subtitle: "Let's get you set up",
  },
  loginRedirect: {
    title: "Welcome",
    subtitle: "Let's get you set up",
  },
  completeAccount: {
    title: "Create Your Account",
    subtitle: "Just a few more details",
  },
  migrateAccount: {
    title: "Set Up Your Account",
    subtitle: "Create your portal password",
  },
  success: {
    title: "Account Created!",
    subtitle: "You're all set",
  },
};

function getTopLevelState(stateValue: unknown): string {
  if (typeof stateValue === "string") return stateValue;
  if (typeof stateValue === "object" && stateValue !== null) {
    return Object.keys(stateValue)[0] ?? "idle";
  }
  return "idle";
}

interface GetStartedFormProps {
  /** Callback when step changes (for parent to update title) */
  onStepChange?: (step: StepName, meta: { title: string; subtitle: string }) => void;
}

export function GetStartedForm({ onStepChange }: GetStartedFormProps) {
  const { state, send } = useGetStartedMachine();
  const router = useRouter();
  const redirectInitiated = useRef(false);

  const topState = getTopLevelState(state.value);

  // Reset form on mount to ensure clean state (but not if coming from handoff)
  useEffect(() => {
    const hasHandoffParam = window.location.search.includes("handoff=");
    const hasHandoffToken = sessionStorage.getItem("get-started-handoff-token");
    const hasVerifiedParam = window.location.search.includes("verified=");

    if (!hasHandoffParam && !hasHandoffToken && !hasVerifiedParam) {
      send({ type: "RESET" });
    }
  }, [send]);

  // Notify parent of step changes
  useEffect(() => {
    const meta = stepTitles[topState] ?? stepTitles["email"]!;
    onStepChange?.(topState, meta);
  }, [topState, onStepChange]);

  // Auto-start the machine if it's in idle state
  useEffect(() => {
    if (topState === "idle") {
      send({ type: "START" });
    }
  }, [topState, send]);

  // On success: sync auth store and redirect directly to dashboard
  useEffect(() => {
    if (topState !== "success" || redirectInitiated.current) return;
    redirectInitiated.current = true;

    const { authResponse, redirectTo, serviceContext } = state.context;

    // Sync auth response to global auth store so AppShell recognizes the session
    if (authResponse) {
      useAuthStore.getState().applyAuthResponse(authResponse);
    }

    const destination = getSafeRedirect(redirectTo || serviceContext?.redirectTo, "/account");
    router.push(destination);
  }, [topState, router]); // eslint-disable-line react-hooks/exhaustive-deps -- guarded by redirectInitiated ref; state.context is read but doesn't need to trigger re-runs

  switch (topState) {
    case "email":
      return (
        <div className="w-full">
          <EmailStep />
        </div>
      );
    case "verification":
      return (
        <div className="w-full">
          <VerificationStep />
        </div>
      );
    case "accountStatus":
    case "loginRedirect":
      return (
        <div className="w-full">
          <AccountStatusStep />
        </div>
      );
    case "completeAccount":
      return (
        <div className="w-full">
          <CompleteAccountStep />
        </div>
      );
    case "migrateAccount":
      return (
        <div className="w-full">
          <MigrateAccountStep />
        </div>
      );
    case "success":
      return null;
    default:
      return (
        <div className="w-full">
          <EmailStep />
        </div>
      );
  }
}
