import React, { useMemo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { useSubtaskCompletion } from '@/hooks/useSubtaskCompletion';
import { format, isPast, parseISO, isValid, addDays } from 'date-fns';
import { Skeleton } from '@/components/ui/skeleton';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, AlertTriangle } from 'lucide-react';

export default function SubtaskList({ subtasks = [], parentTask, onRefresh, loading = false }) {
  const { markSubtaskComplete } = useSubtaskCompletion();

  const { visibleTasks, totalTasks } = useMemo(() => {
    if (!subtasks || subtasks.length === 0) return { visibleTasks: [], totalTasks: 0 };
    const sorted = [...subtasks].sort((a, b) => (a.task_sequence || 0) - (b.task_sequence || 0));
    const firstIncompleteIndex = sorted.findIndex(t => t.status !== 'completed');
    const filtered = firstIncompleteIndex === -1 ? sorted : sorted.slice(0, firstIncompleteIndex + 1);
    return { visibleTasks: filtered, totalTasks: sorted.length };
  }, [subtasks]);

  const calculateDueDate = (task) => {
    if (task.status === 'completed') return task.completed_at || task.due_date;
    if (!parentTask?.created_at) return task.due_date;
    try {
      const baseDate = parseISO(parentTask.created_at);
      if (!isValid(baseDate)) return task.due_date;
      return addDays(baseDate, task.days_until_due || 0).toISOString();
    } catch { return task.due_date; }
  };

  const handleCheck = async (taskId, checked) => {
    const success = await markSubtaskComplete(taskId, checked);
    if (success && onRefresh) onRefresh();
  };

  if (loading) {
    return (<div className="space-y-3 py-2">{[1, 2].map(i => <Skeleton key={i} className="h-12 w-full rounded-lg" />)}</div>);
  }
  if (totalTasks === 0) {
    return (<div className="text-center py-6 text-muted-foreground text-sm italic border border-dashed rounded-lg">No steps defined for this workflow.</div>);
  }

  return (
    <div className="space-y-4 relative">
      {visibleTasks.length > 1 && (<div className="absolute left-[26px] top-6 bottom-8 w-px bg-border z-0" />)}
      <AnimatePresence mode='popLayout'>
        {visibleTasks.map((task, index) => {
          const isComplete = task.status === 'completed';
          const isCurrent = !isComplete && index === visibleTasks.length - 1;
          const effectiveDueDateStr = calculateDueDate(task);
          const effectiveDueDate = effectiveDueDateStr ? parseISO(effectiveDueDateStr) : null;
          const isOverdue = !isComplete && effectiveDueDate && isPast(effectiveDueDate);
          const formattedDate = effectiveDueDate && isValid(effectiveDueDate) ? format(effectiveDueDate, 'MMM dd') : null;

          return (
            <motion.div key={task.id} layout initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}
              className={cn("group relative z-10 flex items-start gap-4 p-4 rounded-xl border transition-all duration-300",
                isCurrent ? "bg-card border-primary/30 shadow-sm ring-1 ring-primary/10" : "bg-muted/30 border-border opacity-90 hover:opacity-100",
                isComplete && "bg-muted/20"
              )}>
              <div className="mt-0.5 bg-background rounded-full p-0.5">
                <Checkbox checked={isComplete} onCheckedChange={(checked) => handleCheck(task.id, checked)}
                  className={cn("h-5 w-5 rounded-full border-2 transition-all data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500",
                    !isComplete && "border-muted-foreground/30 hover:border-primary")} />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-1">
                  <span className={cn("font-semibold text-sm transition-colors", isComplete ? "text-muted-foreground line-through" : "text-foreground")}>{task.title}</span>
                  <div className="flex items-center gap-2 shrink-0">
                    {isCurrent && (<Badge variant="secondary" className="text-[10px] px-2 py-0 h-5 bg-primary/10 text-primary border-0 font-medium">Current Step</Badge>)}
                    {!isComplete && task.priority === 'urgent' && (<Badge className="text-[10px] h-5 bg-destructive/10 text-destructive border-0">Urgent</Badge>)}
                  </div>
                </div>
                {task.description && (<p className={cn("text-xs leading-relaxed mb-2.5", isComplete ? "text-muted-foreground/60" : "text-muted-foreground")}>{task.description}</p>)}
                <div className="flex items-center gap-3">
                  {formattedDate && (
                    <div className={cn("flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded transition-colors",
                      isComplete ? "bg-muted text-muted-foreground" : isOverdue ? "bg-destructive/10 text-destructive border border-destructive/20" : "bg-primary/10 text-primary border border-primary/20")}>
                      {isOverdue && !isComplete ? <AlertTriangle className="w-3 h-3" /> : <Calendar className="w-3 h-3" />}
                      <span>{isComplete ? `Completed: ${formattedDate}` : `${isOverdue ? 'Overdue: ' : 'Due: '} ${formattedDate}`}</span>
                    </div>
                  )}
                </div>
              </div>
            </motion.div>
          );
        })}
      </AnimatePresence>
      {visibleTasks.length < totalTasks && (
        <div className="text-center pt-2">
          <span className="text-xs text-muted-foreground font-medium bg-muted px-3 py-1 rounded-full">{totalTasks - visibleTasks.length} more steps remaining</span>
        </div>
      )}
    </div>
  );
}
