import React, { useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ChevronDown, ChevronUp, Trash2, CheckCircle2, PlayCircle } from 'lucide-react';
import { useWorkflowDeletion } from '@/hooks/useWorkflowDeletion';
import { useSubtaskCompletion } from '@/hooks/useSubtaskCompletion';
import SubtaskList from './SubtaskList';
import { cn } from '@/lib/utils';

export default function ParentTaskCard({ task, subtasks = [], onRefresh }) {
  const [isOpen, setIsOpen] = useState(false);
  const { deleteWorkflow, deleting } = useWorkflowDeletion();
  const { markAllSubtasksComplete, loading: completingAll } = useSubtaskCompletion();

  const total = subtasks.length;
  const completed = subtasks.filter(s => s.status === 'completed').length;
  const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
  const isAllDone = pct === 100;

  const handleDelete = async () => {
    if (window.confirm('Delete this workflow and all its subtasks?')) {
      await deleteWorkflow(task.id, onRefresh);
    }
  };

  const handleCompleteAll = async () => {
    const success = await markAllSubtasksComplete(task.id);
    if (success && onRefresh) onRefresh();
  };

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <Card className={cn("transition-shadow", isOpen && "shadow-md")}>
        <CardContent className="py-3 px-4">
          <CollapsibleTrigger className="flex items-center justify-between w-full text-left">
            <div className="flex items-center gap-3 min-w-0">
              {isAllDone ? <CheckCircle2 className="h-5 w-5 text-emerald-500 shrink-0" /> : <PlayCircle className="h-5 w-5 text-primary shrink-0" />}
              <div className="min-w-0">
                <p className={cn("font-medium truncate", isAllDone && "line-through text-muted-foreground")}>{task.title}</p>
                <p className="text-xs text-muted-foreground">
                  {task.associations?.name || task.workflow_template?.name || ''}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-3 shrink-0">
              <span className="text-sm text-muted-foreground">{completed}/{total}</span>
              <Progress value={pct} className="w-24 h-2" />
              <Badge variant={isAllDone ? "default" : "secondary"} className={cn(isAllDone && "bg-emerald-500")}>{pct}%</Badge>
              {isOpen ? <ChevronUp className="h-4 w-4 text-muted-foreground" /> : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
            </div>
          </CollapsibleTrigger>

          <CollapsibleContent className="mt-4 pt-4 border-t space-y-4">
            <SubtaskList subtasks={subtasks} parentTask={task} onRefresh={onRefresh} />
            <div className="flex justify-between items-center pt-2">
              {!isAllDone && (
                <Button variant="outline" size="sm" disabled={completingAll} onClick={handleCompleteAll}>
                  <CheckCircle2 className="h-3.5 w-3.5 mr-1" /> Complete All
                </Button>
              )}
              <Button variant="destructive" size="sm" disabled={deleting} onClick={handleDelete} className="ml-auto">
                <Trash2 className="h-3.5 w-3.5 mr-1" /> Delete Workflow
              </Button>
            </div>
          </CollapsibleContent>
        </CardContent>
      </Card>
    </Collapsible>
  );
}
