/**
 * AccountStatusStep - Shows login UI for portal_exists accounts
 *
 * With XState's `always` transitions on accountStatus, only portal_exists
 * reaches this component (via loginRedirect state). Other statuses
 * (whmcs_unmapped, sf_unmapped, new_customer) auto-route to their
 * respective steps (migrateAccount, completeAccount).
 */

"use client";

import { Button } from "@/components/atoms";
import { CheckCircleIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import { LoginForm } from "@/features/auth/components/LoginForm/LoginForm";
import { getSafeRedirect } from "@/features/auth/utils/route-protection";
import { useGetStartedMachine } from "../../../hooks/useGetStartedMachine";

export function AccountStatusStep() {
  const { state } = useGetStartedMachine();
  const { formData, inline, redirectTo, serviceContext } = state.context;

  // Compute effective redirect URL from machine context (with validation)
  const effectiveRedirectTo = getSafeRedirect(redirectTo || serviceContext?.redirectTo, "/account");

  // Inline mode: render login form directly
  if (inline) {
    return (
      <div className="space-y-6">
        <div className="text-center">
          <div className="flex justify-center">
            <div className="h-16 w-16 rounded-full bg-success/10 flex items-center justify-center">
              <CheckCircleIcon className="h-8 w-8 text-success" />
            </div>
          </div>

          <div className="space-y-2 mt-4">
            <h3 className="text-lg font-semibold text-foreground">Account Found</h3>
            <p className="text-sm text-muted-foreground">
              You already have a portal account with this email. Please log in to continue.
            </p>
          </div>
        </div>

        <LoginForm
          initialEmail={formData.email}
          redirectTo={effectiveRedirectTo}
          showSignupLink={false}
          showForgotPasswordLink={true}
        />
      </div>
    );
  }

  // Full-page mode: redirect to login page
  const loginUrl = `/auth/login?email=${encodeURIComponent(formData.email)}&redirect=${encodeURIComponent(effectiveRedirectTo)}`;
  return (
    <div className="space-y-6 text-center">
      <div className="flex justify-center">
        <div className="h-16 w-16 rounded-full bg-success/10 flex items-center justify-center">
          <CheckCircleIcon className="h-8 w-8 text-success" />
        </div>
      </div>

      <div className="space-y-2">
        <h3 className="text-lg font-semibold text-foreground">Account Found</h3>
        <p className="text-sm text-muted-foreground">
          You already have a portal account with this email. Please log in to continue.
        </p>
      </div>

      <Button
        as="a"
        href={loginUrl}
        className="w-full h-11"
        rightIcon={<ArrowRightIcon className="h-4 w-4" />}
      >
        Go to Login
      </Button>
    </div>
  );
}
