/**
 * InlineGetStartedSection - Inline email-first registration for service pages
 *
 * Uses the XState get-started machine (email -> OTP -> status -> form) inline on service pages
 * like the SIM configure page. Supports service context to track plan selection through the flow.
 *
 * The email-first approach auto-detects the user's account status after OTP verification:
 * - portal_exists: Shows LoginForm inline
 * - whmcs_unmapped: Shows LinkWhmcsForm inline
 * - sf_unmapped / new_customer: Continues to account completion
 */

"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { getSafeRedirect } from "@/features/auth/utils/route-protection";
import {
  useGetStartedMachineRoot,
  GetStartedMachineProvider,
} from "../../hooks/useGetStartedMachine";
import type { ServiceContext } from "../../machines/get-started.types";
import { EmailStep } from "../GetStartedForm/steps/EmailStep";
import { VerificationStep } from "../GetStartedForm/steps/VerificationStep";
import { AccountStatusStep } from "../GetStartedForm/steps/AccountStatusStep";
import { CompleteAccountStep } from "../GetStartedForm/steps/CompleteAccountStep";
import { MigrateAccountStep } from "../GetStartedForm/steps/MigrateAccountStep";

interface HighlightItem {
  title: string;
  description: string;
}

interface InlineGetStartedSectionProps {
  title: string;
  description?: string;
  serviceContext?: Omit<ServiceContext, "redirectTo">;
  redirectTo?: string;
  highlights?: HighlightItem[];
  className?: string;
}

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";
}

export function InlineGetStartedSection({
  title,
  description,
  serviceContext,
  redirectTo,
  highlights = [],
  className = "",
}: InlineGetStartedSectionProps) {
  const router = useRouter();
  const safeRedirect = getSafeRedirect(redirectTo, "/account");

  const { state, send } = useGetStartedMachineRoot({
    inline: true,
    serviceContext: serviceContext ? { ...serviceContext, redirectTo: safeRedirect } : undefined,
  });

  // Set redirect URL when component mounts
  useEffect(() => {
    send({ type: "SET_REDIRECT", redirectTo: safeRedirect });
  }, [safeRedirect, send]);

  const topState = getTopLevelState(state.value);

  // Redirect on success
  useEffect(() => {
    if (topState === "success") {
      router.push(safeRedirect);
    }
  }, [topState, safeRedirect, router]);

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

  // Render the current step
  const renderStep = () => {
    switch (topState) {
      case "email":
        return <EmailStep />;
      case "verification":
        return <VerificationStep />;
      case "accountStatus":
      case "loginRedirect":
        return <AccountStatusStep />;
      case "completeAccount":
        return <CompleteAccountStep />;
      case "migrateAccount":
        return <MigrateAccountStep />;
      case "success":
        return null;
      default:
        return <EmailStep />;
    }
  };

  return (
    <GetStartedMachineProvider value={{ state, send }}>
      <div className={`bg-muted/50 border border-border rounded-2xl p-6 md:p-8 ${className}`}>
        <div className="text-center mb-6">
          <h3 className="text-lg font-semibold text-foreground mb-2">{title}</h3>
          {description && (
            <p className="text-sm text-muted-foreground max-w-2xl mx-auto">{description}</p>
          )}
        </div>

        <div className="bg-card border border-border rounded-xl p-5 sm:p-6 shadow-[var(--cp-shadow-1)]">
          {renderStep()}
        </div>

        {highlights.length > 0 && (
          <div className="mt-6 pt-6 border-t border-border">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
              {highlights.map(item => (
                <div key={item.title}>
                  <div className="text-sm font-medium text-foreground mb-1">{item.title}</div>
                  <div className="text-xs text-muted-foreground">{item.description}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </GetStartedMachineProvider>
  );
}
