"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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/hooks/use-toast";
import {
  CreditCard,
  Smartphone,
  CheckCircle,
  XCircle,
  Clock,
  RefreshCw,
  Send,
  DollarSign,
  TrendingUp,
  AlertTriangle,
  Search,
  Eye,
  Loader2,
  Users,
} from "lucide-react";

interface MpesaTransaction {
  id: string;
  collectionFileId: string;
  phoneNumber: string;
  amount: number;
  accountReference: string;
  transactionDesc: string | null;
  merchantRequestId: string | null;
  checkoutRequestId: string | null;
  mpesaReceiptNumber: string | null;
  status: string;
  resultDesc: string | null;
  createdAt: string;
  completedAt: string | null;
  collectionFile: {
    id: string;
    customerName: string;
    phoneNumber: string;
    assignedAgent?: {
      id: string;
      name: string;
      role: string;
    };
  };
  payment: {
    id: string;
    amount: number;
    paymentDate: string;
  } | null;
}

interface TransactionSummary {
  total: number;
  completed: number;
  pending: number;
  failed: number;
  totalAmount: number;
  collectedAmount: number;
}

interface CollectionFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  outstandingBalance: number;
}

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

export default function PaymentsPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const { toast } = useToast();

  const [transactions, setTransactions] = useState<MpesaTransaction[]>([]);
  const [summary, setSummary] = useState<TransactionSummary>({
    total: 0,
    completed: 0,
    pending: 0,
    failed: 0,
    totalAmount: 0,
    collectedAmount: 0,
  });
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  // New payment dialog
  const [showPaymentDialog, setShowPaymentDialog] = useState(false);
  const [collectionFiles, setCollectionFiles] = useState<CollectionFile[]>([]);
  const [selectedFile, setSelectedFile] = useState<CollectionFile | null>(null);
  const [paymentAmount, setPaymentAmount] = useState("");
  const [paymentPhone, setPaymentPhone] = useState("");
  const [initiatingPayment, setInitiatingPayment] = useState(false);
  const [loadingFiles, setLoadingFiles] = useState(false);

  // Status polling
  const [pollingId, setPollingId] = useState<string | null>(null);

  // Details dialog state
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [detailsTitle, setDetailsTitle] = useState('');
  const [detailsData, setDetailsData] = useState<MpesaTransaction[]>([]);
  const [detailsSummary, setDetailsSummary] = useState<{ count: number; totalAmount: number; byUser: UserBreakdown[] }>({
    count: 0,
    totalAmount: 0,
    byUser: []
  });
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [detailsTab, setDetailsTab] = useState('details');
  const [detailsStatusFilter, setDetailsStatusFilter] = useState<string>('all');

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

  const fetchTransactions = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      params.append("page", page.toString());
      params.append("limit", "20");
      if (statusFilter !== "all") {
        params.append("status", statusFilter);
      }

      const res = await fetch(`/api/mpesa/transactions?${params}`);
      if (res.ok) {
        const data = await res.json();
        setTransactions(data.transactions);
        setSummary(data.summary);
        setTotalPages(data.pagination.pages);
      }
    } catch (error) {
      console.error("Error fetching transactions:", error);
    } finally {
      setLoading(false);
    }
  }, [page, statusFilter]);

  useEffect(() => {
    fetchTransactions();
  }, [fetchTransactions]);

  // Poll for pending transaction status
  useEffect(() => {
    if (!pollingId) return;

    const interval = setInterval(async () => {
      try {
        const res = await fetch(`/api/mpesa/status?transactionId=${pollingId}`);
        if (res.ok) {
          const data = await res.json();
          if (data.transaction.status !== "PENDING") {
            setPollingId(null);
            fetchTransactions();

            if (data.transaction.status === "COMPLETED") {
              toast({
                title: "Payment Successful!",
                description: `KES ${data.transaction.amount.toLocaleString()} received`,
              });
            } else {
              toast({
                title: "Payment Status",
                description: data.transaction.resultDesc || "Transaction completed",
                variant: data.transaction.status === "CANCELLED" ? "default" : "destructive",
              });
            }
          }
        }
      } catch (error) {
        console.error("Polling error:", error);
      }
    }, 5000);

    return () => clearInterval(interval);
  }, [pollingId, fetchTransactions, toast]);

  const fetchCollectionFiles = async () => {
    setLoadingFiles(true);
    try {
      const res = await fetch("/api/collection-files?status=IN_PROGRESS,NEW");
      if (res.ok) {
        const data = await res.json();
        setCollectionFiles(data.files || []);
      }
    } catch (error) {
      console.error("Error fetching files:", error);
    } finally {
      setLoadingFiles(false);
    }
  };

  const handleOpenPaymentDialog = () => {
    fetchCollectionFiles();
    setShowPaymentDialog(true);
  };

  const handleSelectFile = (fileId: string) => {
    const file = collectionFiles.find((f) => f.id === fileId);
    if (file) {
      setSelectedFile(file);
      setPaymentPhone(file.phoneNumber);
      setPaymentAmount(file.outstandingBalance.toString());
    }
  };

  const initiatePayment = async () => {
    if (!selectedFile || !paymentAmount || !paymentPhone) {
      toast({
        title: "Error",
        description: "Please fill in all required fields",
        variant: "destructive",
      });
      return;
    }

    setInitiatingPayment(true);
    try {
      const res = await fetch("/api/mpesa/stkpush", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          collectionFileId: selectedFile.id,
          amount: parseFloat(paymentAmount),
          phoneNumber: paymentPhone,
          description: `Payment for ${selectedFile.customerName}`,
        }),
      });

      const data = await res.json();

      if (res.ok && data.success) {
        toast({
          title: "Payment Request Sent",
          description: data.message || "Check your phone to complete payment",
        });
        setShowPaymentDialog(false);
        setPollingId(data.transaction.id);
        fetchTransactions();

        // Reset form
        setSelectedFile(null);
        setPaymentAmount("");
        setPaymentPhone("");
      } else {
        toast({
          title: "Failed to Initiate Payment",
          description: data.error || "Please try again",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("Payment initiation error:", error);
      toast({
        title: "Error",
        description: "Failed to initiate payment",
        variant: "destructive",
      });
    } finally {
      setInitiatingPayment(false);
    }
  };

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

  const calculateDetailsSummary = (statusFilter: string) => {
    setDetailsLoading(true);
    
    let filteredData: MpesaTransaction[] = [];
    if (statusFilter === 'all') {
      filteredData = [...transactions];
    } else if (statusFilter === 'completed') {
      filteredData = transactions.filter(t => t.status === 'COMPLETED');
    } else if (statusFilter === 'pending') {
      filteredData = transactions.filter(t => t.status === 'PENDING');
    } else if (statusFilter === 'failed') {
      filteredData = transactions.filter(t => t.status === 'FAILED' || t.status === 'CANCELLED' || t.status === 'TIMEOUT');
    }

    const totalAmount = filteredData.reduce((sum, t) => sum + t.amount, 0);

    // Calculate user breakdown
    const byUserMap = filteredData.reduce((acc, tx) => {
      const agentName = tx.collectionFile?.assignedAgent?.name || 'Unassigned';
      const agentRole = tx.collectionFile?.assignedAgent?.role || 'AGENT';
      const key = `${agentName}|${agentRole}`;
      if (!acc[key]) {
        acc[key] = { name: agentName, role: agentRole, count: 0, amount: 0 };
      }
      acc[key].count += 1;
      acc[key].amount += tx.amount;
      return acc;
    }, {} as Record<string, UserBreakdown>);

    setDetailsData(filteredData);
    setDetailsSummary({
      count: filteredData.length,
      totalAmount,
      byUser: Object.values(byUserMap)
    });
    setDetailsLoading(false);
  };

  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 getStatusBadge = (status: string) => {
    switch (status) {
      case "COMPLETED":
        return <Badge className="bg-green-100 text-green-800"><CheckCircle className="w-3 h-3 mr-1" />Completed</Badge>;
      case "PENDING":
        return <Badge className="bg-yellow-100 text-yellow-800"><Clock className="w-3 h-3 mr-1" />Pending</Badge>;
      case "FAILED":
        return <Badge className="bg-red-100 text-red-800"><XCircle className="w-3 h-3 mr-1" />Failed</Badge>;
      case "CANCELLED":
        return <Badge className="bg-gray-100 text-gray-800"><XCircle className="w-3 h-3 mr-1" />Cancelled</Badge>;
      case "TIMEOUT":
        return <Badge className="bg-orange-100 text-orange-800"><Clock className="w-3 h-3 mr-1" />Timeout</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const filteredTransactions = transactions.filter((tx) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      tx.collectionFile.customerName.toLowerCase().includes(query) ||
      tx.phoneNumber.includes(query) ||
      tx.accountReference.toLowerCase().includes(query) ||
      (tx.mpesaReceiptNumber && tx.mpesaReceiptNumber.toLowerCase().includes(query))
    );
  });

  return (
    <ProtectedLayout>
      <div className="p-6 space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <CreditCard className="h-6 w-6" />
              Payment Gateway
            </h1>
            <p className="text-muted-foreground">
              M-Pesa STK Push integration for automated payment collection
            </p>
          </div>
          <Button onClick={handleOpenPaymentDialog} className="gap-2">
            <Send className="h-4 w-4" />
            Initiate Payment
          </Button>
        </div>

        {/* Summary Cards - Clickable */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-blue-300"
            onClick={() => openDetailsDialog('all', 'All Transactions')}
          >
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Total Transactions
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-2xl font-bold">{summary.total}</div>
                  <p className="text-xs text-muted-foreground">
                    KES {summary.totalAmount.toLocaleString()} requested
                  </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('completed', 'Successful Transactions')}
          >
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <CheckCircle className="h-4 w-4 text-green-600" />
                Successful
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-2xl font-bold text-green-600">
                    {summary.completed}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    KES {summary.collectedAmount.toLocaleString()} collected
                  </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-yellow-300"
            onClick={() => openDetailsDialog('pending', 'Pending Transactions')}
          >
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <Clock className="h-4 w-4 text-yellow-600" />
                Pending
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-2xl font-bold text-yellow-600">
                    {summary.pending}
                  </div>
                  <p className="text-xs text-muted-foreground">Awaiting response</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={() => openDetailsDialog('all', 'Success Rate Details')}
          >
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <TrendingUp className="h-4 w-4 text-blue-600" />
                Success Rate
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-2xl font-bold text-blue-600">
                    {summary.total > 0
                      ? Math.round((summary.completed / summary.total) * 100)
                      : 0}
                    %
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {summary.failed} failed transactions
                  </p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Polling indicator */}
        {pollingId && (
          <Card className="bg-blue-50 border-blue-200">
            <CardContent className="py-3 flex items-center gap-3">
              <Loader2 className="h-5 w-5 text-blue-600 animate-spin" />
              <span className="text-blue-800">
                Waiting for payment confirmation... The customer should enter their M-Pesa PIN.
              </span>
            </CardContent>
          </Card>
        )}

        {/* Transactions List */}
        <Card>
          <CardHeader>
            <CardTitle>Transaction History</CardTitle>
            <CardDescription>
              View and track all M-Pesa payment requests
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col md:flex-row gap-4 mb-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search by name, phone, or receipt..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9"
                />
              </div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="Filter status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="COMPLETED">Completed</SelectItem>
                  <SelectItem value="PENDING">Pending</SelectItem>
                  <SelectItem value="FAILED">Failed</SelectItem>
                  <SelectItem value="CANCELLED">Cancelled</SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline" onClick={fetchTransactions} className="gap-2">
                <RefreshCw className="h-4 w-4" />
                Refresh
              </Button>
            </div>

            {loading ? (
              <div className="flex justify-center py-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : filteredTransactions.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Smartphone className="h-12 w-12 mx-auto mb-2 opacity-50" />
                <p>No transactions found</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Customer</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Amount</TableHead>
                    {canViewUserBreakdown && <TableHead>Agent</TableHead>}
                    <TableHead>Reference</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Receipt</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredTransactions.map((tx) => (
                    <TableRow key={tx.id}>
                      <TableCell className="font-medium">
                        {tx.collectionFile.customerName}
                      </TableCell>
                      <TableCell>{tx.phoneNumber}</TableCell>
                      <TableCell>KES {tx.amount.toLocaleString()}</TableCell>
                      {canViewUserBreakdown && (
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <span>{tx.collectionFile.assignedAgent?.name || 'Unassigned'}</span>
                            {tx.collectionFile.assignedAgent && (
                              <Badge variant="outline" className={`text-xs ${getRoleBadgeColor(tx.collectionFile.assignedAgent.role)}`}>
                                {tx.collectionFile.assignedAgent.role}
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                      )}
                      <TableCell>
                        <code className="text-xs bg-muted px-1 py-0.5 rounded">
                          {tx.accountReference}
                        </code>
                      </TableCell>
                      <TableCell>{getStatusBadge(tx.status)}</TableCell>
                      <TableCell>
                        {tx.mpesaReceiptNumber || "-"}
                      </TableCell>
                      <TableCell>
                        {new Date(tx.createdAt).toLocaleString()}
                      </TableCell>
                      <TableCell>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => router.push(`/files/${tx.collectionFileId}`)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex justify-center gap-2 mt-4">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === 1}
                  onClick={() => setPage(page - 1)}
                >
                  Previous
                </Button>
                <span className="px-3 py-1 text-sm">
                  Page {page} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === totalPages}
                  onClick={() => setPage(page + 1)}
                >
                  Next
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Initiate Payment Dialog */}
        <Dialog open={showPaymentDialog} onOpenChange={setShowPaymentDialog}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Smartphone className="h-5 w-5" />
                Initiate M-Pesa Payment
              </DialogTitle>
              <DialogDescription>
                Send an STK Push request to the customer&apos;s phone
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Select Customer</Label>
                <Select onValueChange={handleSelectFile}>
                  <SelectTrigger>
                    <SelectValue placeholder="Choose a customer..." />
                  </SelectTrigger>
                  <SelectContent>
                    {loadingFiles ? (
                      <SelectItem value="loading" disabled>
                        Loading...
                      </SelectItem>
                    ) : (
                      collectionFiles.map((file) => (
                        <SelectItem key={file.id} value={file.id}>
                          {file.customerName} - {file.phoneNumber}
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
              </div>

              {selectedFile && (
                <Card className="bg-muted">
                  <CardContent className="pt-4">
                    <div className="text-sm space-y-1">
                      <p>
                        <strong>Customer:</strong> {selectedFile.customerName}
                      </p>
                      <p>
                        <strong>Outstanding:</strong> KES{" "}
                        {selectedFile.outstandingBalance.toLocaleString()}
                      </p>
                    </div>
                  </CardContent>
                </Card>
              )}

              <div className="space-y-2">
                <Label htmlFor="phone">Phone Number</Label>
                <Input
                  id="phone"
                  placeholder="254712345678"
                  value={paymentPhone}
                  onChange={(e) => setPaymentPhone(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">
                  Format: 254XXXXXXXXX or 07XXXXXXXX
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="amount">Amount (KES)</Label>
                <Input
                  id="amount"
                  type="number"
                  placeholder="Enter amount"
                  value={paymentAmount}
                  onChange={(e) => setPaymentAmount(e.target.value)}
                />
              </div>
            </div>

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setShowPaymentDialog(false)}
              >
                Cancel
              </Button>
              <Button
                onClick={initiatePayment}
                disabled={initiatingPayment || !selectedFile}
                className="gap-2"
              >
                {initiatingPayment ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="h-4 w-4" />
                    Send Request
                  </>
                )}
              </Button>
            </DialogFooter>
          </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">
                <CreditCard className="h-5 w-5 text-blue-600" />
                {detailsTitle}
              </DialogTitle>
              <DialogDescription>
                Detailed breakdown of transactions
              </DialogDescription>
            </DialogHeader>

            {detailsLoading ? (
              <div className="flex justify-center items-center py-8">
                <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
              </div>
            ) : (
              <Tabs value={detailsTab} onValueChange={setDetailsTab}>
                <TabsList>
                  <TabsTrigger value="details">Details</TabsTrigger>
                  {canViewUserBreakdown && <TabsTrigger value="byUser">By Agent</TabsTrigger>}
                </TabsList>

                <TabsContent value="details">
                  <div className="space-y-4">
                    {/* Summary */}
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      <Card>
                        <CardContent className="pt-4">
                          <p className="text-sm text-muted-foreground">Total Records</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 Amount</p>
                          <p className="text-2xl font-bold">KES {detailsSummary.totalAmount.toLocaleString()}</p>
                        </CardContent>
                      </Card>
                    </div>

                    {/* Data Table */}
                    <ScrollArea className="h-[400px] rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Customer</TableHead>
                            <TableHead>Phone</TableHead>
                            <TableHead>Amount</TableHead>
                            {canViewUserBreakdown && <TableHead>Agent</TableHead>}
                            <TableHead>Status</TableHead>
                            <TableHead>Date</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {detailsData.length === 0 ? (
                            <TableRow>
                              <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                                No records found
                              </TableCell>
                            </TableRow>
                          ) : (
                            detailsData.map((tx) => (
                              <TableRow key={tx.id}>
                                <TableCell className="font-medium">{tx.collectionFile.customerName}</TableCell>
                                <TableCell>{tx.phoneNumber}</TableCell>
                                <TableCell>KES {tx.amount.toLocaleString()}</TableCell>
                                {canViewUserBreakdown && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <span>{tx.collectionFile.assignedAgent?.name || 'Unassigned'}</span>
                                      {tx.collectionFile.assignedAgent && (
                                        <Badge variant="outline" className={`text-xs ${getRoleBadgeColor(tx.collectionFile.assignedAgent.role)}`}>
                                          {tx.collectionFile.assignedAgent.role}
                                        </Badge>
                                      )}
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell>{getStatusBadge(tx.status)}</TableCell>
                                <TableCell>
                                  {new Date(tx.createdAt).toLocaleString()}
                                </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">
                        {detailsSummary.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">Transactions:</span>
                                  <span className="font-medium">{user.count}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">Amount:</span>
                                  <span className="font-medium">KES {user.amount.toLocaleString()}</span>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </ScrollArea>
                  </TabsContent>
                )}
              </Tabs>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}
