'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, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
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,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import {
  FileText,
  Plus,
  Calendar,
  TrendingUp,
  Users,
  Building2,
  Shield,
  Download,
  Eye,
  Loader2,
  BarChart3,
  DollarSign,
  Phone,
  CheckCircle,
  AlertTriangle,
  FileSpreadsheet,
  FileDown,
  ChevronDown,
  Trash2
} from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

interface Report {
  id: string;
  type: string;
  title: string;
  periodStart: string;
  periodEnd: string;
  status: string;
  generatedAt: string;
  client?: {
    id: string;
    name: string;
    email: string;
  };
  data: string;
}

interface Client {
  id: string;
  name: string;
  email: string;
}

type ReportData = {
  overview?: {
    totalFiles: number;
    totalToCollect: number;
    totalCollected: number;
    totalOutstanding: number;
    collectionRate: string;
    totalActivities: number;
  };
  statusCounts?: Record<string, number>;
  promiseStats?: {
    total: number;
    pending: number;
    kept: number;
    broken: number;
  };
  paymentMethodBreakdown?: Record<string, number>;
  agents?: Array<{
    name: string;
    periodCollected: number;
    collectionRate: string;
    totalActivities: number;
    callsMade: number;
  }>;
  totals?: {
    totalCollected: number;
    totalActivities: number;
    totalCalls: number;
  };
  rankings?: {
    byCollection: Array<{ rank: number; name: string; amount: number }>;
  };
  batchPerformance?: Array<{
    name: string;
    client: string;
    periodCollected: number;
    collectionRate: string;
    targetProgress: string;
  }>;
  overallMetrics?: {
    totalBatches: number;
    activeBatches: number;
    totalCollected: number;
    overallTargetProgress: string;
  };
  systemOverview?: {
    totalUsers: number;
    usersByRole: Record<string, number>;
    totalClients: number;
    totalBatches: number;
    totalFiles: number;
  };
  financials?: {
    totalToCollect: number;
    totalOutstanding: number;
    totalCollected: number;
    periodCollected: number;
    collectionRate: string;
  };
  activities?: {
    totalActivities: number;
    breakdown: Record<string, number>;
    smsSent: number;
  };
  fileStatus?: Record<string, number>;
};

const REPORT_TYPES = [
  { value: 'MONTHLY_SUMMARY', label: 'Monthly Summary', icon: FileText, description: 'Overview of collection performance' },
  { value: 'MONTHLY_ACCOUNTS', label: 'Accounts Report', icon: Building2, description: 'Detailed account-level analysis' },
  { value: 'MONTHLY_AGENTS', label: 'Agents Report', icon: Users, description: 'Agent performance metrics' },
  { value: 'MONTHLY_MANAGERS', label: 'Managers Report', icon: TrendingUp, description: 'Team and batch performance' },
  { value: 'MONTHLY_ADMINS', label: 'Admin Report', icon: Shield, description: 'System-wide analytics' },
];

const MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'
];

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8'];

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

  const [reports, setReports] = useState<Report[]>([]);
  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [viewingReport, setViewingReport] = useState<Report | null>(null);
  const [reportData, setReportData] = useState<ReportData | null>(null);

  const [formData, setFormData] = useState({
    reportType: 'MONTHLY_SUMMARY',
    clientId: '',
    month: new Date().getMonth(),
    year: new Date().getFullYear()
  });
  const [exporting, setExporting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [reportToDelete, setReportToDelete] = useState<Report | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const isAdmin = session?.user?.role === 'ADMIN';

  const fetchReports = useCallback(async () => {
    try {
      const res = await fetch('/api/reports/monthly?limit=50');
      if (res.ok) {
        const data = await res.json();
        setReports(data);
      }
    } catch (error) {
      console.error('Error fetching reports:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchClients = useCallback(async () => {
    try {
      const res = await fetch('/api/clients');
      if (res.ok) {
        const data = await res.json();
        setClients(data);
      }
    } catch (error) {
      console.error('Error fetching clients:', error);
    }
  }, []);

  useEffect(() => {
    fetchReports();
    fetchClients();
  }, [fetchReports, fetchClients]);

  useEffect(() => {
    if (session?.user?.role === 'AGENT') {
      router.push('/dashboard');
    }
  }, [session, router]);

  const handleGenerateReport = async (e: React.FormEvent) => {
    e.preventDefault();
    setGenerating(true);

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

      if (res.ok) {
        const data = await res.json();
        toast({
          title: 'Success',
          description: 'Report generated successfully',
        });
        setIsDialogOpen(false);
        fetchReports();
        // Show the generated report
        setViewingReport(data.report);
        setReportData(data.data);
      } else {
        throw new Error('Failed to generate report');
      }
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to generate report',
        variant: 'destructive',
      });
    } finally {
      setGenerating(false);
    }
  };

  const handleViewReport = (report: Report) => {
    setViewingReport(report);
    try {
      setReportData(JSON.parse(report.data));
    } catch {
      setReportData(null);
    }
  };

  const handleDeleteClick = (report: Report, e: React.MouseEvent) => {
    e.stopPropagation();
    setReportToDelete(report);
    setIsDeleteDialogOpen(true);
  };

  const handleDeleteReport = async () => {
    if (!reportToDelete) return;

    setDeleting(true);
    try {
      const res = await fetch(`/api/reports/monthly?id=${reportToDelete.id}`, {
        method: 'DELETE'
      });

      if (res.ok) {
        toast({
          title: 'Success',
          description: 'Report deleted successfully',
        });
        // Clear viewing report if it was the deleted one
        if (viewingReport?.id === reportToDelete.id) {
          setViewingReport(null);
          setReportData(null);
        }
        // Refresh the reports list
        fetchReports();
      } else {
        const data = await res.json();
        throw new Error(data.error || 'Failed to delete report');
      }
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to delete report',
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
      setIsDeleteDialogOpen(false);
      setReportToDelete(null);
    }
  };

  const handleExportReport = async (format: 'csv' | 'excel' | 'pdf') => {
    if (!viewingReport || !reportData) {
      toast({ title: 'Error', description: 'No report selected to export', variant: 'destructive' });
      return;
    }
    
    setExporting(true);
    if (format === 'pdf') {
      toast({ title: 'Generating PDF', description: 'Please wait while the PDF is being generated...' });
    }
    
    try {
      // Convert report data to CSV format
      let csvContent = '';
      const reportType = viewingReport.type;
      
      if (reportType === 'MONTHLY_SUMMARY' && reportData.overview) {
        csvContent = `MONTHLY SUMMARY REPORT\n`;
        csvContent += `Period,${viewingReport.periodStart} to ${viewingReport.periodEnd}\n\n`;
        csvContent += `OVERVIEW\n`;
        csvContent += `Metric,Value\n`;
        csvContent += `Total Files,${reportData.overview.totalFiles}\n`;
        csvContent += `Total To Collect (KES),${reportData.overview.totalToCollect}\n`;
        csvContent += `Total Collected (KES),${reportData.overview.totalCollected}\n`;
        csvContent += `Total Outstanding (KES),${reportData.overview.totalOutstanding}\n`;
        csvContent += `Collection Rate (%),${reportData.overview.collectionRate}\n`;
        csvContent += `Total Activities,${reportData.overview.totalActivities}\n\n`;
        
        if (reportData.statusCounts) {
          csvContent += `FILE STATUS BREAKDOWN\n`;
          csvContent += `Status,Count\n`;
          Object.entries(reportData.statusCounts).forEach(([status, count]) => {
            csvContent += `${status},${count}\n`;
          });
          csvContent += `\n`;
        }
        
        if (reportData.promiseStats) {
          csvContent += `PROMISE TO PAY STATISTICS\n`;
          csvContent += `Metric,Value\n`;
          csvContent += `Total Promises,${reportData.promiseStats.total}\n`;
          csvContent += `Pending,${reportData.promiseStats.pending}\n`;
          csvContent += `Kept,${reportData.promiseStats.kept}\n`;
          csvContent += `Broken,${reportData.promiseStats.broken}\n`;
        }
      } else if (reportType === 'MONTHLY_AGENTS' && reportData.agents) {
        csvContent = `MONTHLY AGENTS REPORT\n`;
        csvContent += `Period,${viewingReport.periodStart} to ${viewingReport.periodEnd}\n\n`;
        csvContent += `Agent Name,Collected (KES),Collection Rate (%),Activities,Calls Made\n`;
        reportData.agents.forEach(agent => {
          csvContent += `${agent.name},${agent.periodCollected},${agent.collectionRate},${agent.totalActivities},${agent.callsMade}\n`;
        });
        if (reportData.totals) {
          csvContent += `TOTAL,${reportData.totals.totalCollected},,${reportData.totals.totalActivities},${reportData.totals.totalCalls}\n`;
        }
      } else if (reportType === 'MONTHLY_MANAGERS' && reportData.batchPerformance) {
        csvContent = `MONTHLY MANAGERS REPORT\n`;
        csvContent += `Period,${viewingReport.periodStart} to ${viewingReport.periodEnd}\n\n`;
        csvContent += `Batch Name,Client,Collected (KES),Collection Rate (%),Target Progress (%)\n`;
        reportData.batchPerformance.forEach(batch => {
          csvContent += `${batch.name},${batch.client},${batch.periodCollected},${batch.collectionRate},${batch.targetProgress}\n`;
        });
      } else if (reportType === 'MONTHLY_ADMINS' && reportData.systemOverview) {
        csvContent = `MONTHLY ADMIN REPORT\n`;
        csvContent += `Period,${viewingReport.periodStart} to ${viewingReport.periodEnd}\n\n`;
        csvContent += `SYSTEM OVERVIEW\n`;
        csvContent += `Metric,Value\n`;
        csvContent += `Total Users,${reportData.systemOverview.totalUsers}\n`;
        csvContent += `Total Clients,${reportData.systemOverview.totalClients}\n`;
        csvContent += `Total Batches,${reportData.systemOverview.totalBatches}\n`;
        csvContent += `Total Files,${reportData.systemOverview.totalFiles}\n\n`;
        if (reportData.financials) {
          csvContent += `FINANCIAL SUMMARY\n`;
          csvContent += `Total To Collect (KES),${reportData.financials.totalToCollect}\n`;
          csvContent += `Total Collected (KES),${reportData.financials.totalCollected}\n`;
          csvContent += `Total Outstanding (KES),${reportData.financials.totalOutstanding}\n`;
          csvContent += `Period Collected (KES),${reportData.financials.periodCollected}\n`;
          csvContent += `Collection Rate (%),${reportData.financials.collectionRate}\n`;
        }
      } else {
        csvContent = `MONTHLY REPORT\n`;
        csvContent += `Period,${viewingReport.periodStart} to ${viewingReport.periodEnd}\n\n`;
        csvContent += `Report data not available in exportable format.\n`;
      }
      
      // Use the download API with the CSV content
      const params = new URLSearchParams({
        type: 'summary',
        startDate: viewingReport.periodStart.split('T')[0],
        endDate: viewingReport.periodEnd.split('T')[0],
        format
      });
      
      // For monthly reports, we'll create the file directly from the report data
      if (format === 'csv') {
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${viewingReport.title.replace(/[^a-z0-9]/gi, '_')}.csv`;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(url);
        document.body.removeChild(a);
        toast({ title: 'Success', description: 'CSV report downloaded' });
      } else if (format === 'excel') {
        // Generate Excel XML
        const lines = csvContent.split('\n').filter(line => line.trim());
        const rows = lines.map(line => line.split(',').map(cell => cell.trim()));
        
        let xmlRows = '';
        rows.forEach((row, rowIndex) => {
          let xmlCells = '';
          row.forEach(cell => {
            const isNumber = !isNaN(Number(cell)) && cell !== '';
            const cellType = isNumber ? 'Number' : 'String';
            const cellValue = cell.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            xmlCells += `<Cell><Data ss:Type="${cellType}">${cellValue}</Data></Cell>`;
          });
          const style = rowIndex === 0 || row[0]?.toUpperCase() === row[0] ? ' ss:StyleID="Header"' : '';
          xmlRows += `<Row${style}>${xmlCells}</Row>`;
        });
        
        const excelXML = `<?xml version="1.0" encoding="UTF-8"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
  <Styles>
    <Style ss:ID="Default"/>
    <Style ss:ID="Header"><Font ss:Bold="1"/><Interior ss:Color="#E0E0E0" ss:Pattern="Solid"/></Style>
  </Styles>
  <Worksheet ss:Name="${viewingReport.title.substring(0, 31)}">
    <Table>${xmlRows}</Table>
  </Worksheet>
</Workbook>`;
        
        const blob = new Blob([excelXML], { type: 'application/vnd.ms-excel' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${viewingReport.title.replace(/[^a-z0-9]/gi, '_')}.xls`;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(url);
        document.body.removeChild(a);
        toast({ title: 'Success', description: 'Excel report downloaded' });
      } else if (format === 'pdf') {
        // Use the API to generate PDF
        const response = await fetch('/api/reports/monthly/export', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            reportId: viewingReport.id,
            format: 'pdf'
          })
        });
        
        if (response.ok) {
          const blob = await response.blob();
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `${viewingReport.title.replace(/[^a-z0-9]/gi, '_')}.pdf`;
          document.body.appendChild(a);
          a.click();
          URL.revokeObjectURL(url);
          document.body.removeChild(a);
          toast({ title: 'Success', description: 'PDF report downloaded' });
        } else {
          throw new Error('Failed to generate PDF');
        }
      }
    } catch (error) {
      console.error('Export error:', error);
      toast({ title: 'Error', description: 'Failed to export report', variant: 'destructive' });
    } finally {
      setExporting(false);
    }
  };

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

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString('en-KE', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const getReportTypeInfo = (type: string) => {
    return REPORT_TYPES.find(t => t.value === type) || REPORT_TYPES[0];
  };

  const getStatusBadge = (status: string) => {
    const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
      COMPLETED: 'default',
      PENDING: 'secondary',
      GENERATING: 'outline',
      FAILED: 'destructive',
      SENT: 'default'
    };
    return <Badge variant={variants[status] || 'secondary'}>{status}</Badge>;
  };

  const renderReportContent = () => {
    if (!viewingReport || !reportData) return null;

    const type = viewingReport.type;

    if (type === 'MONTHLY_SUMMARY' && reportData.overview) {
      const statusData = reportData.statusCounts ? Object.entries(reportData.statusCounts).map(([name, value]) => ({ name, value })) : [];
      const paymentData = reportData.paymentMethodBreakdown ? Object.entries(reportData.paymentMethodBreakdown).map(([name, value]) => ({ name, value })) : [];

      return (
        <div className="space-y-6">
          {/* Overview Cards */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.overview.totalFiles}</div>
                <p className="text-sm text-muted-foreground">Total Files</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{formatCurrency(reportData.overview.totalCollected)}</div>
                <p className="text-sm text-muted-foreground">Collected</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.overview.collectionRate}%</div>
                <p className="text-sm text-muted-foreground">Collection Rate</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.overview.totalActivities}</div>
                <p className="text-sm text-muted-foreground">Activities</p>
              </CardContent>
            </Card>
          </div>

          {/* Charts */}
          <div className="grid md:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Status Distribution</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={250}>
                  <PieChart>
                    <Pie data={statusData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} label>
                      {statusData.map((_, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Payment Methods</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={250}>
                  <BarChart data={paymentData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip formatter={(value: number) => formatCurrency(value)} />
                    <Bar dataKey="value" fill="#8884d8" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Promise Stats */}
          {reportData.promiseStats && (
            <Card>
              <CardHeader>
                <CardTitle>Promise to Pay Statistics</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-4 gap-4">
                  <div className="text-center">
                    <div className="text-2xl font-bold">{reportData.promiseStats.total}</div>
                    <p className="text-sm text-muted-foreground">Total</p>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-yellow-600">{reportData.promiseStats.pending}</div>
                    <p className="text-sm text-muted-foreground">Pending</p>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-600">{reportData.promiseStats.kept}</div>
                    <p className="text-sm text-muted-foreground">Kept</p>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-red-600">{reportData.promiseStats.broken}</div>
                    <p className="text-sm text-muted-foreground">Broken</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      );
    }

    if (type === 'MONTHLY_AGENTS' && reportData.agents) {
      return (
        <div className="space-y-6">
          {/* Totals */}
          {reportData.totals && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.agents.length}</div>
                  <p className="text-sm text-muted-foreground">Total Agents</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{formatCurrency(reportData.totals.totalCollected)}</div>
                  <p className="text-sm text-muted-foreground">Total Collected</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.totals.totalActivities}</div>
                  <p className="text-sm text-muted-foreground">Total Activities</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.totals.totalCalls}</div>
                  <p className="text-sm text-muted-foreground">Total Calls</p>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Agent Rankings Chart */}
          {reportData.rankings?.byCollection && (
            <Card>
              <CardHeader>
                <CardTitle>Top Performers by Collection</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={reportData.rankings.byCollection.slice(0, 10)} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" tickFormatter={(value) => formatCurrency(value)} />
                    <YAxis dataKey="name" type="category" width={100} />
                    <Tooltip formatter={(value: number) => formatCurrency(value)} />
                    <Bar dataKey="amount" fill="#22c55e" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          )}

          {/* Agent Table */}
          <Card>
            <CardHeader>
              <CardTitle>Agent Performance Details</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Agent</TableHead>
                    <TableHead>Collected</TableHead>
                    <TableHead>Rate</TableHead>
                    <TableHead>Activities</TableHead>
                    <TableHead>Calls</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {reportData.agents.map((agent, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="font-medium">{agent.name}</TableCell>
                      <TableCell>{formatCurrency(agent.periodCollected)}</TableCell>
                      <TableCell>{agent.collectionRate}%</TableCell>
                      <TableCell>{agent.totalActivities}</TableCell>
                      <TableCell>{agent.callsMade}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </div>
      );
    }

    if (type === 'MONTHLY_MANAGERS' && reportData.batchPerformance) {
      return (
        <div className="space-y-6">
          {reportData.overallMetrics && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.overallMetrics.totalBatches}</div>
                  <p className="text-sm text-muted-foreground">Total Batches</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.overallMetrics.activeBatches}</div>
                  <p className="text-sm text-muted-foreground">Active Batches</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{formatCurrency(reportData.overallMetrics.totalCollected)}</div>
                  <p className="text-sm text-muted-foreground">Total Collected</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-4">
                  <div className="text-2xl font-bold">{reportData.overallMetrics.overallTargetProgress}%</div>
                  <p className="text-sm text-muted-foreground">Target Progress</p>
                </CardContent>
              </Card>
            </div>
          )}

          <Card>
            <CardHeader>
              <CardTitle>Batch Performance</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Batch</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead>Collected</TableHead>
                    <TableHead>Collection Rate</TableHead>
                    <TableHead>Target Progress</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {reportData.batchPerformance.map((batch, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="font-medium">{batch.name}</TableCell>
                      <TableCell>{batch.client}</TableCell>
                      <TableCell>{formatCurrency(batch.periodCollected)}</TableCell>
                      <TableCell>{batch.collectionRate}%</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div className="w-16 h-2 bg-gray-200 rounded-full overflow-hidden">
                            <div
                              className="h-full bg-blue-500 rounded-full"
                              style={{ width: `${Math.min(parseFloat(batch.targetProgress), 100)}%` }}
                            />
                          </div>
                          <span className="text-sm">{batch.targetProgress}%</span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </div>
      );
    }

    if (type === 'MONTHLY_ADMINS' && reportData.systemOverview) {
      const statusData = reportData.fileStatus ? Object.entries(reportData.fileStatus).map(([name, value]) => ({ name, value })) : [];
      const activityData = reportData.activities?.breakdown ? Object.entries(reportData.activities.breakdown).map(([name, value]) => ({ name, value })) : [];

      return (
        <div className="space-y-6">
          {/* System Overview */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.systemOverview.totalUsers}</div>
                <p className="text-sm text-muted-foreground">Total Users</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.systemOverview.totalClients}</div>
                <p className="text-sm text-muted-foreground">Clients</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.systemOverview.totalBatches}</div>
                <p className="text-sm text-muted-foreground">Batches</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.systemOverview.totalFiles}</div>
                <p className="text-sm text-muted-foreground">Files</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-4">
                <div className="text-2xl font-bold">{reportData.financials?.collectionRate}%</div>
                <p className="text-sm text-muted-foreground">Collection Rate</p>
              </CardContent>
            </Card>
          </div>

          {/* Financial Overview */}
          {reportData.financials && (
            <Card>
              <CardHeader>
                <CardTitle>Financial Summary</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <div className="text-xl font-bold">{formatCurrency(reportData.financials.totalToCollect)}</div>
                    <p className="text-sm text-muted-foreground">Total to Collect</p>
                  </div>
                  <div>
                    <div className="text-xl font-bold text-green-600">{formatCurrency(reportData.financials.totalCollected)}</div>
                    <p className="text-sm text-muted-foreground">Total Collected</p>
                  </div>
                  <div>
                    <div className="text-xl font-bold text-orange-600">{formatCurrency(reportData.financials.totalOutstanding)}</div>
                    <p className="text-sm text-muted-foreground">Outstanding</p>
                  </div>
                  <div>
                    <div className="text-xl font-bold text-blue-600">{formatCurrency(reportData.financials.periodCollected)}</div>
                    <p className="text-sm text-muted-foreground">Period Collected</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Charts */}
          <div className="grid md:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>File Status Distribution</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={250}>
                  <PieChart>
                    <Pie data={statusData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} label>
                      {statusData.map((_, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Activity Breakdown</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={250}>
                  <BarChart data={activityData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="value" fill="#8884d8" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* User Distribution */}
          {reportData.systemOverview.usersByRole && (
            <Card>
              <CardHeader>
                <CardTitle>Users by Role</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex gap-6">
                  {Object.entries(reportData.systemOverview.usersByRole).map(([role, count]) => (
                    <div key={role} className="text-center">
                      <div className="text-xl font-bold">{count}</div>
                      <p className="text-sm text-muted-foreground">{role}</p>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      );
    }

    return (
      <Card>
        <CardContent className="py-8 text-center text-muted-foreground">
          Report data visualization not available for this report type.
        </CardContent>
      </Card>
    );
  };

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Monthly Reports</h1>
            <p className="text-muted-foreground">
              Generate and view monthly progress reports for accounts, agents, managers, and admins
            </p>
          </div>
          <Button onClick={() => setIsDialogOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Generate Report
          </Button>
        </div>

        {/* Report Type Cards */}
        <div className="grid gap-4 md:grid-cols-5">
          {REPORT_TYPES.map((type) => {
            const Icon = type.icon;
            const count = reports.filter(r => r.type === type.value).length;
            return (
              <Card key={type.value} className="cursor-pointer hover:border-primary transition-colors" onClick={() => {
                setFormData({ ...formData, reportType: type.value });
                setIsDialogOpen(true);
              }}>
                <CardHeader className="pb-2">
                  <Icon className="h-8 w-8 text-primary" />
                </CardHeader>
                <CardContent>
                  <h3 className="font-semibold">{type.label}</h3>
                  <p className="text-xs text-muted-foreground mt-1">{type.description}</p>
                  <Badge variant="secondary" className="mt-2">{count} reports</Badge>
                </CardContent>
              </Card>
            );
          })}
        </div>

        {/* Two Column Layout */}
        <div className="grid md:grid-cols-3 gap-6">
          {/* Reports List */}
          <Card className="md:col-span-1">
            <CardHeader>
              <CardTitle>Generated Reports</CardTitle>
              <CardDescription>Click to view report details</CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                </div>
              ) : reports.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  No reports generated yet
                </div>
              ) : (
                <div className="space-y-2 max-h-[600px] overflow-y-auto">
                  {reports.map((report) => {
                    const typeInfo = getReportTypeInfo(report.type);
                    const Icon = typeInfo.icon;
                    return (
                      <div
                        key={report.id}
                        className={`p-3 rounded-lg border cursor-pointer transition-colors ${
                          viewingReport?.id === report.id ? 'bg-primary/10 border-primary' : 'hover:bg-muted'
                        }`}
                        onClick={() => handleViewReport(report)}
                      >
                        <div className="flex items-start gap-3">
                          <Icon className="h-5 w-5 mt-0.5 text-muted-foreground" />
                          <div className="flex-1 min-w-0">
                            <p className="font-medium text-sm truncate">{report.title}</p>
                            <p className="text-xs text-muted-foreground">
                              {formatDate(report.periodStart)} - {formatDate(report.periodEnd)}
                            </p>
                            {report.client && (
                              <p className="text-xs text-blue-600 mt-1">{report.client.name}</p>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            {getStatusBadge(report.status)}
                            {isAdmin && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-7 w-7 text-muted-foreground hover:text-destructive"
                                onClick={(e) => handleDeleteClick(report, e)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Report Viewer */}
          <Card className="md:col-span-2">
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>{viewingReport?.title || 'Select a Report'}</CardTitle>
                  {viewingReport && (
                    <CardDescription>
                      {formatDate(viewingReport.periodStart)} - {formatDate(viewingReport.periodEnd)}
                      {viewingReport.client && ` • ${viewingReport.client.name}`}
                    </CardDescription>
                  )}
                </div>
                {viewingReport && (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="outline" size="sm" disabled={exporting}>
                        {exporting ? (
                          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        ) : (
                          <Download className="h-4 w-4 mr-2" />
                        )}
                        Export
                        <ChevronDown className="h-4 w-4 ml-2" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent>
                      <DropdownMenuItem onClick={() => handleExportReport('csv')}>
                        <FileDown className="h-4 w-4 mr-2" /> CSV
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => handleExportReport('excel')}>
                        <FileSpreadsheet className="h-4 w-4 mr-2" /> Excel
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => handleExportReport('pdf')}>
                        <FileText className="h-4 w-4 mr-2" /> PDF
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                )}
              </div>
            </CardHeader>
            <CardContent>
              {viewingReport ? (
                renderReportContent()
              ) : (
                <div className="text-center py-12 text-muted-foreground">
                  <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>Select a report from the list to view its details</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Generate Report Dialog */}
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle>Generate Monthly Report</DialogTitle>
              <DialogDescription>
                Select the report type and period to generate
              </DialogDescription>
            </DialogHeader>

            <form onSubmit={handleGenerateReport} className="space-y-4">
              <div className="space-y-2">
                <Label>Report Type</Label>
                <Select
                  value={formData.reportType}
                  onValueChange={(value) => setFormData({ ...formData, reportType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {REPORT_TYPES.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>Client (Optional)</Label>
                <Select
                  value={formData.clientId || 'all'}
                  onValueChange={(value) => setFormData({ ...formData, clientId: value === 'all' ? '' : value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="All clients" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All clients</SelectItem>
                    {clients.map((client) => (
                      <SelectItem key={client.id} value={client.id}>
                        {client.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Month</Label>
                  <Select
                    value={String(formData.month)}
                    onValueChange={(value) => setFormData({ ...formData, month: parseInt(value) })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {MONTHS.map((month, idx) => (
                        <SelectItem key={idx} value={String(idx)}>
                          {month}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Year</Label>
                  <Select
                    value={String(formData.year)}
                    onValueChange={(value) => setFormData({ ...formData, year: parseInt(value) })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {[2024, 2025, 2026].map((year) => (
                        <SelectItem key={year} value={String(year)}>
                          {year}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-4">
                <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                  Cancel
                </Button>
                <Button type="submit" disabled={generating}>
                  {generating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Generate Report
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Delete Report</AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to delete &quot;{reportToDelete?.title}&quot;? This action cannot be undone.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDeleteReport}
                disabled={deleting}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {deleting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Deleting...
                  </>
                ) : (
                  'Delete'
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </ProtectedLayout>
  );
}
