import React, { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Loader2, Sparkles, Clock, CheckCircle2, AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import type { Task } from '@shared/schema';

interface SubtaskSuggestion {
  title: string;
  estimatedMinutes: number;
  order: number;
}

interface BreakdownResponse {
  subtasks: SubtaskSuggestion[];
  totalEstimatedMinutes: number;
  encouragement: string;
}

interface TaskBreakdownModalProps {
  task: Task;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function TaskBreakdownModal({ task, open, onOpenChange }: TaskBreakdownModalProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();
  const queryClient = useQueryClient();

  const [breakdown, setBreakdown] = useState<BreakdownResponse | null>(null);
  const [selectedSubtasks, setSelectedSubtasks] = useState<Set<number>>(new Set());

  // Mutation to get AI breakdown
  const breakdownMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch('/api/ai/breakdown-task', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          taskId: task.id,
          title: task.title,
          description: task.description,
          estimatedDuration: task.estimatedDuration,
        }),
      });
      if (!res.ok) throw new Error('Failed to break down task');
      return res.json() as Promise<BreakdownResponse>;
    },
    onSuccess: (data) => {
      setBreakdown(data);
      // Select all by default
      setSelectedSubtasks(new Set(data.subtasks.map((_, i) => i)));
    },
  });

  // Mutation to create subtasks
  const createSubtasksMutation = useMutation({
    mutationFn: async (subtasks: SubtaskSuggestion[]) => {
      const promises = subtasks.map((subtask, index) =>
        fetch('/api/tasks', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({
            title: subtask.title,
            parentTaskId: task.id,
            estimatedDuration: subtask.estimatedMinutes,
            priority: task.priority,
            status: 'todo',
          }),
        })
      );
      return Promise.all(promises);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/tasks'] });
      onOpenChange(false);
    },
  });

  const handleGenerate = () => {
    breakdownMutation.mutate();
  };

  const handleToggleSubtask = (index: number) => {
    const newSet = new Set(selectedSubtasks);
    if (newSet.has(index)) {
      newSet.delete(index);
    } else {
      newSet.add(index);
    }
    setSelectedSubtasks(newSet);
  };

  const handleCreate = () => {
    if (!breakdown) return;
    const selected = breakdown.subtasks.filter((_, i) => selectedSubtasks.has(i));
    createSubtasksMutation.mutate(selected);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            {t('adhd.taskBreakdown.title')}
          </DialogTitle>
          <DialogDescription>
            {t('adhd.taskBreakdown.description')}
          </DialogDescription>
        </DialogHeader>

        {/* Task info */}
        <div className="bg-muted/50 rounded-lg p-4 mb-4">
          <h4 className="font-medium mb-1 truncate">{task.title}</h4>
          {task.description && (
            <p className="text-sm text-muted-foreground">{task.description}</p>
          )}
          {task.estimatedDuration && (
            <div className="flex items-center gap-1 mt-2 text-sm text-muted-foreground">
              <Clock className="h-4 w-4" />
              <span>{task.estimatedDuration} min {t('adhd.taskBreakdown.estimated')}</span>
            </div>
          )}
        </div>

        {/* Generate button or results */}
        {!breakdown ? (
          <div className="flex flex-col items-center py-8">
            <p className="text-sm text-muted-foreground mb-4 text-center">
              {t('adhd.taskBreakdown.prompt')}
            </p>
            <Button
              onClick={handleGenerate}
              disabled={breakdownMutation.isPending}
              size="lg"
              className={settings.largerTargets ? 'h-14 px-8 text-lg' : ''}
            >
              {breakdownMutation.isPending ? (
                <>
                  <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                  {t('adhd.taskBreakdown.analyzing')}
                </>
              ) : (
                <>
                  <Sparkles className="h-5 w-5 mr-2" />
                  {t('adhd.taskBreakdown.breakItDown')}
                </>
              )}
            </Button>
          </div>
        ) : (
          <div className="space-y-4">
            {/* Encouragement */}
            {breakdown.encouragement && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-primary/10 text-primary rounded-lg p-3 text-sm"
              >
                {breakdown.encouragement}
              </motion.div>
            )}

            {/* Subtask list */}
            <div className="space-y-2 max-h-[300px] overflow-y-auto">
              <AnimatePresence>
                {breakdown.subtasks.map((subtask, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: index * 0.1 }}
                    className={`
                      flex items-start gap-3 p-3 rounded-lg border
                      ${selectedSubtasks.has(index) ? 'bg-primary/5 border-primary/30' : 'bg-muted/30 border-transparent'}
                      transition-colors duration-200
                    `}
                  >
                    <Checkbox
                      checked={selectedSubtasks.has(index)}
                      onCheckedChange={() => handleToggleSubtask(index)}
                      className="mt-0.5"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm truncate">{subtask.title}</p>
                      <div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
                        <Clock className="h-3 w-3" />
                        <span>~{subtask.estimatedMinutes} min</span>
                      </div>
                    </div>
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>

            {/* Total time */}
            <div className="flex items-center justify-between text-sm bg-muted/50 rounded-lg p-3">
              <span className="text-muted-foreground">{t('adhd.taskBreakdown.totalTime')}</span>
              <span className="font-medium">
                {breakdown.subtasks
                  .filter((_, i) => selectedSubtasks.has(i))
                  .reduce((sum, s) => sum + s.estimatedMinutes, 0)} min
              </span>
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-2">
              <Button
                variant="outline"
                onClick={handleGenerate}
                disabled={breakdownMutation.isPending}
                className="flex-1"
              >
                {t('adhd.taskBreakdown.regenerate')}
              </Button>
              <Button
                onClick={handleCreate}
                disabled={createSubtasksMutation.isPending || selectedSubtasks.size === 0}
                className="flex-1"
              >
                {createSubtasksMutation.isPending ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <CheckCircle2 className="h-4 w-4 mr-2" />
                )}
                {t('adhd.taskBreakdown.createSubtasks', { count: selectedSubtasks.size })}
              </Button>
            </div>
          </div>
        )}

        {/* Error state */}
        {breakdownMutation.isError && (
          <div className="flex items-center gap-2 text-destructive text-sm mt-2">
            <AlertCircle className="h-4 w-4" />
            <span>{t('adhd.taskBreakdown.error')}</span>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
