import React, { useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { Zap, Clock, Star, CheckCircle2, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import { useEncouragement, EncouragementToast } from '../feedback/EncouragementToast';
import type { Task } from '@shared/schema';
import confetti from 'canvas-confetti';

interface QuickWinListProps {
  maxItems?: number;
  compact?: boolean;
}

function calculateQuickWinScore(task: Task, threshold: number): number {
  let score = 100;

  // Shorter tasks = higher score
  if (task.estimatedDuration) {
    score += Math.max(0, (threshold - task.estimatedDuration) * 10);
  } else {
    // No estimate - assume quick
    score += 30;
  }

  // Lower priority = quicker to complete (less mental load)
  if (task.priority === 'low') score += 20;
  if (task.priority === 'medium') score += 10;

  // Today's due date = bonus
  if (task.dueDate) {
    const today = new Date();
    const dueDate = new Date(task.dueDate);
    if (
      dueDate.getDate() === today.getDate() &&
      dueDate.getMonth() === today.getMonth() &&
      dueDate.getFullYear() === today.getFullYear()
    ) {
      score += 30;
    }
  }

  // Already in progress = bonus
  if (task.status === 'inProgress') score += 40;

  // Low energy level tasks are good quick wins
  if (task.energyLevel === 'low') score += 25;

  return score;
}

export function QuickWinList({ maxItems = 5, compact = false }: QuickWinListProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();
  const queryClient = useQueryClient();
  const encouragement = useEncouragement();

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

  const quickWins = useMemo(() => {
    const threshold = settings.quickWinThreshold || 10;

    return tasks
      .filter((task) => {
        // Only pending or in-progress tasks
        if (task.status === 'done') return false;
        // Only tasks without subtasks (leaf tasks)
        if (tasks.some((t) => t.parentTaskId === task.id)) return false;
        // Filter by duration threshold
        if (task.estimatedDuration && task.estimatedDuration > threshold * 1.5) return false;
        return true;
      })
      .map((task) => ({
        ...task,
        quickWinScore: calculateQuickWinScore(task, threshold),
      }))
      .sort((a, b) => b.quickWinScore - a.quickWinScore)
      .slice(0, maxItems);
  }, [tasks, maxItems, settings.quickWinThreshold]);

  // Mutation to complete task
  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'] });

      // Celebrate!
      confetti({
        particleCount: 50,
        spread: 60,
        origin: { y: 0.8 },
        colors: ['#10b981', '#3b82f6', '#8b5cf6'],
      });

      encouragement.show('quickWin', undefined, 30);
    },
  });

  const handleComplete = (taskId: string) => {
    completeMutation.mutate(taskId);
  };

  if (quickWins.length === 0) {
    return (
      <Card className={compact ? 'border-0 shadow-none' : ''}>
        <CardContent className="flex flex-col items-center justify-center py-8 text-center">
          <Sparkles className="h-12 w-12 text-muted-foreground/50 mb-4" />
          <p className="text-muted-foreground">
            {t('adhd.quickWins.noTasks')}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card className={compact ? 'border-0 shadow-none' : ''}>
        {!compact && (
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-lg">
              <Zap className="h-5 w-5 text-yellow-500" />
              {t('adhd.quickWins.title')}
            </CardTitle>
            <CardDescription>
              {t('adhd.quickWins.description')}
            </CardDescription>
          </CardHeader>
        )}
        <CardContent className={compact ? 'p-0' : ''}>
          <div className="space-y-2">
            <AnimatePresence mode="popLayout">
              {quickWins.map((task, index) => (
                <motion.div
                  key={task.id}
                  layout
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={{ opacity: 0, x: 20, height: 0 }}
                  transition={{ delay: index * 0.05 }}
                  className={`
                    flex items-center gap-3 p-3 rounded-lg
                    bg-gradient-to-r from-yellow-500/5 to-orange-500/5
                    border border-yellow-500/20
                    hover:border-yellow-500/40 transition-colors
                    ${settings.largerTargets ? 'min-h-[72px]' : ''}
                  `}
                >
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleComplete(task.id)}
                    disabled={completeMutation.isPending}
                    className={`
                      shrink-0 rounded-full
                      hover:bg-green-500/20 hover:text-green-500
                      ${settings.largerTargets ? 'h-12 w-12' : 'h-9 w-9'}
                    `}
                  >
                    <CheckCircle2 className={settings.largerTargets ? 'h-6 w-6' : 'h-5 w-5'} />
                  </Button>

                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-sm truncate">{task.title}</p>
                    <div className="flex items-center gap-2 mt-1">
                      {task.estimatedDuration && (
                        <span className="flex items-center gap-1 text-xs text-muted-foreground">
                          <Clock className="h-3 w-3" />
                          {task.estimatedDuration} min
                        </span>
                      )}
                      <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                        +30 XP
                      </Badge>
                    </div>
                  </div>

                  <div className="shrink-0">
                    <Star className="h-4 w-4 text-yellow-500 fill-yellow-500" />
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        </CardContent>
      </Card>

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