'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ProtectedLayout } from '@/components/protected-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/components/ui/use-toast';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { 
  Plus, Calendar, CheckCircle, Clock, AlertCircle, User, FileText, Trash2, Edit,
  Users, Briefcase, Search, RefreshCw, ArrowRight, Phone, DollarSign, UserPlus,
  Filter, MoreHorizontal, Eye, ChevronDown
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { format, isToday, isTomorrow, isPast, isThisWeek } from 'date-fns';

interface Task {
  id: string;
  title: string;
  description: string | null;
  dueDate: string;
  reminderDate: string | null;
  priority: 'LOW' | 'MEDIUM' | 'HIGH';
  status: 'PENDING' | 'COMPLETED' | 'CANCELLED';
  completedAt: string | null;
  assignee: { id: string; name: string; email: string };
  createdBy: { id: string; name: string };
  collectionFile: { id: string; customerName: string; phoneNumber: string } | null;
  createdAt: string;
}

interface User {
  id: string;
  name: string;
  email: string;
  role: string;
}

interface CollectionFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  totalToCollect: number;
  outstandingBalance: number;
  status: string;
  assignedAgentId: string | null;
  assignedAgent: { id: string; name: string; email: string } | null;
  batch: { id: string; name: string; clientName: string } | null;
  createdAt: string;
}

interface AgentWorkload {
  agent: User;
  totalFiles: number;
  totalOutstanding: number;
  newFiles: number;
  inProgressFiles: number;
  paidFiles: number;
  defaultedFiles: number;
  // Percentages
  newPercent: number;
  inProgressPercent: number;
  paidPercent: number;
  defaultedPercent: number;
  progressPercent: number; // Overall progress (paid / total)
}

export default function TasksPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const { toast } = useToast();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>('PENDING');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    assigneeId: '',
    dueDate: '',
    reminderDate: '',
    priority: 'MEDIUM'
  });

  // Agent Jobs state
  const [collectionFiles, setCollectionFiles] = useState<CollectionFile[]>([]);
  const [agentWorkloads, setAgentWorkloads] = useState<AgentWorkload[]>([]);
  const [loadingJobs, setLoadingJobs] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [assignToAgentId, setAssignToAgentId] = useState('');
  const [jobsFilter, setJobsFilter] = useState({ agentId: 'all', status: 'all', search: '' });
  const [activeTab, setActiveTab] = useState('');
  
  // Agent's own assigned jobs
  const [myAssignedFiles, setMyAssignedFiles] = useState<CollectionFile[]>([]);
  const [loadingMyJobs, setLoadingMyJobs] = useState(false);
  const [myJobsFilter, setMyJobsFilter] = useState({ status: 'all', search: '' });

  // Task details dialog state
  const [taskDetailsDialogOpen, setTaskDetailsDialogOpen] = useState(false);
  const [taskDetailsTitle, setTaskDetailsTitle] = useState('');
  const [taskDetailsData, setTaskDetailsData] = useState<Task[]>([]);
  const [taskDetailsSummary, setTaskDetailsSummary] = useState<{ count: number; byUser: { name: string; role: string; count: number }[] }>({ count: 0, byUser: [] });
  const [taskDetailsLoading, setTaskDetailsLoading] = useState(false);
  const [taskDetailsTab, setTaskDetailsTab] = useState('details');

  const canManageTasks = session?.user?.role === 'ADMIN' || session?.user?.role === 'MANAGER';
  const isAgent = session?.user?.role === 'AGENT';
  const isAdmin = session?.user?.role === 'ADMIN';
  const isManager = session?.user?.role === 'MANAGER';
  const canViewUserBreakdown = isAdmin || isManager;

  const fetchTasks = async () => {
    try {
      const url = filterStatus ? `/api/tasks?status=${filterStatus}` : '/api/tasks';
      const res = await fetch(url);
      if (res.ok) {
        const data = await res.json();
        setTasks(data);
      }
    } catch (error) {
      console.error('Error fetching tasks:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const res = await fetch('/api/users');
      if (res.ok) {
        const data = await res.json();
        setUsers(data.users || []);
      }
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };

  const fetchCollectionFiles = useCallback(async () => {
    if (!canManageTasks) return;
    setLoadingJobs(true);
    try {
      const res = await fetch('/api/collection-files/assign');
      if (res.ok) {
        const data = await res.json();
        setCollectionFiles(data.files || []);
      }
    } catch (error) {
      console.error('Error fetching collection files:', error);
    } finally {
      setLoadingJobs(false);
    }
  }, [canManageTasks]);

  // Fetch agent's own assigned jobs
  const fetchMyAssignedJobs = useCallback(async () => {
    if (!isAgent) return;
    setLoadingMyJobs(true);
    try {
      const res = await fetch('/api/collection-files?assignedToMe=true');
      if (res.ok) {
        const data = await res.json();
        setMyAssignedFiles(data.files || data || []);
      }
    } catch (error) {
      console.error('Error fetching my assigned jobs:', error);
    } finally {
      setLoadingMyJobs(false);
    }
  }, [isAgent]);

  const calculateAgentWorkloads = useCallback(() => {
    if (!Array.isArray(users) || !Array.isArray(collectionFiles)) return;
    const agents = users.filter(u => u.role === 'AGENT');
    const workloads: AgentWorkload[] = agents.map(agent => {
      const agentFiles = collectionFiles.filter(f => f.assignedAgentId === agent.id);
      const totalFiles = agentFiles.length;
      const newFiles = agentFiles.filter(f => f.status === 'NEW').length;
      const inProgressFiles = agentFiles.filter(f => f.status === 'IN_PROGRESS').length;
      const paidFiles = agentFiles.filter(f => f.status === 'PAID').length;
      const defaultedFiles = agentFiles.filter(f => f.status === 'DEFAULTED').length;
      
      // Calculate percentages (avoid division by zero)
      const calcPercent = (count: number) => totalFiles > 0 ? Math.round((count / totalFiles) * 100) : 0;
      
      return {
        agent,
        totalFiles,
        totalOutstanding: agentFiles.reduce((sum, f) => sum + f.outstandingBalance, 0),
        newFiles,
        inProgressFiles,
        paidFiles,
        defaultedFiles,
        newPercent: calcPercent(newFiles),
        inProgressPercent: calcPercent(inProgressFiles),
        paidPercent: calcPercent(paidFiles),
        defaultedPercent: calcPercent(defaultedFiles),
        progressPercent: calcPercent(paidFiles), // Progress = paid files
      };
    });
    setAgentWorkloads(workloads);
  }, [users, collectionFiles]);

  // Set initial active tab based on role
  useEffect(() => {
    if (session?.user?.role && !activeTab) {
      setActiveTab(isAgent ? 'my-jobs' : 'pending');
    }
  }, [session?.user?.role, isAgent, activeTab]);

  useEffect(() => {
    fetchTasks();
    if (canManageTasks) {
      fetchUsers();
      fetchCollectionFiles();
    }
    if (isAgent) {
      fetchMyAssignedJobs();
    }
  }, [filterStatus, canManageTasks, isAgent, fetchCollectionFiles, fetchMyAssignedJobs]);

  useEffect(() => {
    if (users.length > 0 && collectionFiles.length > 0) {
      calculateAgentWorkloads();
    }
  }, [users, collectionFiles, calculateAgentWorkloads]);

  const handleCreate = async () => {
    try {
      const res = await fetch('/api/tasks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (res.ok) {
        toast({ title: 'Success', description: 'Task created successfully' });
        setShowCreateDialog(false);
        resetForm();
        fetchTasks();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to create task', variant: 'destructive' });
    }
  };

  const handleEdit = (task: Task) => {
    setEditingTask(task);
    setFormData({
      title: task.title,
      description: task.description || '',
      assigneeId: task.assignee.id,
      dueDate: format(new Date(task.dueDate), 'yyyy-MM-dd'),
      reminderDate: task.reminderDate ? format(new Date(task.reminderDate), 'yyyy-MM-dd') : '',
      priority: task.priority
    });
    setShowEditDialog(true);
  };

  const handleUpdate = async () => {
    if (!editingTask) return;
    try {
      const res = await fetch(`/api/tasks/${editingTask.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (res.ok) {
        toast({ title: 'Success', description: 'Task updated successfully' });
        setShowEditDialog(false);
        setEditingTask(null);
        resetForm();
        fetchTasks();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to update task', variant: 'destructive' });
    }
  };

  const handleStatusChange = async (taskId: string, newStatus: string) => {
    try {
      const res = await fetch(`/api/tasks/${taskId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      });

      if (res.ok) {
        toast({ title: 'Success', description: `Task marked as ${newStatus.toLowerCase()}` });
        fetchTasks();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to update task status', variant: 'destructive' });
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this task?')) return;
    try {
      const res = await fetch(`/api/tasks/${id}`, { method: 'DELETE' });
      if (res.ok) {
        toast({ title: 'Success', description: 'Task deleted successfully' });
        fetchTasks();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to delete task', variant: 'destructive' });
    }
  };

  const resetForm = () => {
    setFormData({
      title: '',
      description: '',
      assigneeId: '',
      dueDate: '',
      reminderDate: '',
      priority: 'MEDIUM'
    });
  };

  // Agent Jobs functions
  const handleSelectFile = (fileId: string) => {
    setSelectedFiles(prev => 
      prev.includes(fileId) 
        ? prev.filter(id => id !== fileId) 
        : [...prev, fileId]
    );
  };

  const handleSelectAll = (files: CollectionFile[]) => {
    const fileIds = files.map(f => f.id);
    const allSelected = fileIds.every(id => selectedFiles.includes(id));
    if (allSelected) {
      setSelectedFiles(prev => prev.filter(id => !fileIds.includes(id)));
    } else {
      setSelectedFiles(prev => [...new Set([...prev, ...fileIds])]);
    }
  };

  const handleAssignFiles = async () => {
    if (!assignToAgentId || selectedFiles.length === 0) {
      toast({ title: 'Error', description: 'Please select files and an agent', variant: 'destructive' });
      return;
    }

    try {
      const res = await fetch('/api/collection-files/assign', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fileIds: selectedFiles, agentId: assignToAgentId })
      });

      if (res.ok) {
        const data = await res.json();
        toast({ title: 'Success', description: data.message });
        setShowAssignDialog(false);
        setSelectedFiles([]);
        setAssignToAgentId('');
        fetchCollectionFiles();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to assign files', variant: 'destructive' });
    }
  };

  const handleReassignFile = async (fileId: string, agentId: string) => {
    try {
      const res = await fetch('/api/collection-files/assign', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fileIds: [fileId], agentId })
      });

      if (res.ok) {
        toast({ title: 'Success', description: 'File reassigned successfully' });
        fetchCollectionFiles();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to reassign file', variant: 'destructive' });
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-KE', { style: 'currency', currency: 'KES', minimumFractionDigits: 0 }).format(amount);
  };

  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'ADMIN': return 'bg-red-100 text-red-700 border-red-200';
      case 'MANAGER': return 'bg-purple-100 text-purple-700 border-purple-200';
      case 'AGENT': return 'bg-blue-100 text-blue-700 border-blue-200';
      default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const openTaskDetailsDialog = (filter: string, title: string) => {
    setTaskDetailsTitle(title);
    setTaskDetailsTab('details');
    setTaskDetailsDialogOpen(true);
    calculateTaskDetailsSummary(filter);
  };

  const calculateTaskDetailsSummary = (filter: string) => {
    setTaskDetailsLoading(true);
    
    let filteredData: Task[] = [];
    if (filter === 'overdue') {
      filteredData = tasks.filter(t => t.status === 'PENDING' && isPast(new Date(t.dueDate)) && !isToday(new Date(t.dueDate)));
    } else if (filter === 'today') {
      filteredData = tasks.filter(t => t.status === 'PENDING' && isToday(new Date(t.dueDate)));
    } else if (filter === 'upcoming') {
      filteredData = tasks.filter(t => t.status === 'PENDING' && !isPast(new Date(t.dueDate)) && !isToday(new Date(t.dueDate)));
    } else if (filter === 'completed') {
      filteredData = tasks.filter(t => t.status === 'COMPLETED');
    }

    // Calculate user breakdown
    const byUserMap = filteredData.reduce((acc, task) => {
      const userName = task.assignee?.name || 'Unassigned';
      const userRole = 'AGENT'; // Default role for display
      const key = userName;
      if (!acc[key]) {
        acc[key] = { name: userName, role: userRole, count: 0 };
      }
      acc[key].count += 1;
      return acc;
    }, {} as Record<string, { name: string; role: string; count: number }>);

    setTaskDetailsData(filteredData);
    setTaskDetailsSummary({
      count: filteredData.length,
      byUser: Object.values(byUserMap)
    });
    setTaskDetailsLoading(false);
  };

  const getStatusBadge = (status: string) => {
    const statusStyles: Record<string, string> = {
      NEW: 'bg-blue-100 text-blue-700 border-blue-300',
      IN_PROGRESS: 'bg-amber-100 text-amber-700 border-amber-300',
      PAID: 'bg-green-100 text-green-700 border-green-300',
      DEFAULTED: 'bg-red-100 text-red-700 border-red-300'
    };
    return (
      <Badge className={`${statusStyles[status] || 'bg-gray-100 text-gray-700'} border`}>
        {status.replace('_', ' ')}
      </Badge>
    );
  };

  const getStatusBorderColor = (status: string) => {
    const borderColors: Record<string, string> = {
      NEW: 'border-l-blue-500',
      IN_PROGRESS: 'border-l-amber-500',
      PAID: 'border-l-green-500',
      DEFAULTED: 'border-l-red-500'
    };
    return borderColors[status] || 'border-l-gray-400';
  };

  const getStatusCardBg = (status: string) => {
    const bgColors: Record<string, string> = {
      NEW: 'bg-blue-50/50',
      IN_PROGRESS: 'bg-amber-50/50',
      PAID: 'bg-green-50/50',
      DEFAULTED: 'bg-red-50/50'
    };
    return bgColors[status] || '';
  };

  // Filter collection files
  const filteredFiles = collectionFiles.filter(file => {
    if (jobsFilter.agentId !== 'all') {
      if (jobsFilter.agentId === 'unassigned') {
        if (file.assignedAgentId !== null) return false;
      } else {
        if (file.assignedAgentId !== jobsFilter.agentId) return false;
      }
    }
    if (jobsFilter.status !== 'all' && file.status !== jobsFilter.status) return false;
    if (jobsFilter.search) {
      const search = jobsFilter.search.toLowerCase();
      if (!file.customerName.toLowerCase().includes(search) && 
          !file.phoneNumber.includes(search)) return false;
    }
    return true;
  });

  const unassignedFiles = collectionFiles.filter(f => !f.assignedAgentId);

  // Filter agent's assigned files
  const filteredMyFiles = myAssignedFiles.filter(file => {
    if (myJobsFilter.status !== 'all' && file.status !== myJobsFilter.status) return false;
    if (myJobsFilter.search) {
      const search = myJobsFilter.search.toLowerCase();
      if (!file.customerName.toLowerCase().includes(search) && 
          !file.phoneNumber.includes(search)) return false;
    }
    return true;
  });

  // Calculate agent's own stats
  const myJobsStats = {
    total: myAssignedFiles.length,
    new: myAssignedFiles.filter(f => f.status === 'NEW').length,
    inProgress: myAssignedFiles.filter(f => f.status === 'IN_PROGRESS').length,
    paid: myAssignedFiles.filter(f => f.status === 'PAID').length,
    defaulted: myAssignedFiles.filter(f => f.status === 'DEFAULTED').length,
    totalOutstanding: myAssignedFiles.reduce((sum, f) => sum + f.outstandingBalance, 0),
  };

  const getPriorityBadge = (priority: string) => {
    const variants: Record<string, 'default' | 'secondary' | 'destructive'> = {
      LOW: 'secondary',
      MEDIUM: 'default',
      HIGH: 'destructive'
    };
    return <Badge variant={variants[priority]}>{priority}</Badge>;
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'COMPLETED': return <CheckCircle className="h-5 w-5 text-green-500" />;
      case 'CANCELLED': return <AlertCircle className="h-5 w-5 text-gray-500" />;
      default: return <Clock className="h-5 w-5 text-orange-500" />;
    }
  };

  const getDueDateLabel = (date: string) => {
    const d = new Date(date);
    if (isPast(d) && !isToday(d)) return <span className="text-red-500 font-medium">Overdue</span>;
    if (isToday(d)) return <span className="text-orange-500 font-medium">Today</span>;
    if (isTomorrow(d)) return <span className="text-blue-500 font-medium">Tomorrow</span>;
    if (isThisWeek(d)) return <span className="text-green-500">This week</span>;
    return format(d, 'MMM d, yyyy');
  };

  // Group tasks
  const overdueTasks = tasks.filter(t => t.status === 'PENDING' && isPast(new Date(t.dueDate)) && !isToday(new Date(t.dueDate)));
  const todayTasks = tasks.filter(t => t.status === 'PENDING' && isToday(new Date(t.dueDate)));
  const upcomingTasks = tasks.filter(t => t.status === 'PENDING' && !isPast(new Date(t.dueDate)) && !isToday(new Date(t.dueDate)));
  const completedTasks = tasks.filter(t => t.status === 'COMPLETED');

  // Form content is now inlined in dialogs to prevent focus loss during typing

  const TaskCard = ({ task }: { task: Task }) => (
    <Card className="hover:shadow-md transition-shadow">
      <CardContent className="p-4">
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-start gap-3 flex-1">
            <button
              onClick={() => task.status === 'PENDING' 
                ? handleStatusChange(task.id, 'COMPLETED')
                : handleStatusChange(task.id, 'PENDING')}
              className="mt-1"
            >
              {getStatusIcon(task.status)}
            </button>
            <div className="flex-1">
              <div className="flex items-center gap-2 flex-wrap">
                <h4 className={`font-medium ${task.status === 'COMPLETED' ? 'line-through text-muted-foreground' : ''}`}>
                  {task.title}
                </h4>
                {getPriorityBadge(task.priority)}
              </div>
              {task.description && (
                <p className="text-sm text-muted-foreground mt-1 line-clamp-2">{task.description}</p>
              )}
              <div className="flex flex-wrap items-center gap-4 mt-2 text-xs text-muted-foreground">
                <span className="flex items-center gap-1">
                  <Calendar className="h-3 w-3" />
                  {getDueDateLabel(task.dueDate)}
                </span>
                <span className="flex items-center gap-1">
                  <User className="h-3 w-3" />
                  {task.assignee.name}
                </span>
                {task.collectionFile && (
                  <button
                    onClick={() => router.push(`/files/${task.collectionFile!.id}`)}
                    className="flex items-center gap-1 text-blue-600 hover:underline"
                  >
                    <FileText className="h-3 w-3" />
                    {task.collectionFile.customerName}
                  </button>
                )}
              </div>
            </div>
          </div>
          <div className="flex gap-1">
            <Button variant="ghost" size="sm" onClick={() => handleEdit(task)}>
              <Edit className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="sm" onClick={() => handleDelete(task.id)}>
              <Trash2 className="h-4 w-4 text-red-500" />
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold">Tasks & Reminders</h1>
            <p className="text-muted-foreground">Manage your collection tasks</p>
          </div>
          <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                New Task
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Create New Task</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="create-title">Task Title *</Label>
                  <Input
                    id="create-title"
                    value={formData.title}
                    onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                    placeholder="e.g., Follow up with customer"
                  />
                </div>
                <div>
                  <Label htmlFor="create-description">Description</Label>
                  <Textarea
                    id="create-description"
                    value={formData.description}
                    onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                    placeholder="Additional details about this task"
                  />
                </div>
                {canManageTasks && (
                  <div>
                    <Label htmlFor="create-assigneeId">Assign To</Label>
                    <Select
                      value={formData.assigneeId}
                      onValueChange={(value) => setFormData(prev => ({ ...prev, assigneeId: value }))}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select assignee" />
                      </SelectTrigger>
                      <SelectContent>
                        {users.map((user) => (
                          <SelectItem key={user.id} value={user.id}>
                            {user.name} ({user.role})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                )}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="create-dueDate">Due Date *</Label>
                    <Input
                      id="create-dueDate"
                      type="date"
                      value={formData.dueDate}
                      onChange={(e) => setFormData(prev => ({ ...prev, dueDate: e.target.value }))}
                    />
                  </div>
                  <div>
                    <Label htmlFor="create-reminderDate">Reminder Date</Label>
                    <Input
                      id="create-reminderDate"
                      type="date"
                      value={formData.reminderDate}
                      onChange={(e) => setFormData(prev => ({ ...prev, reminderDate: e.target.value }))}
                    />
                  </div>
                </div>
                <div>
                  <Label htmlFor="create-priority">Priority</Label>
                  <Select
                    value={formData.priority}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, priority: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="LOW">Low</SelectItem>
                      <SelectItem value="MEDIUM">Medium</SelectItem>
                      <SelectItem value="HIGH">High</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex justify-end gap-2 pt-4">
                  <Button variant="outline" onClick={() => {
                    setShowCreateDialog(false);
                    resetForm();
                  }}>
                    Cancel
                  </Button>
                  <Button onClick={handleCreate} disabled={!formData.title || !formData.dueDate}>
                    Create Task
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {/* Summary Cards - Clickable */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card 
            className={`cursor-pointer hover:shadow-lg transition-all ${overdueTasks.length > 0 ? 'border-red-200 bg-red-50 hover:border-red-400' : 'hover:border-gray-300'}`}
            onClick={() => openTaskDetailsDialog('overdue', 'Overdue Tasks')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className={`p-2 rounded-lg ${overdueTasks.length > 0 ? 'bg-red-100' : 'bg-gray-100'}`}>
                  <AlertCircle className={`h-6 w-6 ${overdueTasks.length > 0 ? 'text-red-600' : 'text-gray-600'}`} />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Overdue</p>
                  <p className="text-2xl font-bold">{overdueTasks.length}</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-orange-300"
            onClick={() => openTaskDetailsDialog('today', 'Due Today')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <Clock className="h-6 w-6 text-orange-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Due Today</p>
                  <p className="text-2xl font-bold">{todayTasks.length}</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-blue-300"
            onClick={() => openTaskDetailsDialog('upcoming', 'Upcoming Tasks')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <Calendar className="h-6 w-6 text-blue-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Upcoming</p>
                  <p className="text-2xl font-bold">{upcomingTasks.length}</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-green-300"
            onClick={() => openTaskDetailsDialog('completed', 'Completed Tasks')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-green-100 rounded-lg">
                  <CheckCircle className="h-6 w-6 text-green-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Completed</p>
                  <p className="text-2xl font-bold">{completedTasks.length}</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Tasks List */}
        <Tabs value={activeTab || (isAgent ? "my-jobs" : "pending")} onValueChange={(v) => {
          setActiveTab(v);
          if (v !== 'agent-jobs' && v !== 'my-jobs') {
            setFilterStatus(v === 'all' ? '' : v.toUpperCase());
          }
        }}>
          <TabsList>
            {isAgent && (
              <TabsTrigger value="my-jobs" className="gap-2">
                <Briefcase className="h-4 w-4" />
                My Jobs
              </TabsTrigger>
            )}
            <TabsTrigger value="pending">Pending</TabsTrigger>
            <TabsTrigger value="completed">Completed</TabsTrigger>
            <TabsTrigger value="all">All Tasks</TabsTrigger>
            {canManageTasks && (
              <TabsTrigger value="agent-jobs" className="gap-2">
                <Briefcase className="h-4 w-4" />
                Agent Jobs
              </TabsTrigger>
            )}
          </TabsList>

          <TabsContent value="pending" className="space-y-6 mt-4">
            {loading ? (
              <div className="text-center py-8">Loading tasks...</div>
            ) : (
              <>
                {overdueTasks.length > 0 && (
                  <div>
                    <h3 className="text-sm font-medium text-red-600 mb-3 flex items-center gap-2">
                      <AlertCircle className="h-4 w-4" /> Overdue ({overdueTasks.length})
                    </h3>
                    <div className="space-y-2">
                      {overdueTasks.map(task => <TaskCard key={task.id} task={task} />)}
                    </div>
                  </div>
                )}

                {todayTasks.length > 0 && (
                  <div>
                    <h3 className="text-sm font-medium text-orange-600 mb-3 flex items-center gap-2">
                      <Clock className="h-4 w-4" /> Due Today ({todayTasks.length})
                    </h3>
                    <div className="space-y-2">
                      {todayTasks.map(task => <TaskCard key={task.id} task={task} />)}
                    </div>
                  </div>
                )}

                {upcomingTasks.length > 0 && (
                  <div>
                    <h3 className="text-sm font-medium text-blue-600 mb-3 flex items-center gap-2">
                      <Calendar className="h-4 w-4" /> Upcoming ({upcomingTasks.length})
                    </h3>
                    <div className="space-y-2">
                      {upcomingTasks.map(task => <TaskCard key={task.id} task={task} />)}
                    </div>
                  </div>
                )}

                {tasks.filter(t => t.status === 'PENDING').length === 0 && (
                  <div className="text-center py-12 text-muted-foreground">
                    <CheckCircle className="h-12 w-12 mx-auto mb-4 opacity-50" />
                    <p>No pending tasks</p>
                  </div>
                )}
              </>
            )}
          </TabsContent>

          <TabsContent value="completed" className="mt-4">
            {completedTasks.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <CheckCircle className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No completed tasks</p>
              </div>
            ) : (
              <div className="space-y-2">
                {completedTasks.map(task => <TaskCard key={task.id} task={task} />)}
              </div>
            )}
          </TabsContent>

          <TabsContent value="all" className="mt-4">
            {tasks.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <CheckCircle className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No tasks found</p>
              </div>
            ) : (
              <div className="space-y-2">
                {tasks.map(task => <TaskCard key={task.id} task={task} />)}
              </div>
            )}
          </TabsContent>

          {/* My Jobs Tab - For Agents */}
          {isAgent && (
            <TabsContent value="my-jobs" className="mt-4 space-y-6">
              {/* Agent's Job Summary */}
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                <Card className="border-gray-200 bg-gray-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-gray-100 rounded-lg">
                        <Briefcase className="h-6 w-6 text-gray-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Total Assigned</p>
                        <p className="text-2xl font-bold text-gray-700">{myJobsStats.total}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card className="border-blue-200 bg-blue-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-blue-100 rounded-lg">
                        <AlertCircle className="h-6 w-6 text-blue-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">New Jobs</p>
                        <p className="text-2xl font-bold text-blue-700">{myJobsStats.new}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card className="border-amber-200 bg-amber-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-amber-100 rounded-lg">
                        <Clock className="h-6 w-6 text-amber-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">In Progress</p>
                        <p className="text-2xl font-bold text-amber-700">{myJobsStats.inProgress}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card className="border-green-200 bg-green-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-green-100 rounded-lg">
                        <CheckCircle className="h-6 w-6 text-green-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Paid</p>
                        <p className="text-2xl font-bold text-green-700">{myJobsStats.paid}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card className="border-red-200 bg-red-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-red-100 rounded-lg">
                        <AlertCircle className="h-6 w-6 text-red-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Defaulted</p>
                        <p className="text-2xl font-bold text-red-700">{myJobsStats.defaulted}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card className="border-purple-200 bg-purple-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-purple-100 rounded-lg">
                        <DollarSign className="h-6 w-6 text-purple-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Outstanding</p>
                        <p className="text-lg font-bold text-purple-700">{formatCurrency(myJobsStats.totalOutstanding)}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* My Progress Section */}
              {myJobsStats.total > 0 && (
                <Card className="border-2 border-dashed border-blue-200">
                  <CardHeader className="pb-2">
                    <CardTitle className="text-lg flex items-center gap-2">
                      <CheckCircle className="h-5 w-5 text-green-600" />
                      My Work Progress
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {/* Overall Progress */}
                      <div>
                        <div className="flex justify-between items-center mb-2">
                          <span className="text-sm font-medium">Overall Completion</span>
                          <span className="text-lg font-bold text-green-600">
                            {myJobsStats.total > 0 ? Math.round((myJobsStats.paid / myJobsStats.total) * 100) : 0}%
                          </span>
                        </div>
                        <div className="h-4 bg-gray-200 rounded-full overflow-hidden">
                          <div 
                            className="h-full bg-gradient-to-r from-green-400 to-green-600 transition-all duration-500" 
                            style={{ width: `${myJobsStats.total > 0 ? Math.round((myJobsStats.paid / myJobsStats.total) * 100) : 0}%` }}
                          />
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                          {myJobsStats.paid} of {myJobsStats.total} jobs completed
                        </p>
                      </div>
                      
                      {/* Work Flow Distribution */}
                      <div>
                        <p className="text-sm font-medium mb-2">Work Flow Distribution</p>
                        <div className="h-4 bg-gray-100 rounded-full overflow-hidden flex">
                          {myJobsStats.new > 0 && (
                            <div 
                              className="h-full bg-blue-500" 
                              style={{ width: `${Math.round((myJobsStats.new / myJobsStats.total) * 100)}%` }}
                            />
                          )}
                          {myJobsStats.inProgress > 0 && (
                            <div 
                              className="h-full bg-amber-500" 
                              style={{ width: `${Math.round((myJobsStats.inProgress / myJobsStats.total) * 100)}%` }}
                            />
                          )}
                          {myJobsStats.paid > 0 && (
                            <div 
                              className="h-full bg-green-500" 
                              style={{ width: `${Math.round((myJobsStats.paid / myJobsStats.total) * 100)}%` }}
                            />
                          )}
                          {myJobsStats.defaulted > 0 && (
                            <div 
                              className="h-full bg-red-500" 
                              style={{ width: `${Math.round((myJobsStats.defaulted / myJobsStats.total) * 100)}%` }}
                            />
                          )}
                        </div>
                        {/* Legend with percentages */}
                        <div className="flex flex-wrap gap-3 mt-2 text-xs">
                          <span className="flex items-center gap-1">
                            <span className="w-3 h-3 rounded-full bg-blue-500"></span>
                            New: {Math.round((myJobsStats.new / myJobsStats.total) * 100)}%
                          </span>
                          <span className="flex items-center gap-1">
                            <span className="w-3 h-3 rounded-full bg-amber-500"></span>
                            In Progress: {Math.round((myJobsStats.inProgress / myJobsStats.total) * 100)}%
                          </span>
                          <span className="flex items-center gap-1">
                            <span className="w-3 h-3 rounded-full bg-green-500"></span>
                            Paid: {Math.round((myJobsStats.paid / myJobsStats.total) * 100)}%
                          </span>
                          {myJobsStats.defaulted > 0 && (
                            <span className="flex items-center gap-1">
                              <span className="w-3 h-3 rounded-full bg-red-500"></span>
                              Defaulted: {Math.round((myJobsStats.defaulted / myJobsStats.total) * 100)}%
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* My Jobs Table */}
              <Card>
                <CardHeader>
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <Briefcase className="h-5 w-5" />
                        My Assigned Jobs
                      </CardTitle>
                      <CardDescription>Click on a customer to work on their collection file</CardDescription>
                    </div>
                    <Button variant="outline" size="sm" onClick={() => fetchMyAssignedJobs()}>
                      <RefreshCw className="h-4 w-4 mr-2" />
                      Refresh
                    </Button>
                  </div>
                  {/* Filters */}
                  <div className="flex flex-wrap items-center gap-3 pt-4">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="Search customer..."
                        value={myJobsFilter.search}
                        onChange={(e) => setMyJobsFilter({ ...myJobsFilter, search: e.target.value })}
                        className="pl-9 w-[200px]"
                      />
                    </div>
                    <Select
                      value={myJobsFilter.status}
                      onValueChange={(value) => setMyJobsFilter({ ...myJobsFilter, status: value })}
                    >
                      <SelectTrigger className="w-[150px]">
                        <SelectValue placeholder="Filter by Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">All Status</SelectItem>
                        <SelectItem value="NEW">New</SelectItem>
                        <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                        <SelectItem value="PAID">Paid</SelectItem>
                        <SelectItem value="DEFAULTED">Defaulted</SelectItem>
                      </SelectContent>
                    </Select>
                    {(myJobsFilter.status !== 'all' || myJobsFilter.search) && (
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => setMyJobsFilter({ status: 'all', search: '' })}
                      >
                        Clear Filters
                      </Button>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  {loadingMyJobs ? (
                    <div className="text-center py-8">Loading your assigned jobs...</div>
                  ) : filteredMyFiles.length === 0 ? (
                    <div className="text-center py-12 text-muted-foreground">
                      <Briefcase className="h-12 w-12 mx-auto mb-4 opacity-50" />
                      <p>{myAssignedFiles.length === 0 ? 'No jobs assigned to you yet' : 'No files found matching your filters'}</p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {filteredMyFiles.map(file => (
                        <Card 
                          key={file.id} 
                          className={`hover:shadow-md transition-shadow cursor-pointer border-l-4 ${getStatusBorderColor(file.status)} ${getStatusCardBg(file.status)}`}
                          onClick={() => router.push(`/files/${file.id}`)}
                        >
                          <CardContent className="p-4">
                            <div className="flex items-center justify-between">
                              <div className="flex-1">
                                <div className="flex items-center gap-3 mb-2">
                                  <h4 className="font-semibold text-lg">{file.customerName}</h4>
                                  {getStatusBadge(file.status)}
                                  {file.status === 'DEFAULTED' && (
                                    <Badge className="bg-red-500 text-white animate-pulse">
                                      <AlertCircle className="h-3 w-3 mr-1" />
                                      URGENT
                                    </Badge>
                                  )}
                                </div>
                                <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
                                  <span className="flex items-center gap-1">
                                    <Phone className="h-4 w-4" />
                                    {file.phoneNumber}
                                  </span>
                                  <span className="flex items-center gap-1">
                                    <DollarSign className="h-4 w-4" />
                                    Outstanding: <span className={`font-medium ${file.status === 'DEFAULTED' ? 'text-red-600' : file.status === 'PAID' ? 'text-green-600' : 'text-foreground'}`}>{formatCurrency(file.outstandingBalance)}</span>
                                  </span>
                                  {file.batch && (
                                    <span className="flex items-center gap-1">
                                      <FileText className="h-4 w-4" />
                                      {file.batch.clientName}
                                    </span>
                                  )}
                                </div>
                              </div>
                              <Button 
                                variant="outline" 
                                size="sm" 
                                className={`gap-2 ${file.status === 'DEFAULTED' ? 'border-red-300 text-red-600 hover:bg-red-50' : file.status === 'NEW' ? 'border-blue-300 text-blue-600 hover:bg-blue-50' : ''}`}
                              >
                                <ArrowRight className="h-4 w-4" />
                                Work on Job
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>
          )}

          {/* Agent Jobs Tab */}
          {canManageTasks && (
            <TabsContent value="agent-jobs" className="mt-4 space-y-6">
              {/* Agent Workload Summary */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <Card className="border-orange-200 bg-orange-50">
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-orange-100 rounded-lg">
                        <FileText className="h-6 w-6 text-orange-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Unassigned Jobs</p>
                        <p className="text-2xl font-bold text-orange-700">{unassignedFiles.length}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-blue-100 rounded-lg">
                        <Users className="h-6 w-6 text-blue-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Active Agents</p>
                        <p className="text-2xl font-bold">{agentWorkloads.filter(w => w.totalFiles > 0).length}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-green-100 rounded-lg">
                        <Briefcase className="h-6 w-6 text-green-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Total Assigned</p>
                        <p className="text-2xl font-bold">{collectionFiles.filter(f => f.assignedAgentId).length}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                <Card>
                  <CardContent className="pt-6">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-purple-100 rounded-lg">
                        <DollarSign className="h-6 w-6 text-purple-600" />
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">Total Outstanding</p>
                        <p className="text-2xl font-bold">{formatCurrency(collectionFiles.reduce((sum, f) => sum + f.outstandingBalance, 0))}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Agent Workload Cards */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Users className="h-5 w-5" />
                    Agent Workload Distribution
                  </CardTitle>
                  <CardDescription>Overview of jobs assigned to each agent</CardDescription>
                </CardHeader>
                <CardContent>
                  {loadingJobs ? (
                    <div className="text-center py-8">Loading...</div>
                  ) : agentWorkloads.length === 0 ? (
                    <p className="text-center text-muted-foreground py-8">No agents found</p>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {agentWorkloads.map(workload => (
                        <Card key={workload.agent.id} className="hover:shadow-md transition-shadow">
                          <CardContent className="pt-4">
                            <div className="flex items-center justify-between mb-3">
                              <div className="flex items-center gap-2">
                                <div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                                  <User className="h-5 w-5 text-blue-600" />
                                </div>
                                <div>
                                  <p className="font-medium">{workload.agent.name}</p>
                                  <p className="text-xs text-muted-foreground">{workload.agent.email}</p>
                                </div>
                              </div>
                              <Button 
                                variant="outline" 
                                size="sm"
                                onClick={() => setJobsFilter({ ...jobsFilter, agentId: workload.agent.id })}
                              >
                                <Eye className="h-4 w-4" />
                              </Button>
                            </div>
                            
                            {/* Progress Bar */}
                            <div className="mb-3">
                              <div className="flex justify-between items-center mb-1">
                                <span className="text-xs text-muted-foreground">Work Progress</span>
                                <span className="text-xs font-semibold text-green-600">{workload.progressPercent}% Complete</span>
                              </div>
                              <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                                <div 
                                  className="h-full bg-green-500 transition-all duration-300" 
                                  style={{ width: `${workload.progressPercent}%` }}
                                />
                              </div>
                            </div>
                            
                            {/* Status Flow Breakdown */}
                            <div className="mb-3">
                              <p className="text-xs text-muted-foreground mb-2">Work Flow Distribution</p>
                              <div className="h-3 bg-gray-100 rounded-full overflow-hidden flex">
                                {workload.newPercent > 0 && (
                                  <div 
                                    className="h-full bg-blue-500" 
                                    style={{ width: `${workload.newPercent}%` }}
                                    title={`New: ${workload.newPercent}%`}
                                  />
                                )}
                                {workload.inProgressPercent > 0 && (
                                  <div 
                                    className="h-full bg-amber-500" 
                                    style={{ width: `${workload.inProgressPercent}%` }}
                                    title={`In Progress: ${workload.inProgressPercent}%`}
                                  />
                                )}
                                {workload.paidPercent > 0 && (
                                  <div 
                                    className="h-full bg-green-500" 
                                    style={{ width: `${workload.paidPercent}%` }}
                                    title={`Paid: ${workload.paidPercent}%`}
                                  />
                                )}
                                {workload.defaultedPercent > 0 && (
                                  <div 
                                    className="h-full bg-red-500" 
                                    style={{ width: `${workload.defaultedPercent}%` }}
                                    title={`Defaulted: ${workload.defaultedPercent}%`}
                                  />
                                )}
                              </div>
                              {/* Legend */}
                              <div className="flex flex-wrap gap-2 mt-2 text-xs">
                                <span className="flex items-center gap-1">
                                  <span className="w-2 h-2 rounded-full bg-blue-500"></span>
                                  New {workload.newPercent}%
                                </span>
                                <span className="flex items-center gap-1">
                                  <span className="w-2 h-2 rounded-full bg-amber-500"></span>
                                  Progress {workload.inProgressPercent}%
                                </span>
                                <span className="flex items-center gap-1">
                                  <span className="w-2 h-2 rounded-full bg-green-500"></span>
                                  Paid {workload.paidPercent}%
                                </span>
                                {workload.defaultedPercent > 0 && (
                                  <span className="flex items-center gap-1">
                                    <span className="w-2 h-2 rounded-full bg-red-500"></span>
                                    Default {workload.defaultedPercent}%
                                  </span>
                                )}
                              </div>
                            </div>
                            
                            <div className="grid grid-cols-2 gap-2 text-sm">
                              <div className="bg-gray-50 rounded p-2">
                                <p className="text-muted-foreground text-xs">Total Files</p>
                                <p className="font-semibold">{workload.totalFiles}</p>
                              </div>
                              <div className="bg-gray-50 rounded p-2">
                                <p className="text-muted-foreground text-xs">Outstanding</p>
                                <p className="font-semibold text-sm">{formatCurrency(workload.totalOutstanding)}</p>
                              </div>
                              <div className="bg-blue-50 rounded p-2">
                                <p className="text-muted-foreground text-xs">New</p>
                                <p className="font-semibold text-blue-600">{workload.newFiles}</p>
                              </div>
                              <div className="bg-amber-50 rounded p-2">
                                <p className="text-muted-foreground text-xs">In Progress</p>
                                <p className="font-semibold text-amber-600">{workload.inProgressFiles}</p>
                              </div>
                              <div className="bg-green-50 rounded p-2">
                                <p className="text-muted-foreground text-xs">Paid</p>
                                <p className="font-semibold text-green-600">{workload.paidFiles}</p>
                              </div>
                              {workload.defaultedFiles > 0 && (
                                <div className="bg-red-50 rounded p-2">
                                  <p className="text-muted-foreground text-xs">Defaulted</p>
                                  <p className="font-semibold text-red-600">{workload.defaultedFiles}</p>
                                </div>
                              )}
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Jobs Table with Filters */}
              <Card>
                <CardHeader>
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <Briefcase className="h-5 w-5" />
                        Collection Files (Jobs)
                      </CardTitle>
                      <CardDescription>Manage and assign collection files to agents</CardDescription>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                      {selectedFiles.length > 0 && (
                        <Button onClick={() => setShowAssignDialog(true)} className="gap-2">
                          <UserPlus className="h-4 w-4" />
                          Assign Selected ({selectedFiles.length})
                        </Button>
                      )}
                      <Button variant="outline" size="sm" onClick={() => fetchCollectionFiles()}>
                        <RefreshCw className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  {/* Filters */}
                  <div className="flex flex-wrap items-center gap-3 pt-4">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="Search customer..."
                        value={jobsFilter.search}
                        onChange={(e) => setJobsFilter({ ...jobsFilter, search: e.target.value })}
                        className="pl-9 w-[200px]"
                      />
                    </div>
                    <Select
                      value={jobsFilter.agentId}
                      onValueChange={(value) => setJobsFilter({ ...jobsFilter, agentId: value })}
                    >
                      <SelectTrigger className="w-[180px]">
                        <SelectValue placeholder="Filter by Agent" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">All Agents</SelectItem>
                        <SelectItem value="unassigned">Unassigned</SelectItem>
                        {(users || []).filter(u => u.role === 'AGENT').map(agent => (
                          <SelectItem key={agent.id} value={agent.id}>{agent.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <Select
                      value={jobsFilter.status}
                      onValueChange={(value) => setJobsFilter({ ...jobsFilter, status: value })}
                    >
                      <SelectTrigger className="w-[150px]">
                        <SelectValue placeholder="Filter by Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">All Status</SelectItem>
                        <SelectItem value="NEW">New</SelectItem>
                        <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                        <SelectItem value="PAID">Paid</SelectItem>
                        <SelectItem value="DEFAULTED">Defaulted</SelectItem>
                      </SelectContent>
                    </Select>
                    {(jobsFilter.agentId !== 'all' || jobsFilter.status !== 'all' || jobsFilter.search) && (
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => setJobsFilter({ agentId: 'all', status: 'all', search: '' })}
                      >
                        Clear Filters
                      </Button>
                    )}
                  </div>
                </CardHeader>
                <CardContent>
                  {loadingJobs ? (
                    <div className="text-center py-8">Loading files...</div>
                  ) : filteredFiles.length === 0 ? (
                    <div className="text-center py-12 text-muted-foreground">
                      <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                      <p>No files found matching your filters</p>
                    </div>
                  ) : (
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[50px]">
                              <Checkbox
                                checked={filteredFiles.length > 0 && filteredFiles.every(f => selectedFiles.includes(f.id))}
                                onCheckedChange={() => handleSelectAll(filteredFiles)}
                              />
                            </TableHead>
                            <TableHead>Customer</TableHead>
                            <TableHead>Phone</TableHead>
                            <TableHead>Outstanding</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead>Assigned To</TableHead>
                            <TableHead>Client/Batch</TableHead>
                            <TableHead className="text-right">Actions</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {filteredFiles.slice(0, 50).map(file => (
                            <TableRow key={file.id} className={selectedFiles.includes(file.id) ? 'bg-blue-50' : ''}>
                              <TableCell>
                                <Checkbox
                                  checked={selectedFiles.includes(file.id)}
                                  onCheckedChange={() => handleSelectFile(file.id)}
                                />
                              </TableCell>
                              <TableCell>
                                <button 
                                  onClick={() => router.push(`/files/${file.id}`)}
                                  className="font-medium text-blue-600 hover:underline"
                                >
                                  {file.customerName}
                                </button>
                              </TableCell>
                              <TableCell>
                                <span className="flex items-center gap-1 text-sm">
                                  <Phone className="h-3 w-3" />
                                  {file.phoneNumber}
                                </span>
                              </TableCell>
                              <TableCell className="font-medium">
                                {formatCurrency(file.outstandingBalance)}
                              </TableCell>
                              <TableCell>{getStatusBadge(file.status)}</TableCell>
                              <TableCell>
                                {file.assignedAgent ? (
                                  <span className="flex items-center gap-1">
                                    <User className="h-3 w-3" />
                                    {file.assignedAgent.name}
                                  </span>
                                ) : (
                                  <Badge variant="outline" className="text-orange-600 border-orange-300">Unassigned</Badge>
                                )}
                              </TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {file.batch?.clientName || '-'}
                              </TableCell>
                              <TableCell className="text-right">
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="sm">
                                      <MoreHorizontal className="h-4 w-4" />
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent align="end">
                                    <DropdownMenuItem onClick={() => router.push(`/files/${file.id}`)}>
                                      <Eye className="h-4 w-4 mr-2" /> View Details
                                    </DropdownMenuItem>
                                    {(users || []).filter(u => u.role === 'AGENT').map(agent => (
                                      <DropdownMenuItem 
                                        key={agent.id}
                                        onClick={() => handleReassignFile(file.id, agent.id)}
                                        disabled={file.assignedAgentId === agent.id}
                                      >
                                        <UserPlus className="h-4 w-4 mr-2" />
                                        Assign to {agent.name}
                                      </DropdownMenuItem>
                                    ))}
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                      {filteredFiles.length > 50 && (
                        <div className="p-3 text-center text-sm text-muted-foreground border-t">
                          Showing first 50 of {filteredFiles.length} files. Use filters to narrow results.
                        </div>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>
          )}
        </Tabs>

        {/* Assign Files Dialog */}
        <Dialog open={showAssignDialog} onOpenChange={setShowAssignDialog}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Assign Files to Agent</DialogTitle>
              <DialogDescription>
                Select an agent to assign the {selectedFiles.length} selected file(s) to.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div>
                <Label>Select Agent</Label>
                <Select value={assignToAgentId} onValueChange={setAssignToAgentId}>
                  <SelectTrigger>
                    <SelectValue placeholder="Choose an agent" />
                  </SelectTrigger>
                  <SelectContent>
                    {(users || []).filter(u => u.role === 'AGENT').map(agent => (
                      <SelectItem key={agent.id} value={agent.id}>
                        <div className="flex items-center gap-2">
                          <User className="h-4 w-4" />
                          {agent.name}
                          <span className="text-muted-foreground text-xs">
                            ({agentWorkloads.find(w => w.agent.id === agent.id)?.totalFiles || 0} files)
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="bg-gray-50 rounded-lg p-3">
                <p className="text-sm font-medium mb-2">Selected Files ({selectedFiles.length})</p>
                <div className="max-h-[150px] overflow-y-auto space-y-1">
                  {selectedFiles.map(fileId => {
                    const file = collectionFiles.find(f => f.id === fileId);
                    return file ? (
                      <div key={fileId} className="text-sm flex justify-between">
                        <span>{file.customerName}</span>
                        <span className="text-muted-foreground">{formatCurrency(file.outstandingBalance)}</span>
                      </div>
                    ) : null;
                  })}
                </div>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setShowAssignDialog(false)}>Cancel</Button>
              <Button onClick={handleAssignFiles} disabled={!assignToAgentId}>
                <UserPlus className="h-4 w-4 mr-2" />
                Assign Files
              </Button>
            </div>
          </DialogContent>
        </Dialog>

        {/* Edit Dialog */}
        <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Edit Task</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="edit-title">Task Title *</Label>
                <Input
                  id="edit-title"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  placeholder="e.g., Follow up with customer"
                />
              </div>
              <div>
                <Label htmlFor="edit-description">Description</Label>
                <Textarea
                  id="edit-description"
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="Additional details about this task"
                />
              </div>
              {canManageTasks && (
                <div>
                  <Label htmlFor="edit-assigneeId">Assign To</Label>
                  <Select
                    value={formData.assigneeId}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, assigneeId: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select assignee" />
                    </SelectTrigger>
                    <SelectContent>
                      {users.map((user) => (
                        <SelectItem key={user.id} value={user.id}>
                          {user.name} ({user.role})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="edit-dueDate">Due Date *</Label>
                  <Input
                    id="edit-dueDate"
                    type="date"
                    value={formData.dueDate}
                    onChange={(e) => setFormData(prev => ({ ...prev, dueDate: e.target.value }))}
                  />
                </div>
                <div>
                  <Label htmlFor="edit-reminderDate">Reminder Date</Label>
                  <Input
                    id="edit-reminderDate"
                    type="date"
                    value={formData.reminderDate}
                    onChange={(e) => setFormData(prev => ({ ...prev, reminderDate: e.target.value }))}
                  />
                </div>
              </div>
              <div>
                <Label htmlFor="edit-priority">Priority</Label>
                <Select
                  value={formData.priority}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, priority: value }))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="LOW">Low</SelectItem>
                    <SelectItem value="MEDIUM">Medium</SelectItem>
                    <SelectItem value="HIGH">High</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex justify-end gap-2 pt-4">
                <Button variant="outline" onClick={() => {
                  setShowEditDialog(false);
                  setEditingTask(null);
                  resetForm();
                }}>
                  Cancel
                </Button>
                <Button onClick={handleUpdate} disabled={!formData.title || !formData.dueDate}>
                  Save Changes
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* Task Details Dialog */}
        <Dialog open={taskDetailsDialogOpen} onOpenChange={setTaskDetailsDialogOpen}>
          <DialogContent className="max-w-4xl max-h-[80vh]">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Calendar className="h-5 w-5 text-blue-600" />
                {taskDetailsTitle}
              </DialogTitle>
              <DialogDescription>
                Detailed breakdown of tasks
              </DialogDescription>
            </DialogHeader>

            {taskDetailsLoading ? (
              <div className="flex justify-center items-center py-8">
                <RefreshCw className="h-8 w-8 animate-spin text-blue-600" />
              </div>
            ) : (
              <Tabs value={taskDetailsTab} onValueChange={setTaskDetailsTab}>
                <TabsList>
                  <TabsTrigger value="details">Tasks</TabsTrigger>
                  {canViewUserBreakdown && <TabsTrigger value="byUser">By Assignee</TabsTrigger>}
                </TabsList>

                <TabsContent value="details">
                  <div className="space-y-4">
                    {/* Summary */}
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <Card>
                        <CardContent className="pt-4">
                          <p className="text-sm text-muted-foreground">Total Tasks</p>
                          <p className="text-2xl font-bold">{taskDetailsSummary.count}</p>
                        </CardContent>
                      </Card>
                    </div>

                    {/* Data Table */}
                    <ScrollArea className="h-[400px] rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Task</TableHead>
                            <TableHead>Assignee</TableHead>
                            <TableHead>Priority</TableHead>
                            <TableHead>Due Date</TableHead>
                            <TableHead>Status</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {taskDetailsData.length === 0 ? (
                            <TableRow>
                              <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                                No tasks found
                              </TableCell>
                            </TableRow>
                          ) : (
                            taskDetailsData.map((task) => (
                              <TableRow key={task.id}>
                                <TableCell>
                                  <div>
                                    <p className="font-medium">{task.title}</p>
                                    {task.description && (
                                      <p className="text-xs text-muted-foreground line-clamp-1">{task.description}</p>
                                    )}
                                  </div>
                                </TableCell>
                                <TableCell>
                                  <div className="flex items-center gap-2">
                                    <User className="h-4 w-4 text-muted-foreground" />
                                    <span>{task.assignee?.name || 'Unassigned'}</span>
                                  </div>
                                </TableCell>
                                <TableCell>{getPriorityBadge(task.priority)}</TableCell>
                                <TableCell>{getDueDateLabel(task.dueDate)}</TableCell>
                                <TableCell>
                                  <Badge variant={task.status === 'COMPLETED' ? 'default' : 'outline'}>
                                    {task.status}
                                  </Badge>
                                </TableCell>
                              </TableRow>
                            ))
                          )}
                        </TableBody>
                      </Table>
                    </ScrollArea>
                  </div>
                </TabsContent>

                {canViewUserBreakdown && (
                  <TabsContent value="byUser">
                    <ScrollArea className="h-[400px]">
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-1">
                        {taskDetailsSummary.byUser.length === 0 ? (
                          <p className="col-span-3 text-center py-8 text-muted-foreground">No assignee data available</p>
                        ) : (
                          taskDetailsSummary.byUser.map((user, idx) => (
                            <Card key={idx}>
                              <CardContent className="pt-4">
                                <div className="flex items-center justify-between mb-2">
                                  <div className="flex items-center gap-2">
                                    <Users className="h-4 w-4 text-muted-foreground" />
                                    <span className="font-medium">{user.name}</span>
                                  </div>
                                  <Badge variant="outline" className={getRoleBadgeColor(user.role)}>
                                    {user.role}
                                  </Badge>
                                </div>
                                <div className="space-y-1 text-sm">
                                  <div className="flex justify-between">
                                    <span className="text-muted-foreground">Tasks:</span>
                                    <span className="font-medium">{user.count}</span>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))
                        )}
                      </div>
                    </ScrollArea>
                  </TabsContent>
                )}
              </Tabs>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}