import React, { useEffect, useState, useRef } from 'react';
import { Button } from '../ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';
import { Badge } from '../ui/badge';
import { ImageWithFallback } from '../figma/ImageWithFallback';
import { TestimonialsSection } from '../TestimonialsSection';
import { navigateTo } from '../Router';
import { PrimaryCTAButton } from '../PrimaryCTAButton';
import { 
  TrendingUp, 
  Users, 
  Award, 
  ArrowRight,
  Star,
  Quote,
  Building,
  Target,
  Globe,
  Sparkles,
  CheckCircle,
  BarChart3,
  PieChart,
  Activity
} from 'lucide-react';
// Import the actual logos from Figma assets (same as LogosSection)
import imgImage36 from "figma:asset/6bdf8056f51bbdc6dd9dab9044a6579a254bd02c.png";
import imgImage39 from "figma:asset/037c4659b7b0bf15b1dfdcd4868cb42e8257e838.png";
import imgImage43 from "figma:asset/c57ec1f4466f68e607139a3cd6d52f7e2f372408.png";
import imgImage45 from "figma:asset/4833274f0a593cd31fdefe553b70bb016de281af.png";
import imgImage38 from "figma:asset/d5bab6ea4f3d8cef3b0425c45cfee7faea19fdbc.png";
import imgImage47 from "figma:asset/e8fad960112d5eba554c3969d08891ebe4d4b9c7.png";

const impactStats = [
  {
    number: 26643,
    suffix: "",
    label: "PARTICIPANTS",
    description: "Leaders developed across all programs",
    icon: Users,
    bgColor: "bg-primary/10"
  },
  {
    number: 1220,
    suffix: "",
    label: "PROGRAMS",
    description: "Successfully delivered initiatives",
    icon: Target,
    bgColor: "bg-primary/15"
  },
  {
    number: 152,
    suffix: "",
    label: "CLIENTS",
    description: "Organizations transformed",
    icon: Building,
    bgColor: "bg-primary/20"
  }
];

const clientLogos = [
  {
    name: "CANMOOR",
    logo: imgImage36,
    sector: "Financial Services",
    width: 302,
    height: 54
  },
  {
    name: "BlackRock",
    logo: imgImage45,
    sector: "Investment Management", 
    width: 210,
    height: 54
  },
  {
    name: "Royal London",
    logo: imgImage38,
    sector: "Insurance",
    width: 145,
    height: 54
  },
  {
    name: "Abstract",
    logo: imgImage39,
    sector: "Technology",
    width: 172,
    height: 54
  },
  {
    name: "ARES",
    logo: imgImage47,
    sector: "Asset Management",
    width: 163,
    height: 54
  },
  {
    name: "KADANS",
    logo: imgImage43,
    sector: "Real Estate",
    width: 206,
    height: 54
  },
  // Add repeats for more variety
  {
    name: "CANMOOR",
    logo: imgImage36,
    sector: "Financial Services",
    width: 302,
    height: 54
  },
  {
    name: "BlackRock",
    logo: imgImage45,
    sector: "Investment Management",
    width: 210,
    height: 54
  },
  {
    name: "Royal London",
    logo: imgImage38,
    sector: "Insurance",
    width: 145,
    height: 54
  },
  {
    name: "Abstract",
    logo: imgImage39,
    sector: "Technology",
    width: 172,
    height: 54
  },
  {
    name: "ARES",
    logo: imgImage47,
    sector: "Asset Management",
    width: 163,
    height: 54
  },
  {
    name: "KADANS",
    logo: imgImage43,
    sector: "Real Estate",
    width: 206,
    height: 54
  },
  {
    name: "CANMOOR",
    logo: imgImage36,
    sector: "Financial Services",
    width: 302,
    height: 54
  },
  {
    name: "BlackRock",
    logo: imgImage45,
    sector: "Investment Management",
    width: 210,
    height: 54
  },
  {
    name: "Royal London",
    logo: imgImage38,
    sector: "Insurance",
    width: 145,
    height: 54
  }
];

const testimonialHighlights = [
  {
    quote: "KLC's leadership program transformed our entire management approach. The ROI was evident within 6 months.",
    author: "Rajesh Kumar",
    position: "CEO, TechVision Ltd",
    program: "Executive Leadership Program",
    image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop",
    rating: 5
  },
  {
    quote: "The practical frameworks and peer learning experience exceeded our expectations. Highly recommend KLC.",
    author: "Priya Sharma",
    position: "VP Operations, Global Manufacturing",
    program: "Team Leadership Intensive",
    image: "https://images.unsplash.com/photo-1494790108755-2616b612b47c?w=150&h=150&fit=crop",
    rating: 5
  },
  {
    quote: "KLC's consulting approach helped us navigate complex organizational change with remarkable success.",
    author: "Dr. Amit Patel",
    position: "Director, Healthcare Innovation",
    program: "Organizational Consulting",
    image: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop",
    rating: 5
  }
];

// Animated counter component
function AnimatedCounter({ 
  targetValue, 
  suffix = "", 
  duration = 2000,
  isVisible = false 
}: { 
  targetValue: number; 
  suffix?: string; 
  duration?: number;
  isVisible?: boolean;
}) {
  const [currentValue, setCurrentValue] = useState(0);

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

    const startTime = Date.now();
    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      
      // Easing function for smooth animation
      const easeOutExpo = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress);
      const newValue = Math.floor(targetValue * easeOutExpo);
      
      setCurrentValue(newValue);
      
      if (progress < 1) {
        requestAnimationFrame(animate);
      }
    };
    
    requestAnimationFrame(animate);
  }, [isVisible, targetValue, duration]);

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

// Intersection Observer hook for triggering animations
function useIntersectionObserver(options = {}) {
  const [isVisible, setIsVisible] = useState(false);
  const elementRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
        }
      },
      { threshold: 0.3, ...options }
    );

    if (elementRef.current) {
      observer.observe(elementRef.current);
    }

    return () => observer.disconnect();
  }, []);

  return [elementRef, isVisible] as const;
}

export function OurImpact() {
  const [statsRef, statsVisible] = useIntersectionObserver();

  useEffect(() => {
    document.title = 'Our Impact - About Us | KLC';
    window.scrollTo(0, 0);
  }, []);

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FFFFFF' }}>
      {/* Hero Section - Services Page Style */}
      <section className="relative min-h-[90vh] flex flex-col">
        <div className="absolute inset-0 z-0">
          <ImageWithFallback
            src="https://images.unsplash.com/photo-1460472178825-e5240623afd5?w=1920&h=1080&fit=crop"
            alt="Measuring leadership impact and organizational transformation"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/70 to-black/60"></div>
        </div>

        <div className="relative z-10 flex-1 flex items-center">
          <div className="mx-auto section-margin-x">
            <div className="text-center max-w-5xl mx-auto">
              <div className="branded-tag-system-white mb-8 justify-center">
                <div className="dot"></div>
                <span className="text">Knowledge Leadership Centre</span>
              </div>
              
              <h1 className="text-h1-white mb-6">
                Our Impact
              </h1>
              
              <p className="text-body-lg-white mb-8 max-w-2xl mx-auto">
                Real numbers. Real transformation. Discover the measurable difference we've made 
                across industries and organizations worldwide through our leadership development expertise.
              </p>

              <div className="flex flex-col sm:flex-row gap-4 mb-12 justify-center">
                <PrimaryCTAButton
                  text="View Success Stories"
                  onClick={() => document.getElementById('testimonials')?.scrollIntoView({ behavior: 'smooth' })}
                  className="management-dev-primary-cta"
                />
                
                <Button 
                  onClick={() => navigateTo('/contact')}
                  className="management-dev-glassmorphic-btn text-body px-8 py-4 min-h-[52px] border text-white transition-all duration-300"
                  style={{
                    fontFamily: 'var(--font-family-base)'
                  }}
                >
                  <ArrowRight className="w-5 h-5 mr-2" />
                  Get Started
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* Statistics Section - Embedded in Hero */}
        <div className="relative z-10 border-t border-white/20 backdrop-blur-sm bg-black/20" ref={statsRef}>
          <div className="mx-auto section-margin-x py-12">
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-8 text-center max-w-5xl mx-auto">
              <div>
                <div className="text-h2-white mb-2">
                  <AnimatedCounter 
                    targetValue={26643} 
                    isVisible={statsVisible}
                  />
                </div>
                <div className="text-small-white opacity-90">Participants Developed</div>
              </div>
              <div>
                <div className="text-h2-white mb-2">
                  <AnimatedCounter 
                    targetValue={1220} 
                    isVisible={statsVisible}
                  />
                </div>
                <div className="text-small-white opacity-90">Programs Delivered</div>
              </div>
              <div>
                <div className="text-h2-white mb-2">
                  <AnimatedCounter 
                    targetValue={152} 
                    isVisible={statsVisible}
                  />
                  +
                </div>
                <div className="text-small-white opacity-90">Organizations Transformed</div>
              </div>
              <div>
                <div className="text-h2-white mb-2">96%</div>
                <div className="text-small-white opacity-90">Client Satisfaction</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Partners Section - Redesigned According to JSON Config */}
      <section className="py-20" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="mx-auto section-margin-x">


          {/* Statistics Section - Landing Page Style */}
          <div className="mb-20">
            <div className="grid lg:grid-cols-2 gap-16 items-center max-w-7xl mx-auto">
              
              {/* Left Column - Descriptive Content */}
              <div>
                <h2 className="text-h2 mb-6 text-black">
                  Trusted by Industry Leaders
                </h2>
                

                
                {/* Industries We Serve */}
                <div className="mb-6">
                  <h3 className="text-h3 mb-6">Industries We Serve</h3>
                  <div className="flex flex-wrap gap-4">
                    {[
                      "Financial Services", "Investment Banking", "Asset Management", "Technology",
                      "Healthcare", "Manufacturing", "Real Estate", "Consulting"
                    ].map((sector) => (
                      <span 
                        key={sector}
                        className="px-6 py-3 text-body text-gray-700 border border-primary rounded-full transition-all duration-300 hover:bg-primary hover:text-white hover:shadow-lg hover:scale-105 cursor-default group"
                        style={{
                          backgroundColor: '#FFFFFF',
                          borderColor: 'var(--color-primary)',
                        }}
                      >
                        <span className="group-hover:animate-pulse">{sector}</span>
                      </span>
                    ))}
                  </div>
                </div>
              </div>
              
              {/* Right Column - Statistics with Yellow Bullets */}
              <div className="space-y-8">
                {[
                  { value: "27,000+", label: "Leaders Developed" },
                  { value: "150+", label: "Corporate Clients" },
                  { value: "20+", label: "Countries Served" }
                ].map((stat, i) => (
                  <div 
                    key={stat.label}
                    className={`flex items-center gap-6 ${i < 2 ? 'border-b border-gray-200 pb-8' : ''}`}
                    style={{ animation: `fade-in-up 0.6s ease-out ${i * 0.1}s both` }}
                  >
                    {/* Yellow Bullet Point */}
                    <div 
                      className="w-3 h-3 rounded-full flex-shrink-0"
                      style={{ backgroundColor: 'var(--color-accent)' }}
                    ></div>
                    
                    {/* Stats Content */}
                    <div>
                      <div className="stats-number text-primary mb-1">{stat.value}</div>
                      <p className="text-body font-semibold text-black uppercase tracking-wide">
                        {stat.label}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>



          {/* Client Logos Grid */}
          <div className="mb-20">
            <h3 className="text-h3 text-center mb-12">Our Valued Partners</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-8 max-w-6xl mx-auto">
              {clientLogos.slice(0, 16).map((client, index) => {
                // Calculate appropriate width based on original logo dimensions
                const scaledWidth = client.width > 200 ? Math.round(client.width * 0.7) : client.width * 1.1;
                const displayWidth = Math.max(120, Math.min(scaledWidth, 200));
                
                return (
                  <div 
                    key={`${client.name}-${index}`} 
                    className="group p-6 flex items-center justify-center h-24 transition-all duration-300 cursor-pointer border border-gray-100 rounded-xl hover:border-primary/30 hover:shadow-lg hover:-translate-y-1"
                  >
                    <img
                      src={client.logo}
                      alt={client.name}
                      style={{
                        width: `${displayWidth}px`,
                        height: 'auto',
                        maxHeight: '50px',
                        objectFit: 'contain',
                        filter: 'grayscale(100%) opacity(0.7)',
                        transition: 'all 0.3s ease'
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.filter = 'grayscale(0%) opacity(1)';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.filter = 'grayscale(100%) opacity(0.7)';
                      }}
                    />
                  </div>
                );
              })}
            </div>
          </div>

          {/* Partnership CTA Section - Two Column Layout */}
          <div className="max-w-7xl mx-auto">
            <Card className="border-0 rounded-2xl overflow-hidden card-shadow-dramatic" style={{ backgroundColor: 'rgb(249, 250, 251)' }}>
              <CardContent className="p-0">
                <div className="grid lg:grid-cols-2 gap-0 items-center min-h-[400px]">
                  
                  {/* Left Column - Partnership Graphic */}
                  <div className="relative h-full min-h-[400px] overflow-hidden">
                    <img
                      src="https://images.unsplash.com/photo-1739285452621-59d92842fcc8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxidXNpbmVzcyUyMGhhbmRzaGFrZSUyMHBhcnRuZXJzaGlwJTIwcHJvZmVzc2lvbmFsJTIwbWVldGluZ3xlbnwxfHx8fDE3NTU1OTg0NTV8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
                      alt="Partnership collaboration"
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-gradient-to-r from-primary/80 to-primary/40"></div>
                  </div>
                  
                  {/* Right Column - CTA Content */}
                  <div className="p-12 flex flex-col justify-center bg-gray-50">
                    
                    {/* Branded Tag */}
                    <div className="mb-6">
                      <div className="branded-tag-system">
                        <div className="dot"></div>
                        <span className="text">Partner With Us</span>
                      </div>
                    </div>

                    {/* Heading */}
                    <h3 className="text-h2 mb-6 text-black">
                      Ready to Transform Your Leadership?
                    </h3>
                    
                    {/* Description */}
                    <p className="text-body-lg text-muted mb-8 leading-relaxed">
                      Join our network of successful organizations and unlock your team's full potential. 
                      <span className="text-primary font-semibold"> Get in touch</span> to start your development journey today.
                    </p>
                    
                    {/* Sticky CTA Button */}
                    <div className="sticky top-8">
                      <button
                        onClick={() => navigateTo('/contact')}
                        className="w-full px-8 py-4 rounded-lg font-semibold transition-all duration-300 hover:shadow-xl mb-4 group"
                        style={{
                          backgroundColor: 'var(--color-primary)',
                          color: '#FFFFFF',
                          fontFamily: 'var(--font-family-base)',
                          fontSize: '1.125rem',
                          fontWeight: '600',
                          border: 'none'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = '#030359';
                          e.currentTarget.style.transform = 'translateY(-2px)';
                          e.currentTarget.style.boxShadow = '0 12px 24px rgba(4, 4, 91, 0.3)';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = 'var(--color-primary)';
                          e.currentTarget.style.transform = 'translateY(0)';
                          e.currentTarget.style.boxShadow = 'none';
                        }}
                      >
                        <span className="flex items-center justify-center gap-2">
                          Schedule a Partnership Discussion
                          <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform duration-300" />
                        </span>
                      </button>
                      
                      {/* Supporting Information */}
                      <div className="bg-white/80 backdrop-blur-sm rounded-lg p-4 border border-primary/20">
                        <p className="text-small text-muted text-center leading-relaxed">
                          Connect with our partnership specialists to explore collaboration opportunities 
                          and discuss your organization's specific leadership development needs.
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      {/* Success Stories Section - Branded Testimonials */}
      <div id="testimonials">
        <TestimonialsSection 
          customTestimonials={testimonialHighlights.map(testimonial => ({
            name: testimonial.author,
            role: testimonial.position,
            company: testimonial.program,
            avatar: testimonial.image,
            quote: testimonial.quote,
            rating: testimonial.rating,
            isVideo: false
          }))}
          title="What Our Clients Say"
          subtitle="Don't just take our word for it. Here's what leaders from our partner organizations have to say about their transformational experiences with KLC."
          tagText="Client Success"
        />
      </div>

      {/* Additional Metrics Section - Redesigned */}
      <section className="py-20" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="mx-auto section-margin-x">
          <div className="text-center mb-16">
            <Badge 
              className="mb-6 text-body px-4 py-2"
              style={{
                backgroundColor: 'rgba(4, 4, 91, 0.1)',
                color: 'var(--color-primary)',
                border: 'none'
              }}
            >
              Transformation Metrics
            </Badge>
            <h2 className="text-h2 mb-6">
              Measuring Real Transformation
            </h2>
            <p className="text-body-lg text-muted max-w-3xl mx-auto leading-relaxed">
              Our impact extends far beyond statistics. We measure success through the 
              lasting transformation we create in leadership capabilities, organizational 
              culture, and sustainable business outcomes.
            </p>
          </div>

          <div className="grid lg:grid-cols-3 gap-8 max-w-6xl mx-auto">
            {[
              { 
                icon: TrendingUp, 
                metric: "85%", 
                label: "Leadership Effectiveness", 
                description: "Average improvement in leadership effectiveness scores within 6 months",
                details: ["Decision-making quality", "Team engagement", "Strategic thinking", "Change management"]
              },
              { 
                icon: Award, 
                metric: "92%", 
                label: "Client Satisfaction", 
                description: "Client satisfaction and program completion rate across all services",
                details: ["Program quality", "Facilitator expertise", "Content relevance", "Measurable outcomes"]
              },
              { 
                icon: Globe, 
                metric: "15+", 
                label: "Global Reach", 
                description: "Countries where our alumni now lead organizations and drive change",
                details: ["Global network", "Cultural diversity", "Best practices", "Knowledge transfer"]
              }
            ].map((stat, index) => {
              const Icon = stat.icon;
              return (
                <Card 
                  key={index} 
                  className="border-0 shadow-sm hover:shadow-lg transition-all duration-300 group h-full"
                  style={{ backgroundColor: '#FFFFFF' }}
                >
                  <CardContent className="p-8">
                    {/* Icon and Metric */}
                    <div className="text-center mb-6">
                      <div 
                        className="w-20 h-20 rounded-2xl flex items-center justify-center mx-auto mb-4 group-hover:scale-110 transition-transform duration-300"
                        style={{ backgroundColor: 'rgba(4, 4, 91, 0.1)' }}
                      >
                        <Icon className="w-10 h-10 text-primary" />
                      </div>
                      <div className="text-4xl font-bold text-primary mb-2">
                        {stat.metric}
                      </div>
                      <h3 className="text-h4 text-black font-semibold">
                        {stat.label}
                      </h3>
                    </div>

                    {/* Description */}
                    <p className="text-body text-muted leading-relaxed mb-6 text-center">
                      {stat.description}
                    </p>

                    {/* Details */}
                    <div className="space-y-3">
                      <h4 className="text-subhead text-black font-medium">Key Areas:</h4>
                      {stat.details.map((detail, detailIndex) => (
                        <div key={detailIndex} className="flex items-center gap-3">
                          <CheckCircle className="w-4 h-4 text-primary flex-shrink-0" />
                          <span className="text-small text-muted">{detail}</span>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA Section - Branded Banner Style */}
      <section className="relative h-[700px] overflow-hidden">
        {/* Background Image */}
        <div className="absolute inset-0">
          <ImageWithFallback
            src="https://images.unsplash.com/photo-1552664730-d307ca884978?w=2940&h=1200&fit=crop"
            alt="Professional team collaborating in modern office"
            className="w-full h-full object-cover"
          />
          
          {/* Subtle dark overlay for overall image */}
          <div className="absolute inset-0 bg-black/30" />
          
          {/* Gradient overlay for better text readability */}
          <div className="absolute inset-0 bg-gradient-to-r from-black/20 via-transparent to-black/60" />
        </div>

        {/* Content Container */}
        <div className="relative h-full flex items-center justify-end section-margin-x">
          {/* CTA Content Block */}
          <div 
            className="bg-opacity-95 backdrop-blur-sm rounded-lg p-16 max-w-2xl"
            style={{ 
              backgroundColor: 'var(--color-primary)'
            }}
          >
            {/* Branded Tag */}
            <div className="mb-6">
              <div className="branded-tag-system-white">
                <div className="dot"></div>
                <span className="text">
                  Next Steps
                </span>
              </div>
            </div>

            {/* Main Headline */}
            <h2 className="text-h2-white leading-tight mb-8">
              Ready to Create Your Own Success Story?
              <span 
                className="italic"
                style={{ color: 'var(--color-accent)' }}
              >
                {" "}Join the leaders{" "}
              </span>
              transforming their organizations.
            </h2>

            {/* CTA Button */}
            <PrimaryCTAButton 
              text="Explore Our Services"
              onClick={() => navigateTo('/services/leadership-development')}
              ariaLabel="Explore our leadership development services"
              className="cta-banner-yellow"
            />

            {/* Supporting Text */}
            <p className="text-body-white mt-6 opacity-90">
              Connect with our leadership experts to discover how KLC's proven methodologies 
              can transform your organization's performance and culture.
            </p>
          </div>
        </div>
      </section>
    </div>
  );
}