import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Play, Pause, CheckCircle2, ArrowRight, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import type { Task } from '@shared/schema';

interface FiveMinuteStarterProps {
  task: Task;
  onClose: () => void;
  onComplete: () => void;
  onContinue?: () => void;
}

type Phase = 'ready' | 'running' | 'done';

export function FiveMinuteStarter({
  task,
  onClose,
  onComplete,
  onContinue,
}: FiveMinuteStarterProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();

  const [phase, setPhase] = useState<Phase>('ready');
  const [timeLeft, setTimeLeft] = useState(5 * 60); // 5 minutes in seconds
  const [isRunning, setIsRunning] = useState(false);

  const progress = ((5 * 60 - timeLeft) / (5 * 60)) * 100;

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

    const interval = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          setIsRunning(false);
          setPhase('done');
          // Play completion sound
          const audio = new Audio('/sounds/complete.mp3');
          audio.volume = 0.3;
          audio.play().catch(() => {});
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

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

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

  const handleStart = () => {
    setPhase('running');
    setIsRunning(true);
  };

  const handlePause = () => {
    setIsRunning(!isRunning);
  };

  const handleDone = () => {
    onComplete();
    onClose();
  };

  const handleContinue = () => {
    // Reset for another 5 minutes
    setTimeLeft(5 * 60);
    setPhase('running');
    setIsRunning(true);
    onContinue?.();
  };

  const handleTakeBreak = () => {
    // Just close without completing
    onClose();
  };

  return (
    <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 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm"
    >
      <div className="relative w-full max-w-md bg-card rounded-2xl border shadow-2xl p-6">
        {/* Close button */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 rounded-full hover:bg-muted transition-colors"
        >
          <X className="h-5 w-5 text-muted-foreground" />
        </button>

        <AnimatePresence mode="wait">
          {phase === 'ready' && (
            <motion.div
              key="ready"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="text-center"
            >
              <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-primary/10 flex items-center justify-center">
                <Play className="h-10 w-10 text-primary" />
              </div>

              <h3 className="text-xl font-bold mb-2">
                {t('adhd.fiveMin.title')}
              </h3>
              <p className="text-muted-foreground mb-2 truncate max-w-full">
                {task.title}
              </p>
              <p className="text-sm text-muted-foreground mb-6">
                {t('adhd.fiveMin.prompt')}
              </p>

              <Button
                size="lg"
                onClick={handleStart}
                className={`w-full ${settings.largerTargets ? 'h-14 text-lg' : 'h-12'}`}
              >
                <Play className="h-5 w-5 mr-2" />
                {t('adhd.fiveMin.start')}
              </Button>

              <p className="text-xs text-muted-foreground mt-4 italic">
                {t('adhd.fiveMin.noObligation')}
              </p>
            </motion.div>
          )}

          {phase === 'running' && (
            <motion.div
              key="running"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="text-center"
            >
              {/* Visual progress ring */}
              <div className="relative w-48 h-48 mx-auto mb-6">
                <svg className="w-full h-full transform -rotate-90">
                  <circle
                    cx="96"
                    cy="96"
                    r="88"
                    stroke="currentColor"
                    strokeWidth="8"
                    fill="none"
                    className="text-muted"
                  />
                  <motion.circle
                    cx="96"
                    cy="96"
                    r="88"
                    stroke="currentColor"
                    strokeWidth="8"
                    fill="none"
                    className="text-primary"
                    strokeLinecap="round"
                    strokeDasharray={553}
                    animate={{ strokeDashoffset: 553 - (553 * progress) / 100 }}
                    transition={{ duration: 0.5 }}
                  />
                </svg>
                <div className="absolute inset-0 flex flex-col items-center justify-center">
                  <span className="text-4xl font-mono font-bold">
                    {formatTime(timeLeft)}
                  </span>
                  <span className="text-sm text-muted-foreground">
                    {t('adhd.fiveMin.remaining')}
                  </span>
                </div>
              </div>

              <p className="font-medium mb-4 truncate px-4">
                {task.title}
              </p>

              <div className="flex gap-3">
                <Button
                  variant="outline"
                  onClick={handlePause}
                  className="flex-1"
                >
                  {isRunning ? (
                    <>
                      <Pause className="h-4 w-4 mr-2" />
                      {t('adhd.fiveMin.pause')}
                    </>
                  ) : (
                    <>
                      <Play className="h-4 w-4 mr-2" />
                      {t('adhd.fiveMin.resume')}
                    </>
                  )}
                </Button>
                <Button onClick={handleDone} className="flex-1">
                  <CheckCircle2 className="h-4 w-4 mr-2" />
                  {t('adhd.fiveMin.done')}
                </Button>
              </div>

              <p className="text-xs text-muted-foreground mt-4">
                {t('adhd.fiveMin.encouragement')}
              </p>
            </motion.div>
          )}

          {phase === 'done' && (
            <motion.div
              key="done"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0 }}
              className="text-center"
            >
              <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-green-500/20 flex items-center justify-center">
                <CheckCircle2 className="h-10 w-10 text-green-500" />
              </div>

              <h3 className="text-xl font-bold mb-2">
                {t('adhd.fiveMin.congrats')}
              </h3>
              <p className="text-muted-foreground mb-6">
                {t('adhd.fiveMin.fiveMinDone')}
              </p>

              <div className="flex flex-col gap-3">
                <Button
                  size="lg"
                  onClick={handleContinue}
                  className={`w-full ${settings.largerTargets ? 'h-14' : 'h-12'}`}
                >
                  <ArrowRight className="h-5 w-5 mr-2" />
                  {t('adhd.fiveMin.continueWorking')}
                </Button>

                <div className="flex gap-3">
                  <Button
                    variant="outline"
                    onClick={handleDone}
                    className="flex-1"
                  >
                    <CheckCircle2 className="h-4 w-4 mr-2" />
                    {t('adhd.fiveMin.finished')}
                  </Button>
                  <Button
                    variant="ghost"
                    onClick={handleTakeBreak}
                    className="flex-1"
                  >
                    {t('adhd.fiveMin.takeBreak')}
                  </Button>
                </div>
              </div>

              <p className="text-sm text-primary mt-4 font-medium">
                +10 XP {t('adhd.fiveMin.earned')}
              </p>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </motion.div>
  );
}
