import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Play, Pause, Volume2, VolumeX, SkipForward, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ambientPlayer } from '@/lib/ambient-sounds';
import { useTranslation } from 'react-i18next';
import { triggerConfetti } from '@/lib/confetti';
import { playSuccessSound } from '@/lib/sounds';

interface PomodoroOverlayProps {
    taskId: string | null;
    taskTitle: string;
    isOpen: boolean;
    onClose: () => void;
    onCompleteTask: (taskId: string) => void;
}

export default function PomodoroOverlay({ taskId, taskTitle, isOpen, onClose, onCompleteTask }: PomodoroOverlayProps) {
    const { t } = useTranslation();
    const [timeLeft, setTimeLeft] = useState(25 * 60);
    const [isActive, setIsActive] = useState(false);
    const [isSoundPlaying, setIsSoundPlaying] = useState(false);
    const [mode, setMode] = useState<'focus' | 'break'>('focus');

    const workerRef = useRef<Worker | null>(null);

    // Initialize Worker
    useEffect(() => {
        if (typeof Worker !== 'undefined') {
            workerRef.current = new Worker(new URL('../workers/timer.worker.ts', import.meta.url), { type: 'module' });

            workerRef.current.onmessage = (e) => {
                const { type, remaining } = e.data;
                if (type === 'TICK') {
                    setTimeLeft(remaining);
                } else if (type === 'COMPLETE') {
                    setIsActive(false);
                    playSuccessSound();
                    triggerConfetti(0.5, 0.5);
                    // If focus finished, propose break?
                }
            };
        }

        return () => {
            workerRef.current?.terminate();
            ambientPlayer.stop();
        };
    }, []);

    // Timer Control
    useEffect(() => {
        if (isActive) {
            workerRef.current?.postMessage({
                command: 'START',
                payload: { durationSeconds: timeLeft }
            });
        } else {
            workerRef.current?.postMessage({ command: 'STOP' });
        }
    }, [isActive]);

    const toggleTimer = () => setIsActive(!isActive);

    const toggleSound = () => {
        const playing = ambientPlayer.toggle();
        setIsSoundPlaying(playing);
    };

    const skipTimer = () => {
        setIsActive(false);
        // Switch modes
        if (mode === 'focus') {
            setMode('break');
            setTimeLeft(5 * 60);
        } else {
            setMode('focus');
            setTimeLeft(25 * 60);
        }
    };

    const handleComplete = () => {
        if (taskId) {
            onCompleteTask(taskId);
            onClose();
            setIsActive(false);
            ambientPlayer.stop();
        }
    };

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

    // Circular Progress Calculation
    const totalTime = mode === 'focus' ? 25 * 60 : 5 * 60;
    const progress = ((totalTime - timeLeft) / totalTime) * 100;
    const circleSize = 280;
    const radius = 120;
    const circumference = 2 * Math.PI * radius;
    const strokeDashoffset = circumference - (progress / 100) * circumference;

    return (
        <AnimatePresence>
            {isOpen && (
                <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    className="fixed inset-0 z-50 bg-background/95 backdrop-blur-sm flex flex-col items-center justify-center"
                >
                    <Button
                        variant="ghost"
                        size="icon"
                        className="absolute top-6 right-6 h-12 w-12 rounded-full hover:bg-muted"
                        onClick={() => {
                            setIsActive(false);
                            ambientPlayer.stop();
                            onClose();
                        }}
                    >
                        <X className="w-6 h-6" />
                    </Button>

                    <div className="text-center space-y-8 max-w-md w-full px-4">
                        <div className="space-y-2">
                            <h2 className="text-3xl font-bold tracking-tight">{mode === 'focus' ? 'Focus Time' : 'Break Time'}</h2>
                            <p className="text-xl text-muted-foreground truncate">{taskTitle}</p>
                        </div>

                        <div className="relative flex items-center justify-center">
                            {/* SVG Ring */}
                            <svg width={circleSize} height={circleSize} className="transform -rotate-90">
                                {/* Background Circle */}
                                <circle
                                    cx={circleSize / 2}
                                    cy={circleSize / 2}
                                    r={radius}
                                    stroke="currentColor"
                                    strokeWidth="12"
                                    fill="transparent"
                                    className="text-muted/20"
                                />
                                {/* Progress Circle */}
                                <circle
                                    cx={circleSize / 2}
                                    cy={circleSize / 2}
                                    r={radius}
                                    stroke="currentColor"
                                    strokeWidth="12"
                                    fill="transparent"
                                    strokeDasharray={circumference}
                                    strokeDashoffset={strokeDashoffset}
                                    strokeLinecap="round"
                                    className={`transition-all duration-1000 ease-linear ${mode === 'focus' ? 'text-violet-600' : 'text-green-500'}`}
                                />
                            </svg>

                            {/* Time Display */}
                            <div className="absolute inset-0 flex items-center justify-center">
                                <span className="text-6xl font-mono font-bold tracking-tighter tabular-nums">
                                    {formatTime(timeLeft)}
                                </span>
                            </div>
                        </div>

                        <div className="flex items-center justify-center gap-6">
                            <Button
                                size="icon"
                                variant="outline"
                                className="h-14 w-14 rounded-full border-2"
                                onClick={toggleSound}
                            >
                                {isSoundPlaying ? <Volume2 className="w-6 h-6" /> : <VolumeX className="w-6 h-6" />}
                            </Button>

                            <Button
                                size="icon"
                                className={`h-20 w-20 rounded-full shadow-lg transition-transform hover:scale-105 active:scale-95 ${isActive ? 'bg-orange-500 hover:bg-orange-600' : 'bg-primary hover:bg-primary/90'}`}
                                onClick={toggleTimer}
                            >
                                {isActive ? <Pause className="w-8 h-8 fill-current" /> : <Play className="w-8 h-8 fill-current ml-1" />}
                            </Button>

                            <Button
                                size="icon"
                                variant="outline"
                                className="h-14 w-14 rounded-full border-2"
                                onClick={skipTimer}
                            >
                                <SkipForward className="w-6 h-6" />
                            </Button>
                        </div>

                        {taskId && mode === 'focus' && (
                            <Button
                                variant="ghost"
                                className="mt-8 text-muted-foreground hover:text-green-600 hover:bg-green-50 dark:hover:bg-green-950/20"
                                onClick={handleComplete}
                            >
                                <CheckCircle className="w-5 h-5 mr-2" />
                                Mark Task Complete
                            </Button>
                        )}
                    </div>
                </motion.div>
            )}
        </AnimatePresence>
    );
}
