/**
 * AccountStatusStep - Shows account status and routes to appropriate next step
 *
 * Routes based on account status:
 * - portal_exists: Show login form inline (or redirect link in full-page mode)
 * - whmcs_unmapped: Show migrate form inline (or redirect link in full-page mode)
 * - sf_unmapped: Go to complete-account step (pre-filled form)
 * - new_customer: Go to complete-account step (full signup)
 */

"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/atoms";
import {
  CheckCircleIcon,
  UserCircleIcon,
  ArrowRightIcon,
  DocumentCheckIcon,
} from "@heroicons/react/24/outline";
import { CheckCircle2 } from "lucide-react";
import { LoginForm } from "@/features/auth/components/LoginForm/LoginForm";
import { LinkWhmcsForm } from "@/features/auth/components/LinkWhmcsForm/LinkWhmcsForm";
import { useGetStartedStore } from "../../../stores/get-started.store";

export function AccountStatusStep() {
  const router = useRouter();
  const { accountStatus, formData, goToStep, prefill, inline, redirectTo, serviceContext } =
    useGetStartedStore();

  // Compute effective redirect URL from store state
  const effectiveRedirectTo = redirectTo || serviceContext?.redirectTo || "/account/dashboard";

  // Portal exists - show login form inline or redirect to login page
  if (accountStatus === "portal_exists") {
    // 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>

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

  // WHMCS exists but not mapped - show migrate form inline or redirect to migrate page
  if (accountStatus === "whmcs_unmapped") {
    // Inline mode: render migrate 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-primary/10 flex items-center justify-center">
                <UserCircleIcon className="h-8 w-8 text-primary" />
              </div>
            </div>

            <div className="space-y-2 mt-4">
              <h3 className="text-lg font-semibold text-foreground">Existing Account Found</h3>
              <p className="text-sm text-muted-foreground">
                We found an existing billing account with this email. Please verify your password to
                link it to your new portal account.
              </p>
            </div>
          </div>

          <LinkWhmcsForm
            initialEmail={formData.email}
            onTransferred={result => {
              if (result.needsPasswordSet) {
                const params = new URLSearchParams({
                  email: result.user.email,
                  redirect: effectiveRedirectTo,
                });
                router.push(`/auth/set-password?${params.toString()}`);
                return;
              }
              router.push(effectiveRedirectTo);
            }}
          />
        </div>
      );
    }

    // Full-page mode: redirect to migrate page
    const migrateUrl = `/auth/migrate?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-primary/10 flex items-center justify-center">
            <UserCircleIcon className="h-8 w-8 text-primary" />
          </div>
        </div>

        <div className="space-y-2">
          <h3 className="text-lg font-semibold text-foreground">Existing Account Found</h3>
          <p className="text-sm text-muted-foreground">
            We found an existing billing account with this email. Please verify your password to
            link it to your new portal account.
          </p>
        </div>

        <Link href={migrateUrl}>
          <Button className="w-full h-11">
            Link My Account
            <ArrowRightIcon className="h-4 w-4 ml-2" />
          </Button>
        </Link>
      </div>
    );
  }

  // SF exists but not mapped - complete account with pre-filled data
  if (accountStatus === "sf_unmapped") {
    return (
      <div className="space-y-6">
        <div className="text-center">
          <div className="flex justify-center">
            <div className="h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center">
              <DocumentCheckIcon className="h-8 w-8 text-primary" />
            </div>
          </div>

          <div className="space-y-2 mt-4">
            <h3 className="text-lg font-semibold text-foreground">
              {prefill?.firstName ? `Welcome back, ${prefill.firstName}!` : "Welcome Back!"}
            </h3>
            <p className="text-sm text-muted-foreground">
              We found your information from a previous inquiry. Complete a few more details to
              activate your account.
            </p>
          </div>
        </div>

        {/* Show what's pre-filled vs what's needed */}
        <div className="p-4 rounded-xl bg-muted/50 border border-border text-left space-y-3">
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-2">What we have:</p>
            <ul className="space-y-1.5">
              <li className="flex items-center gap-2 text-sm">
                <CheckCircle2 className="h-4 w-4 text-success flex-shrink-0" />
                <span>Name and email verified</span>
              </li>
              {prefill?.address && (
                <li className="flex items-center gap-2 text-sm">
                  <CheckCircle2 className="h-4 w-4 text-success flex-shrink-0" />
                  <span>Address from your inquiry</span>
                </li>
              )}
            </ul>
          </div>

          <div>
            <p className="text-xs font-medium text-muted-foreground mb-2">What you&apos;ll add:</p>
            <ul className="space-y-1 text-sm text-muted-foreground">
              <li className="flex items-center gap-2">
                <span className="w-4 text-center">•</span>
                <span>Phone number</span>
              </li>
              <li className="flex items-center gap-2">
                <span className="w-4 text-center">•</span>
                <span>Date of birth</span>
              </li>
              <li className="flex items-center gap-2">
                <span className="w-4 text-center">•</span>
                <span>Password</span>
              </li>
            </ul>
          </div>
        </div>

        {prefill?.eligibilityStatus && (
          <p className="text-sm font-medium text-success text-center">
            Eligibility Status: {prefill.eligibilityStatus}
          </p>
        )}

        <Button onClick={() => goToStep("complete-account")} className="w-full h-11">
          Continue
          <ArrowRightIcon className="h-4 w-4 ml-2" />
        </Button>
      </div>
    );
  }

  // New customer - proceed to full signup
  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">Email Verified!</h3>
        <p className="text-sm text-muted-foreground">
          Great! Let&apos;s set up your account so you can access all our services.
        </p>
      </div>

      <Button onClick={() => goToStep("complete-account")} className="w-full h-11">
        Continue
        <ArrowRightIcon className="h-4 w-4 ml-2" />
      </Button>
    </div>
  );
}
