'use client';
import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Mic, Volume2, Sparkles, MicOff } from 'lucide-react';
import WaveAnimation from './WaveAnimation';

export type VoiceState = 'idle' | 'listening' | 'thinking' | 'speaking';

interface Props {
  state: VoiceState;
  audioLevel?: number;
  onTap: () => void;
  onLongPress?: () => void;
  disabled?: boolean;
  size?: 'sm' | 'md' | 'lg';
}

const STATE_CONFIG = {
  idle:      { bg: 'linear-gradient(135deg, #6366f1, #a855f7)', label: 'Tap to speak',  icon: Mic,      glow: 'rgba(99,102,241,0.4)'  },
  listening: { bg: 'linear-gradient(135deg, #ef4444, #dc2626)', label: 'Listening...',  icon: Mic,      glow: 'rgba(239,68,68,0.5)'   },
  thinking:  { bg: 'linear-gradient(135deg, #f59e0b, #d97706)', label: 'Thinking...',   icon: Sparkles, glow: 'rgba(245,158,11,0.4)'  },
  speaking:  { bg: 'linear-gradient(135deg, #3b82f6, #2563eb)', label: 'Speaking...',   icon: Volume2,  glow: 'rgba(59,130,246,0.4)'  },
};

const SIZE_CONFIG = {
  sm: { button: 56, icon: 20, fontSize: 11 },
  md: { button: 72, icon: 24, fontSize: 12 },
  lg: { button: 80, icon: 28, fontSize: 13 },
};

export default function GeminiVoiceButton({ state, audioLevel = 0, onTap, onLongPress, disabled, size = 'lg' }: Props) {
  const [pressing, setPressing] = useState(false);
  const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const config = STATE_CONFIG[state];
  const sz = SIZE_CONFIG[size];

  const handlePointerDown = useCallback(() => {
    setPressing(true);
    // Haptic feedback
    if ('vibrate' in navigator) navigator.vibrate(50);
    // Long press detection
    if (onLongPress) {
      longPressTimer.current = setTimeout(() => {
        if ('vibrate' in navigator) navigator.vibrate([50, 100, 50]);
        onLongPress();
      }, 600);
    }
  }, [onLongPress]);

  const handlePointerUp = useCallback(() => {
    setPressing(false);
    if (longPressTimer.current) {
      clearTimeout(longPressTimer.current);
      longPressTimer.current = null;
    }
  }, []);

  const handleClick = useCallback(() => {
    if (disabled) return;
    if ('vibrate' in navigator) navigator.vibrate(50);
    onTap();
  }, [disabled, onTap]);

  return (
    <div className="flex flex-col items-center gap-3">
      {/* Wave animation above button */}
      <AnimatePresence>
        {(state === 'listening' || state === 'speaking') && (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}>
            <WaveAnimation isActive={true} audioLevel={audioLevel} barCount={20} />
          </motion.div>
        )}
      </AnimatePresence>

      {/* Main button */}
      <div className="relative flex items-center justify-center">
        {/* Pulse ring for listening */}
        {state === 'listening' && (
          <>
            <motion.div className="absolute rounded-full"
              style={{ width: sz.button + 32, height: sz.button + 32, background: 'rgba(239,68,68,0.15)' }}
              animate={{ scale: [1, 1.3, 1], opacity: [0.6, 0, 0.6] }}
              transition={{ duration: 1.5, repeat: Infinity }} />
            <motion.div className="absolute rounded-full"
              style={{ width: sz.button + 16, height: sz.button + 16, background: 'rgba(239,68,68,0.2)' }}
              animate={{ scale: [1, 1.2, 1], opacity: [0.8, 0.2, 0.8] }}
              transition={{ duration: 1.5, repeat: Infinity, delay: 0.3 }} />
          </>
        )}

        {/* Sparkle ring for thinking */}
        {state === 'thinking' && (
          <motion.div className="absolute rounded-full border-2 border-amber-400"
            style={{ width: sz.button + 20, height: sz.button + 20, borderStyle: 'dashed' }}
            animate={{ rotate: 360 }}
            transition={{ duration: 3, repeat: Infinity, ease: 'linear' }} />
        )}

        {/* Button */}
        <motion.button
          onClick={handleClick}
          onPointerDown={handlePointerDown}
          onPointerUp={handlePointerUp}
          onPointerLeave={handlePointerUp}
          disabled={disabled}
          whileTap={{ scale: 0.92 }}
          animate={{ scale: pressing ? 0.95 : 1 }}
          className="relative flex items-center justify-center rounded-full cursor-pointer select-none"
          style={{
            width: sz.button, height: sz.button,
            background: config.bg,
            boxShadow: `0 8px 32px ${config.glow}, 0 4px 16px rgba(0,0,0,0.2)`,
            border: 'none', outline: 'none',
          }}
          aria-label={config.label}>
          <motion.div
            key={state}
            initial={{ scale: 0, rotate: -90 }}
            animate={{ scale: 1, rotate: 0 }}
            transition={{ type: 'spring', stiffness: 400, damping: 20 }}>
            <config.icon
              size={sz.icon}
              color="white"
              className={state === 'thinking' ? 'animate-sparkle' : state === 'listening' ? 'animate-voice-pulse' : ''}
            />
          </motion.div>
        </motion.button>
      </div>

      {/* State label */}
      <motion.p
        key={state}
        initial={{ opacity: 0, y: 4 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-xs font-semibold"
        style={{ color: 'var(--text-secondary)', fontSize: sz.fontSize }}>
        {config.label}
      </motion.p>
    </div>
  );
}

// Need useRef
import { useRef } from 'react';
