import React, { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ChevronLeft,
  ChevronRight,
  CheckCircle2,
  Clock,
  Play,
  SkipForward,
  Focus,
  Sparkles,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import { VisualTimer } from '../timer/VisualTimer';
import { FiveMinuteStarter } from './FiveMinuteStarter';
import { useEncouragement, EncouragementToast } from '../feedback/EncouragementToast';
import type { Task } from '@shared/schema';
import confetti from 'canvas-confetti';

interface SingleTaskViewProps {
  onExit?: () => void;
}

export function SingleTaskView({ onExit }: SingleTaskViewProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();
  const queryClient = useQueryClient();
  const encouragement = useEncouragement();

  const [currentIndex, setCurrentIndex] = useState(0);
  const [showTimer, setShowTimer] = useState(false);
  const [showFiveMin, setShowFiveMin] = useState(false);

  const { data: tasks = [] } = useQuery<Task[]>({
    queryKey: ['/api/tasks'],
  });

  // Filter to actionable tasks (not done, no subtasks)
  const actionableTasks = useMemo(() => {
    return tasks.filter((task) => {
      if (task.status === 'done') return false;
      // Exclude parent tasks (tasks with subtasks)
      if (tasks.some((t) => t.parentTaskId === task.id)) return false;
      return true;
    });
  }, [tasks]);

  const currentTask = actionableTasks[currentIndex];
  const totalTasks = actionableTasks.length;

  // Complete task mutation
  const completeMutation = useMutation({
    mutationFn: async (taskId: string) => {
      const res = await fetch(`/api/tasks/${taskId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ status: 'done' }),
      });
      if (!res.ok) throw new Error('Failed to complete task');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
      queryClient.invalidateQueries({ queryKey: ['/api/user'] });

      confetti({
        particleCount: 100,
        spread: 70,
        origin: { y: 0.6 },
      });

      encouragement.show('taskComplete', undefined, 50);

      // Move to next task if available
      if (currentIndex >= actionableTasks.length - 1) {
        setCurrentIndex(Math.max(0, actionableTasks.length - 2));
      }
    },
  });

  const handleComplete = () => {
    if (currentTask) {
      completeMutation.mutate(currentTask.id);
    }
  };

  const handleNext = () => {
    if (currentIndex < totalTasks - 1) {
      setCurrentIndex(currentIndex + 1);
    }
  };

  const handlePrev = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  const handleSkip = () => {
    handleNext();
  };

  if (totalTasks === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] p-8 text-center">
        <Sparkles className="h-16 w-16 text-primary mb-6" />
        <h2 className="text-2xl font-bold mb-2">{t('adhd.singleTask.allDone')}</h2>
        <p className="text-muted-foreground mb-6">{t('adhd.singleTask.allDoneDesc')}</p>
        {onExit && (
          <Button onClick={onExit} size="lg">
            {t('adhd.singleTask.exit')}
          </Button>
        )}
      </div>
    );
  }

  return (
    <>
      <div className="flex flex-col items-center justify-center min-h-[70vh] p-6">
        {/* Progress indicator */}
        <div className="w-full max-w-md mb-8">
          <div className="flex items-center justify-between text-sm text-muted-foreground mb-2">
            <span>{t('adhd.singleTask.task')} {currentIndex + 1} / {totalTasks}</span>
            <span>{Math.round(((totalTasks - actionableTasks.length + (tasks.length - actionableTasks.length)) / tasks.length) * 100)}% {t('adhd.singleTask.complete')}</span>
          </div>
          <Progress value={((currentIndex + 1) / totalTasks) * 100} className="h-2" />
        </div>

        {/* Timer (when active) */}
        <AnimatePresence>
          {showTimer && currentTask?.estimatedDuration && (
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9 }}
              className="mb-8"
            >
              <VisualTimer
                duration={currentTask.estimatedDuration * 60}
                onComplete={() => setShowTimer(false)}
                taskTitle={currentTask.title}
                size="medium"
              />
            </motion.div>
          )}
        </AnimatePresence>

        {/* 5-Minute Starter */}
        <AnimatePresence>
          {showFiveMin && currentTask && (
            <FiveMinuteStarter
              task={currentTask}
              onClose={() => setShowFiveMin(false)}
              onComplete={handleComplete}
            />
          )}
        </AnimatePresence>

        {/* Task Card */}
        {!showTimer && !showFiveMin && (
          <AnimatePresence mode="wait">
            <motion.div
              key={currentTask?.id}
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -50 }}
              transition={{ duration: settings.reducedAnimations ? 0 : 0.3 }}
              className="w-full max-w-lg"
            >
              <div className="bg-card rounded-2xl border shadow-lg p-8">
                {/* Priority badge */}
                {currentTask && (
                  <div className="flex items-center justify-between mb-4">
                    <Badge
                      variant={
                        currentTask.priority === 'high'
                          ? 'destructive'
                          : currentTask.priority === 'low'
                          ? 'secondary'
                          : 'default'
                      }
                    >
                      {t(`tasks.priority.${currentTask.priority}`)}
                    </Badge>
                    {currentTask.estimatedDuration && (
                      <span className="flex items-center gap-1 text-sm text-muted-foreground">
                        <Clock className="h-4 w-4" />
                        {currentTask.estimatedDuration} min
                      </span>
                    )}
                  </div>
                )}

                {/* Task title */}
                <h2 className="text-2xl md:text-3xl font-bold mb-4 text-center">
                  {currentTask?.title}
                </h2>

                {/* Task description */}
                {currentTask?.description && (
                  <p className="text-muted-foreground text-center mb-6">
                    {currentTask.description}
                  </p>
                )}

                {/* Action buttons */}
                <div className="flex flex-col gap-3">
                  <Button
                    size="lg"
                    onClick={handleComplete}
                    disabled={completeMutation.isPending}
                    className={`w-full ${settings.largerTargets ? 'h-14 text-lg' : 'h-12'}`}
                  >
                    <CheckCircle2 className="h-5 w-5 mr-2" />
                    {t('adhd.singleTask.markComplete')}
                  </Button>

                  <div className="flex gap-3">
                    <Button
                      variant="outline"
                      onClick={() => setShowFiveMin(true)}
                      className={`flex-1 ${settings.largerTargets ? 'h-12' : 'h-10'}`}
                    >
                      <Play className="h-4 w-4 mr-2" />
                      {t('adhd.singleTask.fiveMin')}
                    </Button>

                    {currentTask?.estimatedDuration && (
                      <Button
                        variant="outline"
                        onClick={() => setShowTimer(true)}
                        className={`flex-1 ${settings.largerTargets ? 'h-12' : 'h-10'}`}
                      >
                        <Focus className="h-4 w-4 mr-2" />
                        {t('adhd.singleTask.startTimer')}
                      </Button>
                    )}
                  </div>

                  <Button
                    variant="ghost"
                    onClick={handleSkip}
                    disabled={currentIndex >= totalTasks - 1}
                    className="text-muted-foreground"
                  >
                    <SkipForward className="h-4 w-4 mr-2" />
                    {t('adhd.singleTask.skip')}
                  </Button>
                </div>
              </div>
            </motion.div>
          </AnimatePresence>
        )}

        {/* Navigation dots */}
        <div className="flex items-center gap-4 mt-8">
          <Button
            variant="ghost"
            size="icon"
            onClick={handlePrev}
            disabled={currentIndex === 0}
          >
            <ChevronLeft className="h-5 w-5" />
          </Button>

          <div className="flex gap-1.5">
            {actionableTasks.slice(0, 7).map((_, index) => (
              <button
                key={index}
                onClick={() => setCurrentIndex(index)}
                className={`
                  w-2.5 h-2.5 rounded-full transition-all
                  ${index === currentIndex ? 'bg-primary w-6' : 'bg-muted hover:bg-muted-foreground/50'}
                `}
              />
            ))}
            {totalTasks > 7 && (
              <span className="text-xs text-muted-foreground ml-1">+{totalTasks - 7}</span>
            )}
          </div>

          <Button
            variant="ghost"
            size="icon"
            onClick={handleNext}
            disabled={currentIndex >= totalTasks - 1}
          >
            <ChevronRight className="h-5 w-5" />
          </Button>
        </div>

        {/* Exit button */}
        {onExit && (
          <Button
            variant="link"
            onClick={onExit}
            className="mt-6 text-muted-foreground"
          >
            {t('adhd.singleTask.exit')}
          </Button>
        )}
      </div>

      <EncouragementToast
        type={encouragement.type}
        visible={encouragement.visible}
        onDismiss={encouragement.hide}
        customMessage={encouragement.message}
        xpEarned={encouragement.xp}
      />
    </>
  );
}
