"use client";

import { useEffect, useState } from "react";

import { useRouter } from "next/navigation";

import { Activity, Brain, Check, Loader2, TrendingUp } from "lucide-react";

import { useQuizStore } from "@/stores/quiz-store";
import { STORAGE_KEYS } from "@/types/novalife";

const STEPS = [
  { label: "Scoring your responses...", delay: 500 },
  { label: "Identifying your archetype...", delay: 1200 },
  { label: "Calculating metabolic profile...", delay: 2000 },
  { label: "Preparing your insights...", delay: 2500 },
] as const;

const REDIRECT_AFTER_MS = 3200;

export default function QuizCompletePage() {
  const router = useRouter();
  const { archetypeResult } = useQuizStore();
  const [completedSteps, setCompletedSteps] = useState<Set<number>>(new Set());
  const [icons] = useState([Brain, Activity, TrendingUp]);

  // Guard: if no result, go back to quiz
  useEffect(() => {
    if (globalThis.window === undefined) return;
    const stored = localStorage.getItem(STORAGE_KEYS.ARCHETYPE_RESULT);
    if (!stored && !archetypeResult) {
      router.replace("/quiz");
    }
  }, [archetypeResult, router]);

  // Step completion timers
  useEffect(() => {
    function markStep(idx: number) {
      setCompletedSteps((prev) => new Set([...prev, idx]));
    }

    const timers = STEPS.map((step, idx) => setTimeout(() => markStep(idx), step.delay));
    const redirectTimer = setTimeout(() => router.push("/result"), REDIRECT_AFTER_MS);

    return () => {
      timers.forEach(clearTimeout);
      clearTimeout(redirectTimer);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const activeStep = STEPS.findIndex((_, i) => !completedSteps.has(i));

  return (
    <div className="flex-1 flex flex-col items-center justify-center px-6 py-20 min-h-[70vh]">
      {/* Animated icons row */}
      <div className="flex items-center justify-center gap-8 mb-12">
        {icons.map((Icon, i) => (
          <div
            key={Icon.displayName ?? `icon-${i}`}
            className="flex items-center justify-center w-14 h-14 rounded-2xl bg-teal-50"
            style={{
              animation: `pulse 1.8s ease-in-out infinite`,
              animationDelay: `${i * 0.3}s`,
            }}
          >
            <Icon
              className="w-7 h-7 text-teal-700"
              style={{
                animation: `spin 3s linear infinite`,
                animationDelay: `${i * 0.6}s`,
              }}
            />
          </div>
        ))}
      </div>

      {/* Headline */}
      <div className="text-center mb-10 space-y-2">
        <h1 className="text-2xl font-bold text-gray-900">Analysing your responses</h1>
        <p className="text-sm text-gray-500">This takes just a few seconds&hellip;</p>
      </div>

      {/* Steps list */}
      <div className="w-full max-w-sm space-y-3">
        {STEPS.map((step, idx) => {
          const isDone = completedSteps.has(idx);
          const isActive = idx === activeStep;

          let rowBg = "opacity-40";
          if (isDone) rowBg = "bg-teal-50 opacity-100";
          else if (isActive) rowBg = "bg-gray-50 opacity-100";

          let labelColor = "text-gray-400";
          if (isDone) labelColor = "text-teal-700";
          else if (isActive) labelColor = "text-gray-700";

          return (
            <div
              key={step.label}
              className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-300 ${rowBg}`}
            >
              <div className="flex-shrink-0 w-6 h-6 flex items-center justify-center">
                {isDone && (
                  <span className="w-6 h-6 rounded-full bg-teal-600 flex items-center justify-center animate-in zoom-in duration-300">
                    <Check className="w-3.5 h-3.5 text-white" strokeWidth={3} />
                  </span>
                )}
                {!isDone && isActive && <Loader2 className="w-5 h-5 text-teal-600 animate-spin" />}
                {!isDone && !isActive && <span className="w-5 h-5 rounded-full border-2 border-gray-200" />}
              </div>
              <span className={`text-sm font-medium ${labelColor}`}>{step.label}</span>
            </div>
          );
        })}
      </div>

      {/* Subtle branding */}
      <p className="mt-12 text-xs text-gray-300 font-medium tracking-wide uppercase">Novalife Precision Diagnostic</p>

      <style jsx>{`
        @keyframes spin {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
        @keyframes pulse {
          0%, 100% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.05);
            opacity: 0.8;
          }
        }
      `}</style>
    </div>
  );
}
