import { useState, useEffect, useRef } from 'react';
import { motion } from 'motion/react';
import { Check, ChevronRight, MapPin, Calendar, Smartphone, CreditCard } from 'lucide-react';
import { Button } from './ui/button';
import { Card, CardContent } from './ui/card';
import { Badge } from './ui/badge';
import Navbar from './Navbar';
import { CitySubmenu } from './CitySubmenu';
import { AttractionHassleFreeSection } from './AttractionHassleFreeSection';
import { MobileAppSection } from './MobileAppSection';
import { WhyChooseCityCards } from './WhyChooseCityCards';
import { EnhancedTestimonials } from './EnhancedTestimonials';
import { ReviewsSection } from './ReviewsSection';
import { Footer } from './Footer';

interface User {
  email: string;
  name: string;
}

interface HowItWorksPageProps {
  onBackClick: () => void;
  onHomeClick: () => void;
  onMelbourneClick: () => void;
  onPassesClick: () => void;
  onCheckoutClick: () => void;
  onSignInClick: () => void;
  onSignOutClick: () => void;
  onAttractionsClick: () => void;
  onBlogsClick: () => void;
  onHowItWorksClick: () => void;
  onFAQClick: () => void;
  onPrivacyPolicyClick: () => void;
  onAboutUsClick: () => void;
  onProfileClick: () => void;
  onCityCardsClick: () => void;
  onMagicItineraryClick: () => void;
  onPostCardsClick: () => void;
  onOffersClick: () => void;
  onContactUsClick?: () => void;
  onEsimsClick?: () => void;
  onHotelDiscountsClick?: () => void;
  currentPage: string;
  user: User | null;
}

interface StepItem {
  id: string;
  title: string;
  description: string;
  icon: React.ReactNode;
  isMainStep: boolean;
  parentStep?: string;
  image?: string;
  features?: string[];
}

const steps: StepItem[] = [
  {
    id: 'pick-pass',
    title: 'Pick Your Pass',
    description: 'Choose between our Selective or Unlimited pass options. Each designed to match your travel style and give you the freedom to explore Melbourne your way.',
    icon: <CreditCard className="w-6 h-6" />,
    isMainStep: true,
    features: ['Selective or Unlimited options', 'Instant digital delivery', 'Skip-the-line access', 'Mobile-friendly tickets']
  },
  {
    id: 'plan-itinerary',
    title: 'Plan Your Journey',
    description: 'Use our smart planning tools to create your perfect Melbourne itinerary. Get personalized recommendations based on your interests and available time.',
    icon: <Calendar className="w-6 h-6" />,
    isMainStep: true,
    features: ['AI-powered suggestions', 'Real-time crowd updates', 'Weather-based planning', 'Flexible scheduling']
  },
  {
    id: 'explore-enjoy',
    title: 'Explore & Enjoy',
    description: 'Experience Melbourne like never before with our mobile app, offline maps, and 24/7 support. Every moment is designed to be effortless and memorable.',
    icon: <MapPin className="w-6 h-6" />,
    isMainStep: true,
    features: ['Mobile app included', 'Offline map access', '24/7 customer support', 'Audio guide content']
  }
];

export function HowItWorksPage({ 
  onHomeClick, 
  onMelbourneClick, 
  onPassesClick,
  onCheckoutClick, 
  onSignInClick,
  onSignOutClick,
  onAttractionsClick,
  onBlogsClick,
  onHowItWorksClick,
  onFAQClick,
  onPrivacyPolicyClick,
  onAboutUsClick,
  onProfileClick,
  onCityCardsClick,
  onMagicItineraryClick,
  onPostCardsClick,
  onOffersClick,
  onContactUsClick,
  onEsimsClick,
  onHotelDiscountsClick,
  currentPage,
  user
}: HowItWorksPageProps) {
  const [activeStep, setActiveStep] = useState<string>('pick-pass');
  const [scrollProgress, setScrollProgress] = useState(0);
  const mainSteps = steps; // All steps are now main steps
  const stepRefs = useRef<(HTMLDivElement | null)[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);

  // Scroll-based step activation
  useEffect(() => {
    const handleScroll = () => {
      if (!containerRef.current) return;

      const scrollY = window.scrollY;
      const windowHeight = window.innerHeight;
      const containerTop = containerRef.current.offsetTop;
      const containerHeight = containerRef.current.offsetHeight;

      // Calculate trigger points for each step (when step indicator is in center of viewport)
      const stepElements = stepRefs.current.filter(Boolean);
      let currentStepIndex = 0;
      let minDistance = Infinity;

      stepElements.forEach((stepEl, index) => {
        if (stepEl) {
          const stepTop = stepEl.offsetTop + containerTop;
          const stepCenter = stepTop + stepEl.offsetHeight / 2;
          const viewportCenter = scrollY + windowHeight / 2;
          const distance = Math.abs(stepCenter - viewportCenter);

          if (distance < minDistance) {
            minDistance = distance;
            currentStepIndex = index;
          }
        }
      });

      // Update active step
      const newActiveStep = mainSteps[currentStepIndex]?.id || 'pick-pass';
      if (newActiveStep !== activeStep) {
        setActiveStep(newActiveStep);
      }

      // Calculate smooth progress through entire stepper
      const sectionStart = containerTop - windowHeight / 2;
      const sectionEnd = containerTop + containerHeight - windowHeight / 2;
      const rawProgress = (scrollY - sectionStart) / (sectionEnd - sectionStart);
      const progress = Math.max(0, Math.min(1, rawProgress));
      
      setScrollProgress(progress);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll(); // Initial call

    return () => window.removeEventListener('scroll', handleScroll);
  }, [activeStep, mainSteps]);

  return (
    <div className="min-h-screen bg-background">
      {/* Navigation */}
      <Navbar 
        activeCity="Melbourne"
        onCityChange={() => {}}
        onHomeClick={onHomeClick}
        onSignInClick={onSignInClick}
        onSignOutClick={onSignOutClick}
        onPassesClick={onPassesClick}
        onCheckoutClick={onCheckoutClick}
        onAttractionsClick={onAttractionsClick}
        onBlogsClick={onBlogsClick}
        onHowItWorksClick={onHowItWorksClick}
        onFAQClick={onFAQClick}
        onPrivacyPolicyClick={onPrivacyPolicyClick}
        onAboutUsClick={onAboutUsClick}
        onProfileClick={onProfileClick}
        onCityCardsClick={onCityCardsClick}
        onMagicItineraryClick={onMagicItineraryClick}
        onPostCardsClick={onPostCardsClick}
        onOffersClick={onOffersClick}
        currentPage={currentPage}
        isUserSignedIn={!!user}
        user={user}
      />
      
      <CitySubmenu 
        currentPage={currentPage}
        onClose={() => {}}
        onHomeClick={onHomeClick}
        onMelbourneClick={onMelbourneClick}
        onAttractionsClick={onAttractionsClick}
        onPassesClick={onPassesClick}
        onBlogsClick={onBlogsClick}
        onHowItWorksClick={onHowItWorksClick}
      />

      <div className="container mx-auto px-4 pt-52 pb-12 relative z-10">
        {/* Page Header */}
        <motion.div 
          className="text-center mb-16"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <h1 className="font-poppins font-light text-4xl md:text-5xl lg:text-6xl mb-4">
            How{' '}
            <span className="font-bold italic bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
              It Works
            </span>
          </h1>
          <p className="font-poppins text-xl leading-relaxed font-normal text-gray-600 max-w-3xl mx-auto">
            Discover the simple process that transforms your city exploration from ordinary to extraordinary
          </p>
        </motion.div>

        {/* Vertical Stepper with Alternating Layout */}
        <div ref={containerRef} className="relative max-w-6xl mx-auto mb-20">
          {/* Central Progress Line */}
          <div className="absolute left-1/2 transform -translate-x-0.5 top-0 bottom-0 w-1 bg-gray-200 rounded-full">
            {/* Progress Fill */}
            <motion.div
              className="w-full bg-gradient-to-b from-primary to-secondary rounded-full relative"
              initial={{ height: "0%" }}
              animate={{ 
                height: `${Math.min(100, scrollProgress * 100)}%`
              }}
              transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            >
              {/* Ellipse at the end when progress reaches 100% */}
              {scrollProgress >= 1 && (
                <motion.div
                  className="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-6 h-3 bg-gradient-to-r from-primary to-secondary rounded-full shadow-lg"
                  initial={{ scale: 0, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ duration: 0.4, ease: [0.25, 0.1, 0.25, 1] }}
                />
              )}
            </motion.div>
          </div>

          {/* Steps Container */}
          <div className="space-y-40">
            {mainSteps.map((step, index) => {
              const isActive = activeStep === step.id;
              const isLeft = index % 2 === 0; // Step 1 & 3 on left, Step 2 on right
              const stepNumber = `0${index + 1}`;
              
              return (
                <motion.div
                  key={step.id}
                  ref={(el) => stepRefs.current[index] = el}
                  className="relative"
                  initial={{ opacity: 0, y: 50 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.6, delay: index * 0.2 }}
                >
                  {/* Step Indicator Circle - Always in center */}
                  <motion.div
                    className={`
                      absolute left-1/2 transform -translate-x-1/2 w-16 h-16 rounded-full
                      flex items-center justify-center z-10 border-4 transition-all duration-500
                      ${isActive 
                        ? 'bg-primary border-white text-white shadow-xl scale-110' 
                        : 'bg-white border-gray-300 text-gray-600'
                      }
                    `}
                    animate={{ scale: isActive ? 1.1 : 1 }}
                    transition={{ duration: 0.3 }}
                  >
                    <div className="w-6 h-6">
                      {step.icon}
                    </div>
                  </motion.div>

                  {/* Content Container - Zigzag Layout */}
                  <div className="grid grid-cols-12 gap-8 items-center">
                    {/* Content Card */}
                    <motion.div
                      className={`${isLeft ? 'col-span-5' : 'col-span-5 col-start-8'}`}
                      initial={{ opacity: 0, x: isLeft ? -50 : 50 }}
                      animate={{ 
                        opacity: isActive ? 1 : 0.6, 
                        x: 0,
                        scale: isActive ? 1 : 0.95
                      }}
                      transition={{ duration: 0.5, delay: 0.2 }}
                    >
                      <Card className={`p-8 border-2 transition-all duration-500 rounded-3xl ${
                        isActive 
                          ? 'border-primary shadow-xl bg-gradient-to-br from-primary/5 to-secondary/5' 
                          : 'border-gray-200 bg-white'
                      }`}>
                        <CardContent className="p-0 text-center">
                          {/* Step Number */}
                          <motion.div
                            className={`text-6xl font-poppins font-light mb-4 transition-colors duration-300 ${
                              isActive ? 'text-primary' : 'text-gray-300'
                            }`}
                            animate={{ scale: isActive ? 1.1 : 1 }}
                            transition={{ duration: 0.3 }}
                          >
                            {stepNumber}
                          </motion.div>

                          {/* Step Title */}
                          <h3 className="font-poppins font-normal text-2xl text-gray-900 mb-4">
                            {step.title}
                          </h3>

                          {/* Step Description */}
                          <p className="text-gray-600 leading-relaxed mb-6 text-center font-light">
                            {step.description}
                          </p>

                          {/* Features List */}
                          {step.features && (
                            <div className="grid grid-cols-2 gap-3 mb-6">
                              {step.features.map((feature, featureIndex) => (
                                <motion.div
                                  key={featureIndex}
                                  className="flex items-center gap-2 text-left"
                                  initial={{ opacity: 0, x: -20 }}
                                  animate={{ opacity: isActive ? 1 : 0.7, x: 0 }}
                                  transition={{ duration: 0.3, delay: featureIndex * 0.1 }}
                                >
                                  <div className="w-4 h-4 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0">
                                    <Check className="w-2.5 h-2.5 text-green-600" />
                                  </div>
                                  <span className="text-gray-700 text-sm font-light">{feature}</span>
                                </motion.div>
                              ))}
                            </div>
                          )}

                          {/* Action Button */}
                          {isActive && (
                            <motion.div
                              className="mt-6"
                              initial={{ opacity: 0, y: 20 }}
                              animate={{ opacity: 1, y: 0 }}
                              transition={{ duration: 0.4, delay: 0.3 }}
                            >
                              <Button 
                                className="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-xl font-normal"
                                onClick={onPassesClick}
                              >
                                Get Started
                                <ChevronRight className="w-4 h-4 ml-2" />
                              </Button>
                            </motion.div>
                          )}
                        </CardContent>
                      </Card>
                    </motion.div>

                    {/* Spacer for the opposite side */}
                    <div className={`${isLeft ? 'col-span-6 col-start-7' : 'col-span-6'}`} />
                  </div>
                </motion.div>
              );
            })}
          </div>
        </div>

        {/* Make the most of every attraction section */}
        <AttractionHassleFreeSection />

        {/* Mobile App Section */}
        <MobileAppSection />

        {/* Why Choose CityCards Section */}
        <div className="my-20">
          <WhyChooseCityCards />
        </div>

        {/* Enhanced Testimonials Section */}
        <EnhancedTestimonials />

        {/* Reviews Section */}
        <ReviewsSection />
      </div>

      <Footer 
        onHomeClick={onHomeClick}
        onMelbourneClick={onMelbourneClick}
        onPassesClick={onPassesClick}
        onSignInClick={onSignInClick}
        onAttractionsClick={onAttractionsClick}
        onBlogsClick={onBlogsClick}
        onHowItWorksClick={onHowItWorksClick}
        onFAQClick={onFAQClick}
        onPrivacyPolicyClick={onPrivacyPolicyClick}
        onContactUsClick={onContactUsClick}
        currentPage={currentPage}
      />
    </div>
  );
}

export default HowItWorksPage;