"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { easeOutExpo } from "@/lib/motion";
import { BrandLockup } from "@/components/brand/brand-logo";

const STEPS = [
  "Evaluating KPIs...",
  "Analyzing Attendance...",
  "Calculating Logged Hours...",
  "Reviewing Performance Metrics...",
  "Generating Insights...",
] as const;

interface EvaluationLoadingScreenProps {
  userName?: string;
  onComplete: () => void;
  /** Minimum total duration of the sequence (ms) */
  durationMs?: number;
}

export function EvaluationLoadingScreen({
  userName,
  onComplete,
  durationMs = 5000,
}: EvaluationLoadingScreenProps) {
  const reduceMotion = useReducedMotion();
  const [stepIndex, setStepIndex] = useState(0);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    if (reduceMotion) {
      const t = setTimeout(onComplete, 200);
      return () => clearTimeout(t);
    }

    const stepDuration = durationMs / STEPS.length;
    const stepTimer = setInterval(() => {
      setStepIndex((prev) => Math.min(prev + 1, STEPS.length - 1));
    }, stepDuration);

    const start = performance.now();
    let frame = 0;
    const tick = (now: number) => {
      const p = Math.min(1, (now - start) / durationMs);
      setProgress(p);
      if (p < 1) {
        frame = requestAnimationFrame(tick);
      } else {
        onComplete();
      }
    };
    frame = requestAnimationFrame(tick);

    return () => {
      clearInterval(stepTimer);
      cancelAnimationFrame(frame);
    };
  }, [durationMs, onComplete, reduceMotion]);

  return (
    <div
      className="min-h-[70vh] flex items-center justify-center px-6"
      role="status"
      aria-live="polite"
    >
      <div className="w-full max-w-md text-center">
        <div className="relative mx-auto mb-8 flex h-20 w-full items-center justify-center">
          <motion.div
            className="absolute inset-x-8 inset-y-0 rounded-full bg-primary/10"
            animate={
              reduceMotion
                ? undefined
                : { scale: [1, 1.08, 1], opacity: [0.4, 0.15, 0.4] }
            }
            transition={{ duration: 2.2, repeat: Infinity, ease: "easeInOut" }}
          />
          <BrandLockup height={32} className="relative z-10 items-center" />
        </div>

        <motion.h2
          className="text-2xl font-semibold tracking-tight text-foreground mb-1 font-secondary"
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.05, duration: 0.4, ease: easeOutExpo }}
        >
          Evaluating{userName ? ` ${userName.split(" ")[0]}` : ""}...
        </motion.h2>

        <div className="h-7 mb-6 overflow-hidden">
          <AnimatePresence mode="wait">
            <motion.p
              key={STEPS[stepIndex]}
              className="text-sm text-muted-foreground"
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              transition={{ duration: 0.28, ease: easeOutExpo }}
            >
              {STEPS[stepIndex]}
            </motion.p>
          </AnimatePresence>
        </div>

        <div className="mx-auto h-1 w-48 rounded-full bg-muted overflow-hidden">
          <motion.div
            className="h-full rounded-full bg-primary"
            style={{ width: `${Math.round(progress * 100)}%` }}
          />
        </div>

        <div className="mt-5 flex justify-center gap-1.5">
          {STEPS.map((_, i) => (
            <motion.span
              key={i}
              className="h-1.5 w-1.5 rounded-full"
              animate={{
                backgroundColor:
                  i <= stepIndex
                    ? "hsl(var(--primary))"
                    : "hsl(var(--muted-foreground) / 0.35)",
                scale: i === stepIndex ? 1.25 : 1,
              }}
              transition={{ duration: 0.25 }}
            />
          ))}
        </div>
      </div>
    </div>
  );
}
