'use client';

import { useEffect, useRef, useState } from 'react';
import { StatsSectionProps } from '@/lib/page-builder/types';
import { Users, Calendar, FileText, TrendingUp, Award, Globe, Clock, Briefcase } from 'lucide-react';

export default function StatsSection({
  title = "Our Impact in Numbers",
  highlightedText = "Impact",  // 👈 New: Jo word gradient mein show ho ga
  description = "Real results that speak for themselves",
  stats = [
    { id: '1', value: 5, suffix: '+', label: 'Years of Experience', icon: 'Calendar' },
    { id: '2', value: 500, suffix: '+', label: 'Happy Clients', icon: 'Users' },
    { id: '3', value: 2500, suffix: '+', label: 'Posts Delivered', icon: 'FileText' },
    { id: '4', value: 98, suffix: '%', label: 'Client Satisfaction', icon: 'TrendingUp' }
  ],
  columns = 4,
  animationDuration = 2000,
  showBorder = true,
  className = "",
  id
}: StatsSectionProps) {
  
  const [counts, setCounts] = useState<Record<string, number>>({});
  const sectionRef = useRef<HTMLElement>(null);
  const [hasAnimated] = useState(false);
  const [isVisible, setIsVisible] = useState(false);

  // Icon mapping
  const getIcon = (iconName: string) => {
    const icons: Record<string, React.ReactNode> = {
      Users: <Users className="w-6 h-6" />,
      Calendar: <Calendar className="w-6 h-6" />,
      FileText: <FileText className="w-6 h-6" />,
      TrendingUp: <TrendingUp className="w-6 h-6" />,
      Award: <Award className="w-6 h-6" />,
      Globe: <Globe className="w-6 h-6" />,
      Clock: <Clock className="w-6 h-6" />,
      Briefcase: <Briefcase className="w-6 h-6" />
    };
    return icons[iconName] || <TrendingUp className="w-6 h-6" />;
  };

  // Function to render title with gradient highlight
  const renderTitle = () => {
    if (!highlightedText || !title.includes(highlightedText)) {
      return <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-[#1A1F36] mb-4">{title}</h2>;
    }

    const parts = title.split(highlightedText);
    return (
      <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-[#1A1F36] mb-4">
        {parts[0]}
        <span className="text-gradient">{highlightedText}</span>
        {parts[1]}
      </h2>
    );
  };

  // Get grid class based on columns
  const getGridClass = () => {
    switch (columns) {
      case 2:
        return "grid sm:grid-cols-2 gap-6 md:gap-8";
      case 3:
        return "grid sm:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8";
      case 4:
        return "grid sm:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-8";
      default:
        return "grid sm:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-8";
    }
  };

  // Counter animation with cleanup
  useEffect(() => {
    if (!isVisible || hasAnimated) return;

    const timers: NodeJS.Timeout[] = [];
    
    stats.forEach((stat) => {
      const targetValue = stat.value;
      const duration = animationDuration;
      const stepTime = 20;
      const steps = duration / stepTime;
      const increment = targetValue / steps;
      let current = 0;
      
      const timer = setInterval(() => {
        current += increment;
        if (current >= targetValue) {
          setCounts(prev => ({ ...prev, [stat.id]: targetValue }));
          clearInterval(timer);
        } else {
          setCounts(prev => ({ ...prev, [stat.id]: Math.floor(current) }));
        }
      }, stepTime);
      
      timers.push(timer);
    });
    
    return () => {
      timers.forEach(timer => clearInterval(timer));
    };
  }, [isVisible, stats, animationDuration, hasAnimated]);

  // Intersection Observer for visibility
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !hasAnimated) {
            setIsVisible(true);
          }
        });
      },
      { threshold: 0.2, rootMargin: "0px 0px -100px 0px" }
    );

    const currentSection = sectionRef.current;
    if (currentSection) {
      observer.observe(currentSection);
    }

    return () => {
      if (currentSection) {
        observer.unobserve(currentSection);
      }
    };
  }, [hasAnimated]);

  return (
    <section 
      id={id || "stats"} 
      ref={sectionRef}
      className={`py-16 md:py-20 px-4 ${className}`}
    >
      <div className="max-w-7xl mx-auto">
        {/* Section Header */}
        <div className="text-center mb-12 md:mb-16">
          <span className="inline-block px-4 py-1.5 bg-linear-to-r from-blue-50 to-orange-50 rounded-full text-sm font-medium text-[#0066FF] mb-4">
            Trusted By Industry Leaders
          </span>
          
          {/* Title with Gradient Support */}
          {renderTitle()}
          
          {description && (
            <p className="text-lg text-[#475569] max-w-2xl mx-auto">
              {description}
            </p>
          )}
        </div>

        {/* Stats Grid */}
        <div className={getGridClass()}>
          {stats.map((stat, index) => (
            <div
              key={stat.id}
              className={`
                text-center p-6 rounded-2xl transition-all duration-300 
                ${showBorder 
                  ? 'bg-white/80 backdrop-blur-sm border border-gray-100 shadow-md hover:shadow-xl' 
                  : 'bg-transparent'
                }
                hover:-translate-y-2
              `}
              style={{
                animation: `fadeInUp 0.5s ease-out ${index * 0.1}s forwards`,
                opacity: 0,
                transform: 'translateY(20px)'
              }}
            >
              {/* Icon */}
              <div className={`
                w-14 h-14 rounded-xl flex items-center justify-center mx-auto mb-4
                bg-linear-to-br from-[#0066FF]/10 to-[#00D4FF]/10
                transition-transform duration-300 group-hover:scale-110
              `}>
                <div className="text-[#0066FF]">
                  {getIcon(stat.icon)}
                </div>
              </div>

              {/* Number */}
              <div className="text-4xl md:text-5xl font-bold text-[#1A1F36] mb-2 font-mono">
                {isVisible ? (
                  (counts[stat.id] !== undefined ? counts[stat.id] : stat.value)
                ) : (
                  0
                )}
                {stat.suffix}
              </div>

              {/* Label */}
              <div className="text-[#475569] font-medium">
                {stat.label}
              </div>

              {/* Optional description */}
              {stat.description && (
                <p className="text-sm text-[#475569] mt-2">
                  {stat.description}
                </p>
              )}
            </div>
          ))}
        </div>

        {/* Trust Badge */}
        <div className="text-center mt-12 pt-8 border-t border-gray-100">
          <div className="inline-flex items-center gap-2 text-sm text-[#475569]">
            <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
            <span>Trusted by 500+ businesses worldwide</span>
          </div>
        </div>
      </div>

      {/* Global styles */}
      <style>
        {`
          @keyframes fadeInUp {
            from {
              opacity: 0;
              transform: translateY(20px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }
          
          .text-gradient {
            background: linear-gradient(135deg, #0066FF 0%, #00D4FF 100%);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: inline-block;
          }
        `}
      </style>
    </section>
  );
}