/**
 * SuccessStep - Display success after eligibility check
 *
 * Shows different messages based on:
 * - hasAccount: User created an account
 * - !hasAccount: User just submitted a request (guest)
 */

"use client";

import { useEffect, useState, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import { ArrowRight, Home } from "lucide-react";
import { Button } from "@/components/atoms";
import { useEligibilityCheckStore } from "../../../stores/eligibility-check.store";

const AUTO_REDIRECT_DELAY = 5; // seconds

const NEXT_STEPS = [
  "We check service availability at your address",
  "You receive an email with available plans and pricing",
];

function NextStepsInfo({ hasAccount }: { hasAccount: boolean }) {
  const step3Text = hasAccount
    ? "Log in to your dashboard to complete your order"
    : "Create an account or reply to the email to proceed";

  return (
    <div className="pt-4 border-t border-border">
      <h3 className="text-sm font-medium text-foreground mb-3">What happens next?</h3>
      <ul className="space-y-2">
        {[...NEXT_STEPS, step3Text].map((text, i) => (
          <li key={i} className="flex items-start gap-2">
            <span className="flex-shrink-0 h-5 w-5 rounded-full bg-primary/10 text-primary text-xs flex items-center justify-center font-medium">
              {i + 1}
            </span>
            <span className="text-sm text-muted-foreground">{text}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

export function SuccessStep() {
  const router = useRouter();
  const { hasAccount, formData, reset } = useEligibilityCheckStore();

  const [countdown, setCountdown] = useState(AUTO_REDIRECT_DELAY);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  // Clear timer helper
  const clearTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  // Auto-redirect to dashboard if user created an account
  useEffect(() => {
    if (!hasAccount) return;

    timerRef.current = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearTimer();
          router.push("/dashboard");
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return clearTimer;
  }, [hasAccount, router, clearTimer]);

  const handleGoToDashboard = useCallback(() => {
    clearTimer(); // Clear timer before navigation
    reset();
    router.push("/dashboard");
  }, [clearTimer, reset, router]);

  const handleBackToPlans = useCallback(() => {
    clearTimer(); // Clear timer before navigation
    reset();
    router.push("/services/internet");
  }, [clearTimer, reset, router]);

  return (
    <div className="space-y-6">
      {/* Email notification */}
      <div className="p-4 rounded-lg bg-primary/5 border border-primary/20">
        <p className="text-sm text-foreground">
          We&apos;ll send the results to <span className="font-medium">{formData.email}</span>
        </p>
        <p className="text-xs text-muted-foreground mt-1">
          You should receive an update within 1-2 business days.
        </p>
      </div>

      {/* Actions */}
      {hasAccount ? (
        <div className="space-y-3">
          <Button
            type="button"
            onClick={handleGoToDashboard}
            rightIcon={<ArrowRight className="h-4 w-4" />}
            className="w-full"
          >
            Go to Dashboard
          </Button>
          <p className="text-xs text-muted-foreground text-center">
            Redirecting in {countdown} second{countdown === 1 ? "" : "s"}...
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          <Button
            type="button"
            onClick={handleBackToPlans}
            leftIcon={<Home className="h-4 w-4" />}
            className="w-full"
          >
            View Internet Plans
          </Button>
        </div>
      )}

      <NextStepsInfo hasAccount={hasAccount} />
    </div>
  );
}
