'use client';

import { useState, useEffect } 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/components/ui/use-toast';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, FolderOpen, Calendar, Target, TrendingUp, Users, Trash2, Edit, Eye, DollarSign, RefreshCw, UserCircle } from 'lucide-react';
import { format } from 'date-fns';

interface Batch {
  id: string;
  name: string;
  description: string | null;
  clientName: string | null;
  targetAmount: number;
  startDate: string | null;
  endDate: string | null;
  isActive: boolean;
  fileCount: number;
  totalToCollect: number;
  totalCollected: number;
  totalOutstanding: number;
  paidCount: number;
  collectionRate: string;
  createdAt: string;
  assignedTo?: {
    id: string;
    name: string;
    email: string;
    role: string;
  } | null;
}

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

interface UserBreakdown {
  name: string;
  role: string;
  count: number;
  outstanding: number;
}

export default function BatchesPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const { toast } = useToast();
  const [batches, setBatches] = useState<Batch[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editingBatch, setEditingBatch] = useState<Batch | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    clientName: '',
    targetAmount: '',
    startDate: '',
    endDate: '',
    assignedToId: ''
  });

  // Details dialog state
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [detailsTitle, setDetailsTitle] = useState('');
  const [detailsData, setDetailsData] = useState<Batch[]>([]);
  const [detailsSummary, setDetailsSummary] = useState<{
    count: number;
    totalFiles: number;
    totalOutstanding: number;
    byAgent: UserBreakdown[];
  }>({
    count: 0,
    totalFiles: 0,
    totalOutstanding: 0,
    byAgent: []
  });
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [detailsTab, setDetailsTab] = useState('details');
  const [detailsFilter, setDetailsFilter] = useState<string>('all');

  const canManageBatches = session?.user?.role === 'ADMIN' || session?.user?.role === 'MANAGER';
  const isAdmin = session?.user?.role === 'ADMIN';
  const isManager = session?.user?.role === 'MANAGER';
  const canViewUserBreakdown = isAdmin || isManager;

  const fetchBatches = async () => {
    try {
      const res = await fetch('/api/batches');
      if (res.ok) {
        const data = await res.json();
        setBatches(data);
      }
    } catch (error) {
      console.error('Error fetching batches:', 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);
    }
  };

  useEffect(() => {
    fetchBatches();
    fetchUsers();
  }, []);

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

      if (res.ok) {
        toast({ title: 'Success', description: 'Batch created successfully' });
        setShowCreateDialog(false);
        setFormData({ name: '', description: '', clientName: '', targetAmount: '', startDate: '', endDate: '', assignedToId: '' });
        fetchBatches();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to create batch', variant: 'destructive' });
    }
  };

  const handleEdit = (batch: Batch) => {
    setEditingBatch(batch);
    setFormData({
      name: batch.name,
      description: batch.description || '',
      clientName: batch.clientName || '',
      targetAmount: batch.targetAmount.toString(),
      startDate: batch.startDate ? format(new Date(batch.startDate), 'yyyy-MM-dd') : '',
      endDate: batch.endDate ? format(new Date(batch.endDate), 'yyyy-MM-dd') : '',
      assignedToId: batch.assignedTo?.id || ''
    });
    setShowEditDialog(true);
  };

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

      if (res.ok) {
        toast({ title: 'Success', description: 'Batch updated successfully' });
        setShowEditDialog(false);
        setEditingBatch(null);
        setFormData({ name: '', description: '', clientName: '', targetAmount: '', startDate: '', endDate: '', assignedToId: '' });
        fetchBatches();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to update batch', variant: 'destructive' });
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this batch? Files will be unassigned but not deleted.')) return;
    try {
      const res = await fetch(`/api/batches/${id}`, { method: 'DELETE' });
      if (res.ok) {
        toast({ title: 'Success', description: 'Batch deleted successfully' });
        fetchBatches();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to delete batch', variant: 'destructive' });
    }
  };

  const openDetailsDialog = (filter: string, title: string) => {
    setDetailsFilter(filter);
    setDetailsTitle(title);
    setDetailsTab('details');
    setDetailsDialogOpen(true);
    calculateDetailsSummary(filter);
  };

  const calculateDetailsSummary = async (filter: string) => {
    setDetailsLoading(true);
    
    let filteredData: Batch[] = [];
    if (filter === 'all') {
      filteredData = [...batches];
    } else if (filter === 'active') {
      filteredData = batches.filter(b => b.isActive);
    }

    const totalFiles = filteredData.reduce((sum, b) => sum + b.fileCount, 0);
    const totalOutstanding = filteredData.reduce((sum, b) => sum + b.totalOutstanding, 0);

    // Fetch agent breakdown if admin/manager
    let byAgent: UserBreakdown[] = [];
    if (canViewUserBreakdown) {
      try {
        const res = await fetch('/api/dashboard/details?category=files&period=all');
        if (res.ok) {
          const data = await res.json();
          byAgent = (data.summary?.byAgent || []) as UserBreakdown[];
        }
      } catch (error) {
        console.error('Error fetching agent breakdown:', error);
      }
    }

    setDetailsData(filteredData);
    setDetailsSummary({
      count: filteredData.length,
      totalFiles,
      totalOutstanding,
      byAgent
    });
    setDetailsLoading(false);
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-KE', { style: 'currency', currency: 'KES' }).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';
    }
  };

  // Summary stats
  const totalBatches = batches.length;
  const activeBatches = batches.filter(b => b.isActive).length;
  const totalFiles = batches.reduce((sum, b) => sum + b.fileCount, 0);
  const totalOutstanding = batches.reduce((sum, b) => sum + b.totalOutstanding, 0);

  const BatchForm = ({ onSubmit, submitLabel }: { onSubmit: () => void; submitLabel: string }) => (
    <div className="space-y-4">
      <div>
        <Label htmlFor="name">Batch Name *</Label>
        <Input
          id="name"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          placeholder="e.g., January 2026 Collection"
        />
      </div>
      <div>
        <Label htmlFor="clientName">Client Name</Label>
        <Input
          id="clientName"
          value={formData.clientName}
          onChange={(e) => setFormData({ ...formData, clientName: e.target.value })}
          placeholder="e.g., ABC Bank"
        />
      </div>
      <div>
        <Label htmlFor="assignedTo">Assign To</Label>
        <Select 
          value={formData.assignedToId} 
          onValueChange={(value) => setFormData({ ...formData, assignedToId: value === 'none' ? '' : value })}
        >
          <SelectTrigger className="mt-1">
            <SelectValue placeholder="Select a user (optional)" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="none">
              <span className="text-muted-foreground">No assignment</span>
            </SelectItem>
            {users.filter(u => u.role === 'ADMIN').length > 0 && (
              <>
                <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted">Admins</div>
                {users.filter(u => u.role === 'ADMIN').map(user => (
                  <SelectItem key={user.id} value={user.id}>
                    <div className="flex items-center gap-2">
                      <span>{user.name}</span>
                      <Badge variant="outline" className="text-xs bg-red-50 text-red-700 border-red-200">Admin</Badge>
                    </div>
                  </SelectItem>
                ))}
              </>
            )}
            {users.filter(u => u.role === 'MANAGER').length > 0 && (
              <>
                <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted">Managers</div>
                {users.filter(u => u.role === 'MANAGER').map(user => (
                  <SelectItem key={user.id} value={user.id}>
                    <div className="flex items-center gap-2">
                      <span>{user.name}</span>
                      <Badge variant="outline" className="text-xs bg-purple-50 text-purple-700 border-purple-200">Manager</Badge>
                    </div>
                  </SelectItem>
                ))}
              </>
            )}
            {users.filter(u => u.role === 'AGENT').length > 0 && (
              <>
                <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted">Agents</div>
                {users.filter(u => u.role === 'AGENT').map(user => (
                  <SelectItem key={user.id} value={user.id}>
                    <div className="flex items-center gap-2">
                      <span>{user.name}</span>
                      <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700 border-blue-200">Agent</Badge>
                    </div>
                  </SelectItem>
                ))}
              </>
            )}
          </SelectContent>
        </Select>
        <p className="text-xs text-muted-foreground mt-1">Optionally assign this batch to an admin, manager, or agent</p>
      </div>
      <div>
        <Label htmlFor="description">Description</Label>
        <Textarea
          id="description"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          placeholder="Brief description of this batch"
        />
      </div>
      <div>
        <Label htmlFor="targetAmount">Target Amount (KES)</Label>
        <Input
          id="targetAmount"
          type="number"
          value={formData.targetAmount}
          onChange={(e) => setFormData({ ...formData, targetAmount: e.target.value })}
          placeholder="0.00"
        />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="startDate">Start Date</Label>
          <Input
            id="startDate"
            type="date"
            value={formData.startDate}
            onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
          />
        </div>
        <div>
          <Label htmlFor="endDate">End Date</Label>
          <Input
            id="endDate"
            type="date"
            value={formData.endDate}
            onChange={(e) => setFormData({ ...formData, endDate: e.target.value })}
          />
        </div>
      </div>
      <div className="flex justify-end gap-2 pt-4">
        <Button variant="outline" onClick={() => {
          setShowCreateDialog(false);
          setShowEditDialog(false);
          setEditingBatch(null);
          setFormData({ name: '', description: '', clientName: '', targetAmount: '', startDate: '', endDate: '', assignedToId: '' });
        }}>
          Cancel
        </Button>
        <Button onClick={onSubmit} disabled={!formData.name}>
          {submitLabel}
        </Button>
      </div>
    </div>
  );

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold">Batches</h1>
            <p className="text-muted-foreground">Manage collection file batches</p>
          </div>
          {canManageBatches && (
            <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="h-4 w-4 mr-2" />
                  Create Batch
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Create New Batch</DialogTitle>
                </DialogHeader>
                <BatchForm onSubmit={handleCreate} submitLabel="Create Batch" />
              </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 hover:border-blue-300"
            onClick={() => openDetailsDialog('all', 'All Batches')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <FolderOpen className="h-6 w-6 text-blue-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Total Batches</p>
                  <p className="text-2xl font-bold">{totalBatches}</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={() => openDetailsDialog('active', 'Active Batches')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-green-100 rounded-lg">
                  <Target className="h-6 w-6 text-green-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Active Batches</p>
                  <p className="text-2xl font-bold">{activeBatches}</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-purple-300"
            onClick={() => openDetailsDialog('all', 'Total Files')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <Users className="h-6 w-6 text-purple-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Total Files</p>
                  <p className="text-2xl font-bold">{totalFiles}</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={() => openDetailsDialog('all', 'Total Outstanding')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <TrendingUp className="h-6 w-6 text-orange-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm text-muted-foreground">Total Outstanding</p>
                  <p className="text-xl font-bold">{formatCurrency(totalOutstanding)}</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Batches List */}
        {loading ? (
          <div className="text-center py-8">Loading batches...</div>
        ) : batches.length === 0 ? (
          <Card>
            <CardContent className="py-12 text-center">
              <FolderOpen className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium mb-2">No Batches Yet</h3>
              <p className="text-muted-foreground mb-4">Create your first batch to organize collection files</p>
              {canManageBatches && (
                <Button onClick={() => setShowCreateDialog(true)}>
                  <Plus className="h-4 w-4 mr-2" />
                  Create Batch
                </Button>
              )}
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {batches.map((batch) => (
              <Card key={batch.id} className="hover:shadow-lg transition-shadow">
                <CardHeader className="pb-2">
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle className="text-lg">{batch.name}</CardTitle>
                      {batch.clientName && (
                        <p className="text-sm text-muted-foreground">{batch.clientName}</p>
                      )}
                    </div>
                    <Badge variant={batch.isActive ? 'default' : 'secondary'}>
                      {batch.isActive ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                  {batch.assignedTo && (
                    <div className="flex items-center gap-2 mt-2 p-2 bg-muted/50 rounded-md">
                      <UserCircle className="h-4 w-4 text-muted-foreground" />
                      <span className="text-sm font-medium">{batch.assignedTo.name}</span>
                      <Badge variant="outline" className={`text-xs ${getRoleBadgeColor(batch.assignedTo.role)}`}>
                        {batch.assignedTo.role}
                      </Badge>
                    </div>
                  )}
                </CardHeader>
                <CardContent className="space-y-4">
                  {batch.description && (
                    <p className="text-sm text-muted-foreground line-clamp-2">{batch.description}</p>
                  )}
                  
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <p className="text-muted-foreground">Files</p>
                      <p className="font-medium">{batch.fileCount}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground">Paid</p>
                      <p className="font-medium text-green-600">{batch.paidCount}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground">To Collect</p>
                      <p className="font-medium">{formatCurrency(batch.totalToCollect)}</p>
                    </div>
                    <div>
                      <p className="text-muted-foreground">Collected</p>
                      <p className="font-medium text-green-600">{formatCurrency(batch.totalCollected)}</p>
                    </div>
                  </div>

                  {/* Progress Bar */}
                  <div>
                    <div className="flex justify-between text-xs mb-1">
                      <span>Collection Rate</span>
                      <span className="font-medium">{batch.collectionRate}%</span>
                    </div>
                    <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                      <div 
                        className="h-full bg-green-500 rounded-full transition-all"
                        style={{ width: `${Math.min(parseFloat(batch.collectionRate), 100)}%` }}
                      />
                    </div>
                  </div>

                  {(batch.startDate || batch.endDate) && (
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Calendar className="h-3 w-3" />
                      {batch.startDate && format(new Date(batch.startDate), 'MMM d, yyyy')}
                      {batch.startDate && batch.endDate && ' - '}
                      {batch.endDate && format(new Date(batch.endDate), 'MMM d, yyyy')}
                    </div>
                  )}

                  <div className="flex gap-2 pt-2">
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="flex-1"
                      onClick={() => router.push(`/batches/${batch.id}`)}
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      View
                    </Button>
                    {canManageBatches && (
                      <>
                        <Button variant="outline" size="sm" onClick={() => handleEdit(batch)}>
                          <Edit className="h-4 w-4" />
                        </Button>
                        {session?.user?.role === 'ADMIN' && (
                          <Button variant="outline" size="sm" onClick={() => handleDelete(batch.id)}>
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        )}
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Edit Dialog */}
        <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Edit Batch</DialogTitle>
            </DialogHeader>
            <BatchForm onSubmit={handleUpdate} submitLabel="Save Changes" />
          </DialogContent>
        </Dialog>

        {/* Details Dialog */}
        <Dialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
          <DialogContent className="max-w-4xl max-h-[80vh]">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <FolderOpen className="h-5 w-5 text-blue-600" />
                {detailsTitle}
              </DialogTitle>
              <DialogDescription>
                Detailed breakdown of batches
              </DialogDescription>
            </DialogHeader>

            {detailsLoading ? (
              <div className="flex justify-center items-center py-8">
                <RefreshCw className="h-8 w-8 animate-spin text-blue-600" />
              </div>
            ) : (
              <Tabs value={detailsTab} onValueChange={setDetailsTab}>
                <TabsList>
                  <TabsTrigger value="details">Batches</TabsTrigger>
                  {canViewUserBreakdown && <TabsTrigger value="byAgent">By Agent</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">Batches</p>
                          <p className="text-2xl font-bold">{detailsSummary.count}</p>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardContent className="pt-4">
                          <p className="text-sm text-muted-foreground">Total Files</p>
                          <p className="text-2xl font-bold">{detailsSummary.totalFiles}</p>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardContent className="pt-4">
                          <p className="text-sm text-muted-foreground">Outstanding</p>
                          <p className="text-xl font-bold">{formatCurrency(detailsSummary.totalOutstanding)}</p>
                        </CardContent>
                      </Card>
                    </div>

                    {/* Data Table */}
                    <ScrollArea className="h-[400px] rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Batch Name</TableHead>
                            <TableHead>Client</TableHead>
                            <TableHead>Files</TableHead>
                            <TableHead>To Collect</TableHead>
                            <TableHead>Outstanding</TableHead>
                            <TableHead>Rate</TableHead>
                            <TableHead>Status</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {detailsData.length === 0 ? (
                            <TableRow>
                              <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                                No batches found
                              </TableCell>
                            </TableRow>
                          ) : (
                            detailsData.map((batch) => (
                              <TableRow key={batch.id}>
                                <TableCell className="font-medium">{batch.name}</TableCell>
                                <TableCell>{batch.clientName || '-'}</TableCell>
                                <TableCell>{batch.fileCount}</TableCell>
                                <TableCell>{formatCurrency(batch.totalToCollect)}</TableCell>
                                <TableCell>{formatCurrency(batch.totalOutstanding)}</TableCell>
                                <TableCell>{batch.collectionRate}%</TableCell>
                                <TableCell>
                                  <Badge variant={batch.isActive ? 'default' : 'secondary'}>
                                    {batch.isActive ? 'Active' : 'Inactive'}
                                  </Badge>
                                </TableCell>
                              </TableRow>
                            ))
                          )}
                        </TableBody>
                      </Table>
                    </ScrollArea>
                  </div>
                </TabsContent>

                {canViewUserBreakdown && (
                  <TabsContent value="byAgent">
                    <ScrollArea className="h-[400px]">
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-1">
                        {detailsSummary.byAgent.length === 0 ? (
                          <p className="col-span-3 text-center py-8 text-muted-foreground">No agent data available</p>
                        ) : (
                          detailsSummary.byAgent.map((agent, 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">{agent.name}</span>
                                  </div>
                                  <Badge variant="outline" className={getRoleBadgeColor(agent.role)}>
                                    {agent.role}
                                  </Badge>
                                </div>
                                <div className="space-y-1 text-sm">
                                  <div className="flex justify-between">
                                    <span className="text-muted-foreground">Files:</span>
                                    <span className="font-medium">{agent.count}</span>
                                  </div>
                                  <div className="flex justify-between">
                                    <span className="text-muted-foreground">Outstanding:</span>
                                    <span className="font-medium">{formatCurrency(agent.outstanding || 0)}</span>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))
                        )}
                      </div>
                    </ScrollArea>
                  </TabsContent>
                )}
              </Tabs>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}
