import React, { useState, useEffect } from 'react';
import { Plus, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { supabase } from '@/integrations/supabase/client';
import TaskCard from './TaskCard';
import TaskDialog from './TaskDialog';
import BulkTaskActionBar from './BulkTaskActionBar';
import { useStaffUsers } from '@/hooks/useStaffUsers';

export default function TaskListSection() {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState(null);
  
  const { users: staffUsers } = useStaffUsers();

  const [associations, setAssociations] = useState([]);
  const [selectedAssocId, setSelectedAssocId] = useState('all');
  const [statusFilter, setStatusFilter] = useState('active');

  // Bulk selection
  const [selectedIds, setSelectedIds] = useState(new Set());

  useEffect(() => {
    supabase.from('associations').select('id, name').eq('status', 'active').order('name').then(({ data }) => {
      setAssociations(data || []);
    });
  }, []);

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

      if (searchQuery) standaloneQuery = standaloneQuery.ilike('title', `%${searchQuery}%`);
      if (selectedAssocId && selectedAssocId !== 'all') standaloneQuery = standaloneQuery.eq('association_id', selectedAssocId);
      if (statusFilter === 'active') standaloneQuery = standaloneQuery.neq('status', 'completed');
      else if (statusFilter === 'completed') standaloneQuery = standaloneQuery.eq('status', 'completed');

      let subtaskQuery = supabase
        .from('tasks')
        .select('*, associations!tasks_association_id_fkey(name)')
        .not('parent_task_id', 'is', null)
        .order('task_sequence', { ascending: true });

      if (searchQuery) subtaskQuery = subtaskQuery.ilike('title', `%${searchQuery}%`);
      if (selectedAssocId && selectedAssocId !== 'all') subtaskQuery = subtaskQuery.eq('association_id', selectedAssocId);
      if (statusFilter === 'completed') subtaskQuery = subtaskQuery.eq('status', 'completed');
      else if (statusFilter === 'active') subtaskQuery = subtaskQuery.neq('status', 'completed');

      const [standaloneRes, subtaskRes] = await Promise.all([standaloneQuery, subtaskQuery]);
      if (standaloneRes.error) throw standaloneRes.error;
      if (subtaskRes.error) throw subtaskRes.error;

      const standaloneTasks = standaloneRes.data || [];
      const allSubtasks = subtaskRes.data || [];
      let visibleSubtasks;
      if (statusFilter === 'active') {
        const firstPendingByParent = {};
        for (const st of allSubtasks) {
          if (st.status !== 'completed' && !firstPendingByParent[st.parent_task_id]) {
            firstPendingByParent[st.parent_task_id] = st;
          }
        }
        visibleSubtasks = Object.values(firstPendingByParent);
      } else {
        visibleSubtasks = allSubtasks;
      }

      const combined = [...standaloneTasks, ...visibleSubtasks];
      combined.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());

      const enriched = combined.map(t => {
        const assignedUser = staffUsers.find(u => u.id === t.assigned_to);
        return { ...t, assigned_user_name: assignedUser?.name || null, is_workflow_task: !!t.parent_task_id };
      });
      setTasks(enriched);
    } catch (error) {
      console.error('Error fetching tasks:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTasks();
    const channel = supabase.channel('tasks_list_updates')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'tasks' }, () => {
        fetchTasks();
      })
      .subscribe();
    return () => { supabase.removeChannel(channel); };
  }, [searchQuery, selectedAssocId, statusFilter, staffUsers]);

  const handleTaskUpdate = () => { fetchTasks(); };

  const toggleSelect = (id) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const toggleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(new Set(tasks.map(t => t.id)));
    } else {
      setSelectedIds(new Set());
    }
  };

  const allSelected = tasks.length > 0 && selectedIds.size === tasks.length;
  const someSelected = selectedIds.size > 0 && selectedIds.size < tasks.length;

  return (
    <div className="space-y-4">
      <BulkTaskActionBar
        selectedIds={Array.from(selectedIds)}
        onClear={() => setSelectedIds(new Set())}
        onSuccess={handleTaskUpdate}
        users={staffUsers}
      />

      <div className="bg-card rounded-xl shadow-sm border p-4 flex flex-col md:flex-row items-center gap-4">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input placeholder="Search tasks..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9" />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full md:w-[150px]"><SelectValue placeholder="Status" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="all">All</SelectItem>
          </SelectContent>
        </Select>
        <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
          <SelectTrigger className="w-full md:w-[200px]"><SelectValue placeholder="Client" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Clients</SelectItem>
            {associations.map(a => (<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>))}
          </SelectContent>
        </Select>
        <Button onClick={() => { setSelectedTask(null); setDialogOpen(true); }} className="w-full md:w-auto shrink-0 gap-2">
          <Plus className="w-4 h-4" /> New Task
        </Button>
      </div>

      <div className="bg-card rounded-xl border shadow-sm overflow-hidden">
        {loading ? (
          <div className="p-12 flex justify-center"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div></div>
        ) : tasks.length === 0 ? (
          <div className="p-12 text-center text-muted-foreground">No tasks found.</div>
        ) : (
          <>
            <div className="px-4 py-2 border-b border-border bg-muted/30 flex items-center gap-3">
              <Checkbox
                checked={allSelected}
                ref={(el) => { if (el) el.dataset.indeterminate = someSelected; }}
                onCheckedChange={toggleSelectAll}
                className="data-[state=checked]:bg-primary"
              />
              <span className="text-xs text-muted-foreground">
                {selectedIds.size > 0 ? `${selectedIds.size} of ${tasks.length} selected` : 'Select all'}
              </span>
            </div>
            <div className="divide-y divide-border">
              {tasks.map((task) => (
                <div key={task.id} className="flex items-center">
                  <div className="pl-4 shrink-0">
                    <Checkbox
                      checked={selectedIds.has(task.id)}
                      onCheckedChange={() => toggleSelect(task.id)}
                      className="data-[state=checked]:bg-primary"
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <TaskCard task={task} canManage={true} onEdit={() => { setSelectedTask(task); setDialogOpen(true); }} onRefresh={handleTaskUpdate} />
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>

      <TaskDialog open={dialogOpen} onOpenChange={setDialogOpen} task={selectedTask} onSuccess={handleTaskUpdate} associations={associations} users={staffUsers} />
    </div>
  );
}
