import React, { useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Play, Pause, RotateCcw, Volume2, VolumeX, Maximize2, Minimize2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';

interface VisualTimerProps {
  duration: number; // in seconds
  onComplete?: () => void;
  onMilestone?: (percent: number) => void;
  colorScheme?: 'default' | 'calm' | 'energetic';
  showNumbers?: boolean;
  size?: 'small' | 'medium' | 'large' | 'fullscreen';
  autoStart?: boolean;
  taskTitle?: string;
}

const colorSchemes = {
  default: {
    start: 'hsl(142, 76%, 36%)',
    mid: 'hsl(45, 93%, 47%)',
    end: 'hsl(0, 84%, 60%)',
    bg: 'hsl(0, 0%, 90%)',
  },
  calm: {
    start: 'hsl(200, 70%, 50%)',
    mid: 'hsl(180, 60%, 45%)',
    end: 'hsl(280, 60%, 55%)',
    bg: 'hsl(220, 20%, 95%)',
  },
  energetic: {
    start: 'hsl(160, 84%, 39%)',
    mid: 'hsl(38, 92%, 50%)',
    end: 'hsl(350, 89%, 60%)',
    bg: 'hsl(0, 0%, 92%)',
  },
};

const sizes = {
  small: { ring: 120, stroke: 8, font: 'text-xl' },
  medium: { ring: 200, stroke: 12, font: 'text-3xl' },
  large: { ring: 300, stroke: 16, font: 'text-5xl' },
  fullscreen: { ring: 400, stroke: 20, font: 'text-7xl' },
};

export function VisualTimer({
  duration,
  onComplete,
  onMilestone,
  colorScheme = 'default',
  showNumbers = true,
  size = 'medium',
  autoStart = false,
  taskTitle,
}: VisualTimerProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();

  const [timeLeft, setTimeLeft] = useState(duration);
  const [isRunning, setIsRunning] = useState(autoStart);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [lastMilestone, setLastMilestone] = useState(100);

  const audioRef = useRef<HTMLAudioElement | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const colors = colorSchemes[colorScheme];
  const sizeConfig = isFullscreen ? sizes.fullscreen : sizes[size];

  const progress = timeLeft / duration;
  const percent = Math.round(progress * 100);

  // Calculate current color based on progress
  const getCurrentColor = useCallback(() => {
    if (progress > 0.5) {
      return colors.start;
    } else if (progress > 0.25) {
      return colors.mid;
    } else {
      return colors.end;
    }
  }, [progress, colors]);

  // Format time display
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Play sound effect
  const playSound = useCallback((type: 'tick' | 'milestone' | 'complete') => {
    if (!soundEnabled) return;

    // Simple beep sounds using Web Audio API
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    switch (type) {
      case 'tick':
        oscillator.frequency.value = 800;
        gainNode.gain.value = 0.1;
        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.05);
        break;
      case 'milestone':
        oscillator.frequency.value = 600;
        gainNode.gain.value = 0.2;
        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.2);
        break;
      case 'complete':
        oscillator.frequency.value = 440;
        gainNode.gain.value = 0.3;
        oscillator.start();
        setTimeout(() => {
          oscillator.frequency.value = 554;
        }, 200);
        setTimeout(() => {
          oscillator.frequency.value = 659;
        }, 400);
        oscillator.stop(audioContext.currentTime + 0.6);
        break;
    }
  }, [soundEnabled]);

  // Timer logic
  useEffect(() => {
    if (!isRunning || timeLeft <= 0) return;

    const interval = setInterval(() => {
      setTimeLeft((prev) => {
        const newTime = prev - 1;

        if (newTime <= 0) {
          playSound('complete');
          onComplete?.();
          setIsRunning(false);
          return 0;
        }

        return newTime;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [isRunning, timeLeft, onComplete, playSound]);

  // Milestone detection
  useEffect(() => {
    const milestones = [75, 50, 25, 10, 5];
    for (const milestone of milestones) {
      if (percent <= milestone && lastMilestone > milestone) {
        setLastMilestone(milestone);
        playSound('milestone');
        onMilestone?.(milestone);
        break;
      }
    }
  }, [percent, lastMilestone, onMilestone, playSound]);

  // Reset timer
  const reset = () => {
    setTimeLeft(duration);
    setIsRunning(false);
    setLastMilestone(100);
  };

  // Toggle fullscreen
  const toggleFullscreen = () => {
    if (!document.fullscreenElement && containerRef.current) {
      containerRef.current.requestFullscreen();
      setIsFullscreen(true);
    } else {
      document.exitFullscreen();
      setIsFullscreen(false);
    }
  };

  // SVG calculations
  const radius = (sizeConfig.ring - sizeConfig.stroke) / 2;
  const circumference = radius * 2 * Math.PI;
  const strokeDashoffset = circumference * (1 - progress);

  return (
    <div
      ref={containerRef}
      className={`
        flex flex-col items-center justify-center gap-6 p-6
        ${isFullscreen ? 'fixed inset-0 bg-background z-50' : ''}
        ${settings.reducedAnimations ? '' : 'transition-all duration-300'}
      `}
    >
      {taskTitle && (
        <h3 className="text-lg font-medium text-center text-muted-foreground max-w-md">
          {taskTitle}
        </h3>
      )}

      {/* Visual Timer Ring */}
      <div className="relative" style={{ width: sizeConfig.ring, height: sizeConfig.ring }}>
        <svg
          className="transform -rotate-90"
          width={sizeConfig.ring}
          height={sizeConfig.ring}
        >
          {/* Background circle */}
          <circle
            cx={sizeConfig.ring / 2}
            cy={sizeConfig.ring / 2}
            r={radius}
            stroke={colors.bg}
            strokeWidth={sizeConfig.stroke}
            fill="none"
          />
          {/* Progress circle */}
          <motion.circle
            cx={sizeConfig.ring / 2}
            cy={sizeConfig.ring / 2}
            r={radius}
            stroke={getCurrentColor()}
            strokeWidth={sizeConfig.stroke}
            fill="none"
            strokeLinecap="round"
            strokeDasharray={circumference}
            initial={{ strokeDashoffset: 0 }}
            animate={{ strokeDashoffset }}
            transition={{ duration: settings.reducedAnimations ? 0 : 0.5, ease: 'easeOut' }}
          />
        </svg>

        {/* Time display in center */}
        {showNumbers && (
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <AnimatePresence mode="wait">
              <motion.span
                key={timeLeft}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: settings.reducedAnimations ? 0 : 0.2 }}
                className={`font-mono font-bold ${sizeConfig.font}`}
                style={{ color: getCurrentColor() }}
              >
                {formatTime(timeLeft)}
              </motion.span>
            </AnimatePresence>
            <span className="text-sm text-muted-foreground mt-1">
              {percent}% {t('adhd.timer.remaining')}
            </span>
          </div>
        )}
      </div>

      {/* Controls */}
      <div className="flex items-center gap-3">
        <Button
          variant="outline"
          size="icon"
          onClick={() => setIsRunning(!isRunning)}
          className={settings.largerTargets ? 'h-12 w-12' : 'h-10 w-10'}
        >
          {isRunning ? (
            <Pause className="h-5 w-5" />
          ) : (
            <Play className="h-5 w-5" />
          )}
        </Button>

        <Button
          variant="outline"
          size="icon"
          onClick={reset}
          className={settings.largerTargets ? 'h-12 w-12' : 'h-10 w-10'}
        >
          <RotateCcw className="h-5 w-5" />
        </Button>

        <Button
          variant="outline"
          size="icon"
          onClick={() => setSoundEnabled(!soundEnabled)}
          className={settings.largerTargets ? 'h-12 w-12' : 'h-10 w-10'}
        >
          {soundEnabled ? (
            <Volume2 className="h-5 w-5" />
          ) : (
            <VolumeX className="h-5 w-5" />
          )}
        </Button>

        <Button
          variant="outline"
          size="icon"
          onClick={toggleFullscreen}
          className={settings.largerTargets ? 'h-12 w-12' : 'h-10 w-10'}
        >
          {isFullscreen ? (
            <Minimize2 className="h-5 w-5" />
          ) : (
            <Maximize2 className="h-5 w-5" />
          )}
        </Button>
      </div>

      {/* Progress milestones */}
      <div className="flex gap-2">
        {[75, 50, 25, 0].map((milestone) => (
          <div
            key={milestone}
            className={`
              w-3 h-3 rounded-full transition-all
              ${percent <= milestone ? 'bg-primary' : 'bg-muted'}
            `}
          />
        ))}
      </div>
    </div>
  );
}
