import { useState, useCallback, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import IPhoneMockup from '@/components/landing/IPhoneMockup';
import { FeatureCarousel } from './FeatureCarousel';
import { useShouldReduceAnimations } from '@/hooks/use-reduced-motion';
import type { FeatureShowcase } from '@/config/quizFeatureShowcases';

interface QuizFeatureShowcaseProps {
  feature: FeatureShowcase;
  onContinue: () => void;
  /** Use lightweight CSS animations instead of framer-motion (for in-app browsers) */
  useLightAnimations?: boolean;
}

// Apple-style transition variants — sem filter:blur (caro em WebView)
const imageVariants = {
  enter: { opacity: 0, scale: 0.98 },
  center: { opacity: 1, scale: 1 },
  exit: { opacity: 0, scale: 0.98 },
};

// Light variants - identical to imageVariants now (kept for prop compatibility)
const imageVariantsLight = {
  enter: { opacity: 0 },
  center: { opacity: 1 },
  exit: { opacity: 0 },
};

const contentVariants = {
  enter: { 
    opacity: 0, 
    y: 12 
  },
  center: { 
    opacity: 1, 
    y: 0 
  },
  exit: { 
    opacity: 0, 
    y: -8 
  },
};

// Light content variants - simpler animation
const contentVariantsLight = {
  enter: { opacity: 0 },
  center: { opacity: 1 },
  exit: { opacity: 0 },
};

export function QuizFeatureShowcase({ feature, onContinue, useLightAnimations: useLightAnimationsProp }: QuizFeatureShowcaseProps) {
  const shouldReduceAnimations = useShouldReduceAnimations();
  // Use light animations if prop is true OR if user prefers reduced motion
  const useLightAnimations = useLightAnimationsProp || shouldReduceAnimations;
  const [activeIndex, setActiveIndex] = useState(0);
  const [canContinue, setCanContinue] = useState(false);

  // Get current content from carousel or fallback to main
  const currentImage = feature.carouselImages[activeIndex] || {
    src: feature.mainImage,
    alt: feature.title,
    shortTitle: '',
    title: feature.title + ' ' + feature.titleHighlight,
    description: feature.description,
  };

  // Minimum time before allowing continue (prevents accidental skips)
  // Reduzido de 1500ms para 600ms (suficiente para evitar duplo-clique sem criar atrito)
  useEffect(() => {
    const timer = setTimeout(() => {
      setCanContinue(true);
    }, 600);
    return () => clearTimeout(timer);
  }, []);

  // Reset index when feature changes
  useEffect(() => {
    setActiveIndex(0);
  }, [feature.id]);

  const handlePillSelect = useCallback((index: number) => {
    setActiveIndex(index);
  }, []);

  const getGlowClass = () => {
    switch (feature.glowColor) {
      case 'purple': return 'feature-glow-purple';
      case 'cyan': return 'feature-glow-cyan';
      case 'orange': return 'feature-glow-orange';
      case 'green': return 'feature-glow-green';
      default: return 'feature-glow-primary';
    }
  };

  const getGradientClass = () => {
    switch (feature.glowColor) {
      case 'purple': return 'from-purple-400 to-purple-600';
      case 'cyan': return 'from-cyan-400 to-cyan-600';
      case 'orange': return 'from-orange-400 to-orange-600';
      case 'green': return 'from-green-400 to-green-600';
      default: return 'from-primary to-primary/80';
    }
  };

  const transitionConfig = {
    duration: useLightAnimations ? 0.15 : 0.45,
    ease: [0.25, 0.1, 0.25, 1] as const,
  };

  // Select variants based on light mode
  const activeImageVariants = useLightAnimations ? imageVariantsLight : imageVariants;
  const activeContentVariants = useLightAnimations ? contentVariantsLight : contentVariants;

  return (
    <motion.div
      className="w-full max-w-lg mx-auto flex flex-col items-center gap-5 px-4"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: useLightAnimations ? 0.15 : 0.25 }}
    >
      {/* iPhone Mockup with crossfade transition - Fixed dimensions to prevent CLS */}
      <div className={`relative ${getGlowClass()}`} style={{ minHeight: '434px', contain: 'layout' }}>
        <AnimatePresence mode="wait">
          <motion.div
            key={currentImage.src}
            variants={activeImageVariants}
            initial="enter"
            animate="center"
            exit="exit"
            transition={transitionConfig}
            className="flex items-center justify-center"
          >
            <IPhoneMockup
              image={currentImage.src}
              alt={currentImage.alt}
              priority
              animate={false}
              showDetailedSkeleton
              className="w-[200px] md:w-[220px]"
            />
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Dynamic Title and Description - Increased min-height to prevent CLS */}
      <AnimatePresence mode="wait">
        <motion.div
          key={activeIndex}
          className="text-center space-y-2 min-h-[100px] flex flex-col justify-center"
          variants={activeContentVariants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{ duration: useLightAnimations ? 0.15 : 0.35, ease: [0.25, 0.1, 0.25, 1] }}
        >
          <h2 className="text-xl md:text-2xl font-bold text-foreground leading-tight">
            <span className={`bg-gradient-to-r ${getGradientClass()} bg-clip-text text-transparent`}>
              {currentImage.title}
            </span>
            {currentImage.titleHighlight && (
              <span className={`bg-gradient-to-r ${getGradientClass()} bg-clip-text text-transparent animate-shake-subtle`}>
                {' '}{currentImage.titleHighlight}
              </span>
            )}
          </h2>
          <p className="text-sm text-muted-foreground leading-relaxed max-w-sm mx-auto">
            {currentImage.description}
          </p>
        </motion.div>
      </AnimatePresence>

      {/* Expandable Pills Carousel - No Y displacement to prevent CLS */}
      {feature.carouselImages.length > 0 && (
        <motion.div
          className="w-full"
          initial={useLightAnimations ? {} : { opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: useLightAnimations ? 0 : 0.15, duration: useLightAnimations ? 0.15 : 0.4 }}
        >
          <FeatureCarousel
            images={feature.carouselImages}
            activeIndex={activeIndex}
            onSelect={handlePillSelect}
            glowColor={feature.glowColor}
          />
        </motion.div>
      )}

      {/* CTA Button - No Y displacement to prevent CLS */}
      <motion.div
        className="w-full pt-3"
        initial={useLightAnimations ? {} : { opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: useLightAnimations ? 0 : 0.25, duration: useLightAnimations ? 0.15 : 0.4 }}
      >
        <Button
          onClick={onContinue}
          disabled={!canContinue}
          className="w-full h-14 text-base font-semibold rounded-2xl bg-primary hover:bg-primary/90 text-primary-foreground shadow-lg shadow-primary/25 transition-all duration-300 disabled:opacity-50 group"
        >
          <span>{feature.ctaText}</span>
          <ArrowRight className="w-5 h-5 ml-2 transition-transform group-hover:translate-x-1" />
        </Button>
      </motion.div>
    </motion.div>
  );
}
