"use client";

import { useEffect, useRef, useState } from "react";
import { motion, useInView } from "framer-motion";

interface StatItem {
  value: number;
  suffix: string;
  label: string;
  icon: string;
  color: string;
  bgGradient: string;
  borderColor: string;
}

function AnimatedCounter({ value, suffix, isVisible }: { value: number; suffix: string; isVisible: boolean }) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (!isVisible) return;

    const duration = 2000;
    const steps = 60;
    const increment = value / steps;
    let current = 0;

    const timer = setInterval(() => {
      current += increment;
      if (current >= value) {
        setCount(value);
        clearInterval(timer);
      } else {
        setCount(Math.floor(current));
      }
    }, duration / steps);

    return () => clearInterval(timer);
  }, [value, isVisible]);

  return (
    <span>
      {count.toLocaleString()}
      {suffix}
    </span>
  );
}

export default function Stats() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  const stats: StatItem[] = [
    {
      value: 15000,
      suffix: "+",
      label: "Active Tenders",
      icon: "📋",
      color: "text-green-600",
      bgGradient: "from-green-50 to-green-100/50",
      borderColor: "border-green-200",
    },
    {
      value: 36,
      suffix: "",
      label: "Districts Covered",
      icon: "📍",
      color: "text-orange-600",
      bgGradient: "from-orange-50 to-orange-100/50",
      borderColor: "border-orange-200",
    },
    {
      value: 50,
      suffix: " Cr+",
      label: "Total Tender Value",
      icon: "💰",
      color: "text-blue-600",
      bgGradient: "from-blue-50 to-blue-100/50",
      borderColor: "border-blue-200",
    },
    {
      value: 500,
      suffix: "+",
      label: "Daily Updates",
      icon: "🔄",
      color: "text-purple-600",
      bgGradient: "from-purple-50 to-purple-100/50",
      borderColor: "border-purple-200",
    },
  ];

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2,
      },
    },
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 50, scale: 0.8 },
    visible: {
      opacity: 1,
      y: 0,
      scale: 1,
      transition: {
        type: "spring",
        stiffness: 100,
        damping: 15,
      },
    },
  };

  return (
    <section ref={ref} className="py-8 sm:py-12 bg-gradient-to-br from-gray-50 via-white to-green-50/30 relative">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="text-center mb-10 sm:mb-12"
        >
          <motion.span
            initial={{ opacity: 0 }}
            animate={isInView ? { opacity: 1 } : {}}
            transition={{ delay: 0.2 }}
            className="inline-block px-4 py-2 bg-green-100 text-green-700 rounded-md text-sm font-semibold mb-4"
          >
            OUR IMPACT
          </motion.span>
          <motion.h3
            initial={{ opacity: 0, y: 10 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ delay: 0.3 }}
            className="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-800 mb-2"
          >
            Powering Maharashtra&apos;s{" "}
            <span className="bg-gradient-to-r from-green-600 via-blue-600 to-orange-600 bg-clip-text text-transparent">
              Solar Revolution
            </span>
          </motion.h3>
          <motion.p
            initial={{ opacity: 0 }}
            animate={isInView ? { opacity: 1 } : {}}
            transition={{ delay: 0.4 }}
            className="text-gray-600 mt-2"
          >
            Real-time statistics from our platform
          </motion.p>
        </motion.div>

        <motion.div
          variants={containerVariants}
          initial="hidden"
          animate={isInView ? "visible" : "hidden"}
          className="grid grid-cols-2 md:grid-cols-4 gap-4 sm:gap-6"
        >
          {stats.map((stat, index) => (
            <motion.div
              key={index}
              variants={itemVariants}
              whileHover={{ y: -5 }}
              className={`relative p-4 rounded-xl border border-gray-100 bg-white shadow-lg hover:shadow-xl transition-all overflow-hidden group flex flex-col items-center text-center`}
            >
              {/* Background Decoration */}
              <div className={`absolute inset-0 bg-gradient-to-br ${stat.bgGradient} opacity-30 group-hover:opacity-50 transition-opacity`} />

              {/* Icon */}
              <motion.div
                initial={{ scale: 0, rotate: -180 }}
                animate={isInView ? { scale: 1, rotate: 0 } : {}}
                transition={{ delay: 0.5 + index * 0.1, type: "spring" }}
                className={`w-12 h-12 rounded-full ${stat.borderColor.replace('border', 'bg').replace('-200', '-100')} flex items-center justify-center text-2xl mb-3 relative z-10`}
              >
                {stat.icon}
              </motion.div>

              {/* Number */}
              <motion.div
                className={`text-2xl sm:text-3xl font-black ${stat.color} mb-1 relative z-10 tracking-tight`}
                initial={{ opacity: 0 }}
                animate={isInView ? { opacity: 1 } : {}}
                transition={{ delay: 0.6 + index * 0.1 }}
              >
                <AnimatedCounter value={stat.value} suffix={stat.suffix} isVisible={isInView} />
              </motion.div>

              {/* Label */}
              <motion.p
                initial={{ opacity: 0 }}
                animate={isInView ? { opacity: 1 } : {}}
                transition={{ delay: 0.7 + index * 0.1 }}
                className="text-gray-600 font-bold text-xs uppercase tracking-wide relative z-10"
              >
                {stat.label}
              </motion.p>
            </motion.div>
          ))}
        </motion.div>

        {/* Additional Info Cards */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ delay: 1 }}
          className="mt-10 grid grid-cols-1 md:grid-cols-3 gap-4"
        >
          {[
            { icon: "⚡", text: "Real-time Updates", color: "text-yellow-600" },
            { icon: "🌐", text: "All Districts", color: "text-blue-600" },
            { icon: "📊", text: "Verified Data", color: "text-green-600" },
          ].map((item, index) => (
            <motion.div
              key={index}
              whileHover={{ y: -1 }}
              className="flex items-center gap-3 p-4 bg-white rounded-md shadow-sm border border-gray-200"
            >
              <span className="text-2xl">{item.icon}</span>
              <span className={`font-semibold ${item.color}`}>{item.text}</span>
            </motion.div>
          ))}
        </motion.div>
      </div>
    </section>
  );
}
