"use client";
import { useEffect, useState, useRef, useCallback, useMemo } from "react";
import { motion, useInView, useReducedMotion } from "framer-motion";
import { type Lang } from "@/lib/config";

const containerVariants = {
  hidden: {},
  visible: {
    transition: { staggerChildren: 0.1 },
  },
};

const cardVariants = {
  hidden: { opacity: 0, y: 40, scale: 0.95 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { type: "spring" as const, stiffness: 100, damping: 20 },
  },
};

function easeOutQuart(t: number): number {
  return 1 - Math.pow(1 - t, 4);
}

export default function AnimatedStats({ lang }: { lang: Lang }) {
  const stats = useMemo(
    () => [
      {
        icon: "\u{1F3E5}",
        value: 500,
        suffix: "+",
        labelEn: "Active Clinics",
        labelAr: "\u0639\u064A\u0627\u062F\u0629 \u0646\u0634\u0637\u0629",
        color: "from-blue-500 to-cyan-500",
      },
      {
        icon: "\u{1F4C5}",
        value: 2000000,
        suffix: "+",
        labelEn: "Bookings Processed",
        labelAr: "\u062D\u062C\u0632 \u0645\u0639\u0627\u0644\u062C",
        color: "from-green-500 to-emerald-500",
      },
      {
        icon: "\u26A1",
        value: 10,
        prefix: "<",
        suffix: "s",
        labelEn: "Response Time",
        labelAr: "\u0648\u0642\u062A \u0627\u0644\u0631\u062F",
        color: "from-purple-500 to-pink-500",
      },
      {
        icon: "\u{1F4B3}",
        value: 40,
        suffix: "%",
        labelEn: "Fewer No-Shows",
        labelAr:
          "\u0623\u0642\u0644 \u0639\u062F\u0645 \u062D\u0636\u0648\u0631",
        color: "from-orange-500 to-red-500",
      },
      {
        icon: "\u2B50",
        value: 98,
        suffix: "%",
        labelEn: "Satisfaction Rate",
        labelAr: "\u0645\u0639\u062F\u0644 \u0627\u0644\u0631\u0636\u0627",
        color: "from-yellow-500 to-amber-500",
      },
      {
        icon: "\u{1F30D}",
        value: 6,
        labelEn: "GCC Countries",
        labelAr: "\u062F\u0648\u0644 \u062E\u0644\u064A\u062C\u064A\u0629",
        color: "from-indigo-500 to-purple-500",
      },
    ],
    [],
  );

  const isAr = lang === "ar";
  const sectionRef = useRef<HTMLDivElement>(null);
  const isInView = useInView(sectionRef, { once: true, amount: 0.3 });
  const prefersReducedMotion = useReducedMotion();
  const [counters, setCounters] = useState<number[]>(() => stats.map(() => 0));
  const [animationDone, setAnimationDone] = useState(false);
  const hasAnimated = useRef(false);

  const animateCounters = useCallback(() => {
    if (hasAnimated.current) return;
    hasAnimated.current = true;

    const duration = 2000;
    let start: number | null = null;

    function step(timestamp: number) {
      if (start === null) start = timestamp;
      const elapsed = timestamp - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = easeOutQuart(progress);

      setCounters(stats.map((stat) => Math.floor(stat.value * eased)));

      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        setCounters(stats.map((stat) => stat.value));
        setAnimationDone(true);
      }
    }

    requestAnimationFrame(step);
  }, [stats]);

  useEffect(() => {
    if (isInView && !hasAnimated.current) {
      if (prefersReducedMotion) {
        setCounters(stats.map((stat) => stat.value));
        setAnimationDone(true);
        hasAnimated.current = true;
      } else {
        animateCounters();
      }
    }
  }, [isInView, prefersReducedMotion, animateCounters, stats]);

  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(0) + "M";
    } else if (num >= 1000) {
      return (num / 1000).toFixed(0) + "K";
    }
    return num.toString();
  };

  return (
    <section
      ref={sectionRef}
      className="py-20 px-4 bg-gradient-to-b from-white to-slate-50 dark:from-slate-900 dark:to-slate-800"
    >
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <motion.div
          className="text-center mb-12"
          initial={
            prefersReducedMotion
              ? undefined
              : { opacity: 0, y: 30, filter: "blur(8px)" }
          }
          whileInView={{ opacity: 1, y: 0, filter: "blur(0px)" }}
          viewport={{ once: true, margin: "-60px" }}
          transition={{ duration: 0.6, ease: "easeOut" }}
        >
          <h2 className="text-4xl md:text-5xl font-bold text-brand-ink dark:text-white mb-4">
            {isAr ? (
              <>
                <span className="block">
                  {
                    "\u0627\u0644\u0623\u0631\u0642\u0627\u0645 \u062A\u062A\u062D\u062F\u062B"
                  }
                </span>
                <span className="block text-brand-green">
                  {"\u0639\u0646 \u0646\u0641\u0633\u0647\u0627"}
                </span>
              </>
            ) : (
              <>
                <span className="block">The Numbers Speak</span>
                <span className="block text-brand-green">For Themselves</span>
              </>
            )}
          </h2>
          <p className="text-xl text-slate-600 dark:text-slate-300 max-w-3xl mx-auto">
            {isAr
              ? "\u0646\u062A\u0627\u0626\u062C \u062D\u0642\u064A\u0642\u064A\u0629 \u0645\u0646 \u0639\u064A\u0627\u062F\u0627\u062A \u062D\u0642\u064A\u0642\u064A\u0629 \u0641\u064A \u062C\u0645\u064A\u0639 \u0623\u0646\u062D\u0627\u0621 \u062F\u0648\u0644 \u0645\u062C\u0644\u0633 \u0627\u0644\u062A\u0639\u0627\u0648\u0646 \u0627\u0644\u062E\u0644\u064A\u062C\u064A"
              : "Real results from real clinics across the GCC"}
          </p>
        </motion.div>

        {/* Stats Grid */}
        <motion.div
          className="grid md:grid-cols-2 lg:grid-cols-3 gap-8"
          variants={containerVariants}
          initial="hidden"
          animate={isInView ? "visible" : "hidden"}
        >
          {stats.map((stat, index) => (
            <motion.div
              key={index}
              className="relative group"
              variants={cardVariants}
            >
              <div className="relative bg-white dark:bg-slate-800 rounded-2xl p-8 shadow-lg hover:shadow-2xl transition-[box-shadow,transform] duration-500 transform hover:scale-105 overflow-hidden">
                {/* Background Gradient */}
                <div
                  className={`absolute inset-0 bg-gradient-to-br ${stat.color} opacity-5 group-hover:opacity-10 transition-opacity duration-500`}
                />

                {/* Glow pulse when counter finishes */}
                {animationDone && (
                  <motion.div
                    className={`absolute inset-0 rounded-2xl bg-gradient-to-br ${stat.color}`}
                    initial={{ opacity: 0 }}
                    animate={{
                      opacity: [0, 0.15, 0],
                    }}
                    transition={{
                      duration: 1.2,
                      ease: "easeInOut",
                      delay: index * 0.08,
                    }}
                    style={{ pointerEvents: "none" }}
                  />
                )}

                {/* Icon */}
                <div
                  className={`inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br ${stat.color} mb-4 transform transition-transform duration-500 group-hover:scale-110 group-hover:rotate-3`}
                >
                  <span className="text-3xl text-white">{stat.icon}</span>
                </div>

                {/* Counter */}
                <div className="mb-2">
                  <span
                    className={`text-4xl font-bold bg-gradient-to-r ${stat.color} bg-clip-text text-transparent`}
                  >
                    {stat.prefix}
                    {formatNumber(
                      counters[index] !== undefined ? counters[index] : 0,
                    )}
                    {stat.suffix}
                  </span>
                </div>

                {/* Label */}
                <p className="text-slate-600 dark:text-slate-300 font-medium">
                  {isAr ? stat.labelAr : stat.labelEn}
                </p>

                {/* Animated Dot */}
                <div
                  className={`absolute top-4 right-4 w-2 h-2 rounded-full bg-gradient-to-r ${stat.color} animate-pulse`}
                />

                {/* Hover Effect */}
                <div
                  className={`absolute -bottom-20 -right-20 w-40 h-40 bg-gradient-to-br ${stat.color} rounded-full opacity-10 blur-3xl transition-[transform,bottom,right] duration-500 group-hover:scale-150 group-hover:-bottom-10 group-hover:-right-10`}
                />
              </div>
            </motion.div>
          ))}
        </motion.div>

        {/* Bottom CTA */}
        <div className="mt-16 text-center">
          <div className="inline-flex items-center gap-3 bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 px-6 py-3 rounded-full">
            <svg
              className="w-5 h-5 animate-pulse"
              fill="currentColor"
              viewBox="0 0 20 20"
            >
              <path
                fillRule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                clipRule="evenodd"
              />
            </svg>
            <span className="font-semibold">
              {isAr
                ? "\u0627\u0646\u0636\u0645 \u0625\u0644\u0649 \u0642\u0635\u0635 \u0627\u0644\u0646\u062C\u0627\u062D"
                : "Join the Success Stories"}
            </span>
          </div>
        </div>
      </div>
    </section>
  );
}
