import { motion, AnimatePresence } from 'framer-motion';
import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ValuePill } from './ValuePill';
import { useHapticPulse } from '@/hooks/use-ripple-effect';
import { useRef, useCallback } from 'react';
import type { ValuePill as ValuePillType } from '@/config/quizValuePills';

interface QuizOption {
  value: string;
  label: string;
}

interface QuizQuestionProps {
  question: string;
  options: QuizOption[];
  selectedValue: string | null;
  onSelect: (value: string) => void;
  isLoading?: boolean;
  valuePill?: ValuePillType | null;
  showPill?: boolean;
  onPillComplete?: () => void;
}

export function QuizQuestion({ 
  question, 
  options, 
  selectedValue, 
  onSelect,
  isLoading = false,
  valuePill,
  showPill = false,
  onPillComplete,
}: QuizQuestionProps) {
  // Reduced motion handled via CSS @media (prefers-reduced-motion) in index.css
  const { triggerPulse } = useHapticPulse();
  const optionRefs = useRef<Map<string, HTMLButtonElement>>(new Map());

  // Handle option click with instant visual feedback
  const handleOptionClick = useCallback((value: string, event: React.MouseEvent<HTMLButtonElement>) => {
    if (isLoading || showPill) return;
    
    const element = event.currentTarget;
    
    // Trigger haptic pulse immediately for instant feedback
    triggerPulse(element);
    
    // Call onSelect immediately - no delay
    onSelect(value);
  }, [isLoading, showPill, onSelect, triggerPulse]);

  // Create ripple effect on click
  const createRipple = useCallback((event: React.MouseEvent<HTMLButtonElement>) => {
    const button = event.currentTarget;
    const rect = button.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const size = Math.max(rect.width, rect.height) * 2;

    const ripple = document.createElement('span');
    ripple.style.cssText = `
      position: absolute;
      left: ${x - size / 2}px;
      top: ${y - size / 2}px;
      width: ${size}px;
      height: ${size}px;
      background: hsl(var(--primary) / 0.25);
      border-radius: 50%;
      transform: scale(0);
      animation: ripple-expand 400ms cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
      pointer-events: none;
      z-index: 0;
    `;

    button.appendChild(ripple);
    setTimeout(() => ripple.remove(), 400);
  }, []);

  return (
    <div className="w-full max-w-lg mx-auto space-y-8">
      {/* Question title - CSS-only fade-in (no framer-motion overhead per step) */}
      <h2 className="quiz-css-fade-in text-2xl md:text-3xl font-bold text-foreground text-center leading-tight tracking-tight">
        {question}
      </h2>

      {/* Options - render statically (no per-button motion) for snappier transitions */}
      <div className="space-y-3">
        {options.map((option) => {
          const isSelected = selectedValue === option.value;

          return (
            <button
              key={option.value}
              ref={(el) => {
                if (el) optionRefs.current.set(option.value, el);
              }}
              onClick={(e) => {
                createRipple(e);
                handleOptionClick(option.value, e);
              }}
              disabled={isLoading || showPill}
              className={cn(
                "quiz-option-card w-full text-left",
                "focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 focus:ring-offset-background",
                "disabled:cursor-not-allowed",
                isSelected && "selected"
              )}
            >
              <div className="flex items-center gap-4 relative z-10">
                {/* Radio indicator with CSS-only check transition (no AnimatePresence) */}
                <div
                  className={cn(
                    "w-6 h-6 rounded-full border-2 flex items-center justify-center flex-shrink-0",
                    "transition-colors duration-200",
                    isSelected
                      ? "border-primary bg-primary shadow-[0_0_12px_-2px_hsl(var(--primary)/0.5)]"
                      : "border-white/30 bg-white/5"
                  )}
                >
                  <Check
                    className={cn(
                      "w-3.5 h-3.5 text-primary-foreground transition-transform duration-200 ease-out",
                      isSelected ? "scale-100 opacity-100" : "scale-0 opacity-0"
                    )}
                    strokeWidth={3}
                  />
                </div>
                
                
                {/* Option label */}
                <span className={cn(
                  "text-base md:text-lg transition-colors duration-150",
                  isSelected ? "text-foreground font-medium" : "text-muted-foreground"
                )}>
                  {option.label}
                </span>
              </div>
            </button>
          );
        })}
      </div>

      {/* Value Pill - appears after selection */}
      <AnimatePresence mode="wait">
        {showPill && valuePill && onPillComplete && (
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
          >
            <ValuePill 
              pill={valuePill} 
              onComplete={onPillComplete}
            />
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
