import React, { useState, useEffect } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { supabase } from '@/integrations/supabase/client';
import ParentTaskCard from './ParentTaskCard';
import { Loader2 } from 'lucide-react';

export default function WorkflowProgressDashboard({ onRefresh }) {
  const [activeWorkflows, setActiveWorkflows] = useState([]);
  const [filter, setFilter] = useState('active');
  const [loading, setLoading] = useState(false);

  const fetchWorkflows = async () => {
    setLoading(true);
    try {
      let query = supabase
        .from('tasks')
        .select('*, associations!tasks_association_id_fkey(name), workflow_templates(name)')
        .is('parent_task_id', null)
        .not('template_id', 'is', null)
        .order('created_at', { ascending: false });

      if (filter === 'active') query = query.neq('status', 'completed');
      else if (filter === 'completed') query = query.eq('status', 'completed');

      const { data, error } = await query;
      if (error) throw error;

      if (data && data.length > 0) {
        const ids = data.map(w => w.id);
        const { data: subtasks } = await supabase.from('tasks').select('*').in('parent_task_id', ids).order('task_sequence');
        const subtaskMap = {};
        (subtasks || []).forEach(s => {
          if (!subtaskMap[s.parent_task_id]) subtaskMap[s.parent_task_id] = [];
          subtaskMap[s.parent_task_id].push(s);
        });
        setActiveWorkflows(data.map(w => ({ ...w, subtasks: subtaskMap[w.id] || [] })));
      } else {
        setActiveWorkflows([]);
      }
    } catch (err) {
      console.error("Error fetching workflows", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchWorkflows(); }, [filter]);

  const handleRefresh = () => { fetchWorkflows(); if (onRefresh) onRefresh(); };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold text-foreground flex items-center gap-2">
          Active Workflows
          {activeWorkflows.length > 0 && (
            <span className="bg-primary text-primary-foreground rounded-full px-2 py-0.5 text-xs font-bold">{activeWorkflows.length}</span>
          )}
        </h3>
        <Select value={filter} onValueChange={setFilter}>
          <SelectTrigger className="w-[180px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Workflows</SelectItem>
            <SelectItem value="active">Active / In Progress</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-4 min-h-[200px]">
        {loading ? (
          <div className="flex justify-center py-10"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>
        ) : activeWorkflows.length > 0 ? (
          activeWorkflows.map(workflow => (
            <ParentTaskCard key={workflow.id} task={workflow} subtasks={workflow.subtasks} onRefresh={handleRefresh} />
          ))
        ) : (
          <div className="text-center py-12 border border-dashed rounded-lg bg-muted/50 text-muted-foreground">
            <p className="text-sm">No workflows found.</p>
          </div>
        )}
      </div>
    </div>
  );
}
