'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ProtectedLayout } from '@/components/protected-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  PieChart, Pie, Cell, LineChart, Line, AreaChart, Area
} from 'recharts';
import { Download, TrendingUp, Users, FolderOpen, DollarSign, Calendar, RefreshCw, FileDown, UserCheck, Loader2, Layers, BarChart3, FileSpreadsheet, FileText, ChevronDown } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { format, subMonths } from 'date-fns';

const COLORS = ['#4F46E5', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4'];

interface SummaryReport {
  totalFiles: number;
  totalAllocated: number;
  totalToCollect: number;
  totalCollected: number;
  totalOutstanding: number;
  collectionRate: string;
  statusCounts: Record<string, number>;
  promiseStats: {
    total: number;
    pending: number;
    kept: number;
    broken: number;
    totalAmount: number;
  };
  paymentMethodBreakdown: Record<string, number>;
  totalActivities: number;
}

interface AgentPerformance {
  id: string;
  name: string;
  email: string;
  totalFiles: number;
  paidFiles: number;
  totalToCollect: number;
  totalCollected: number;
  collectionRate: string;
  totalActivities: number;
  activityBreakdown: Record<string, number>;
  promisesKept: number;
  promisesTotal: number;
  promiseKeptRate: string;
}

interface BatchAnalysis {
  id: string;
  name: string;
  clientName: string | null;
  isActive: boolean;
  totalFiles: number;
  totalToCollect: number;
  totalCollected: number;
  totalOutstanding: number;
  collectionRate: string;
  targetAmount: number;
  targetProgress: string;
  statusCounts: Record<string, number>;
}

interface PaymentTrend {
  month: string;
  total: number;
  count: number;
  average: number;
}

export default function ReportsPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('summary');

  // Filters
  const [startDate, setStartDate] = useState(format(subMonths(new Date(), 3), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [selectedBatchId, setSelectedBatchId] = useState('');

  // Report data
  const [summary, setSummary] = useState<SummaryReport | null>(null);
  const [agentPerformance, setAgentPerformance] = useState<AgentPerformance[]>([]);
  const [batchAnalysis, setBatchAnalysis] = useState<BatchAnalysis[]>([]);
  const [paymentTrends, setPaymentTrends] = useState<PaymentTrend[]>([]);
  const [batches, setBatches] = useState<{ id: string; name: string }[]>([]);
  const [downloadingAgents, setDownloadingAgents] = useState(false);
  const [downloadingManagers, setDownloadingManagers] = useState(false);
  const [downloadingSummary, setDownloadingSummary] = useState(false);
  const [downloadingBatches, setDownloadingBatches] = useState(false);

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

  const fetchBatches = async () => {
    try {
      const res = await fetch('/api/batches');
      if (res.ok) {
        const data = await res.json();
        setBatches(data.map((b: { id: string; name: string }) => ({ id: b.id, name: b.name })));
      }
    } catch (error) {
      console.error('Error fetching batches:', error);
    }
  };

  const fetchReport = useCallback(async (type: string) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        type,
        startDate,
        endDate,
        ...(selectedBatchId && { batchId: selectedBatchId })
      });

      const res = await fetch(`/api/reports?${params}`);
      if (res.ok) {
        const data = await res.json();
        
        switch (type) {
          case 'summary':
            setSummary(data);
            break;
          case 'agent_performance':
            setAgentPerformance(data.agents);
            break;
          case 'batch_analysis':
            setBatchAnalysis(data.batches);
            break;
          case 'payment_trends':
            setPaymentTrends(data.trends);
            break;
        }
      }
    } catch (error) {
      console.error('Error fetching report:', error);
      toast({ title: 'Error', description: 'Failed to fetch report', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, selectedBatchId, toast]);

  useEffect(() => {
    fetchBatches();
    fetchReport('summary');
    fetchReport('agent_performance');
    fetchReport('batch_analysis');
    fetchReport('payment_trends');
  }, [fetchReport]);

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

  const handleRefresh = () => {
    fetchReport('summary');
    fetchReport('agent_performance');
    fetchReport('batch_analysis');
    fetchReport('payment_trends');
  };

  const handleDownloadReport = async (type: 'agents' | 'managers' | 'summary' | 'batches', format: 'csv' | 'excel' | 'pdf' = 'csv') => {
    const setDownloadingMap = {
      agents: setDownloadingAgents,
      managers: setDownloadingManagers,
      summary: setDownloadingSummary,
      batches: setDownloadingBatches
    };
    const setDownloading = setDownloadingMap[type];
    setDownloading(true);
    
    if (format === 'pdf') {
      toast({ title: 'Generating PDF', description: 'Please wait while the PDF is being generated...' });
    }
    
    try {
      const params = new URLSearchParams({
        type,
        startDate,
        endDate,
        format,
        ...(selectedBatchId && selectedBatchId !== 'all' && { batchId: selectedBatchId })
      });

      const response = await fetch(`/api/reports/download?${params}`);
      
      if (!response.ok) {
        throw new Error('Failed to download report');
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      
      const extensionMap: Record<string, string> = { csv: 'csv', excel: 'xls', pdf: 'pdf' };
      const ext = extensionMap[format];
      const filenameMap: Record<string, string> = {
        agents: `agent_performance_${startDate}_to_${endDate}.${ext}`,
        managers: `manager_performance_${startDate}_to_${endDate}.${ext}`,
        summary: `collection_summary_${startDate}_to_${endDate}.${ext}`,
        batches: `batch_analysis_${startDate}_to_${endDate}.${ext}`
      };
      a.download = filenameMap[type];
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      const formatNameMap: Record<string, string> = { csv: 'CSV', excel: 'Excel', pdf: 'PDF' };
      const descriptionMap: Record<string, string> = {
        agents: `Agent performance ${formatNameMap[format]} downloaded`,
        managers: `Manager performance ${formatNameMap[format]} downloaded`,
        summary: `Collection summary ${formatNameMap[format]} downloaded`,
        batches: `Batch analysis ${formatNameMap[format]} downloaded`
      };
      toast({ title: 'Success', description: descriptionMap[type] });
    } catch (error) {
      console.error('Download error:', error);
      toast({ title: 'Error', description: 'Failed to download report', variant: 'destructive' });
    } finally {
      setDownloading(false);
    }
  };

  // Prepare chart data
  const statusChartData = summary ? Object.entries(summary.statusCounts).map(([name, value]) => ({
    name: name.replace('_', ' '),
    value
  })) : [];

  const paymentMethodData = summary ? Object.entries(summary.paymentMethodBreakdown).map(([name, value]) => ({
    name: name.replace('_', ' '),
    value
  })) : [];

  const trendChartData = paymentTrends.map(t => ({
    month: format(new Date(t.month + '-01'), 'MMM yyyy'),
    amount: t.total,
    count: t.count
  }));

  if (session?.user?.role === 'AGENT') {
    return null;
  }

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold">Reports & Analytics</h1>
            <p className="text-muted-foreground">Comprehensive collection analytics and performance reports</p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleRefresh}>
              <RefreshCw className="h-4 w-4 mr-2" />
              Refresh
            </Button>
          </div>
        </div>

        {/* Filters */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-wrap gap-4 items-end">
              <div>
                <Label>Start Date</Label>
                <Input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-40"
                />
              </div>
              <div>
                <Label>End Date</Label>
                <Input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-40"
                />
              </div>
              <div>
                <Label>Batch</Label>
                <Select value={selectedBatchId} onValueChange={setSelectedBatchId}>
                  <SelectTrigger className="w-48">
                    <SelectValue placeholder="All Batches" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Batches</SelectItem>
                    {batches.map(batch => (
                      <SelectItem key={batch.id} value={batch.id}>
                        {batch.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button onClick={handleRefresh}>Apply Filters</Button>
            </div>
          </CardContent>
        </Card>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList>
            <TabsTrigger value="summary">Summary</TabsTrigger>
            <TabsTrigger value="agents">Agent Performance</TabsTrigger>
            <TabsTrigger value="batches">Batch Analysis</TabsTrigger>
            <TabsTrigger value="trends">Payment Trends</TabsTrigger>
            <TabsTrigger value="downloads">Downloads</TabsTrigger>
          </TabsList>

          {/* Summary Tab */}
          <TabsContent value="summary" className="space-y-6 mt-4">
            <div className="flex justify-end">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button 
                    disabled={downloadingSummary}
                    className="bg-green-600 hover:bg-green-700"
                  >
                    {downloadingSummary ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : (
                      <Download className="h-4 w-4 mr-2" />
                    )}
                    Download Summary
                    <ChevronDown className="h-4 w-4 ml-2" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <DropdownMenuItem onClick={() => handleDownloadReport('summary', 'csv')}>
                    <FileDown className="h-4 w-4 mr-2" /> CSV
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => handleDownloadReport('summary', 'excel')}>
                    <FileSpreadsheet className="h-4 w-4 mr-2" /> Excel
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => handleDownloadReport('summary', 'pdf')}>
                    <FileText className="h-4 w-4 mr-2" /> PDF
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
            {loading ? (
              <div className="text-center py-8">Loading...</div>
            ) : summary ? (
              <>
                {/* Summary Cards */}
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <Card>
                    <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>
                          <p className="text-sm text-muted-foreground">Total Files</p>
                          <p className="text-2xl font-bold">{summary.totalFiles}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-4">
                        <div className="p-2 bg-orange-100 rounded-lg">
                          <DollarSign className="h-6 w-6 text-orange-600" />
                        </div>
                        <div>
                          <p className="text-sm text-muted-foreground">Total To Collect</p>
                          <p className="text-xl font-bold">{formatCurrency(summary.totalToCollect)}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-4">
                        <div className="p-2 bg-green-100 rounded-lg">
                          <TrendingUp className="h-6 w-6 text-green-600" />
                        </div>
                        <div>
                          <p className="text-sm text-muted-foreground">Total Collected</p>
                          <p className="text-xl font-bold text-green-600">{formatCurrency(summary.totalCollected)}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardContent className="pt-6">
                      <div className="flex items-center gap-4">
                        <div className="p-2 bg-purple-100 rounded-lg">
                          <Users className="h-6 w-6 text-purple-600" />
                        </div>
                        <div>
                          <p className="text-sm text-muted-foreground">Collection Rate</p>
                          <p className="text-2xl font-bold">{summary.collectionRate}%</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* Charts */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle>File Status Distribution</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ResponsiveContainer width="100%" height={300}>
                        <PieChart>
                          <Pie
                            data={statusChartData}
                            cx="50%"
                            cy="50%"
                            labelLine={false}
                            label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                            outerRadius={100}
                            fill="#8884d8"
                            dataKey="value"
                          >
                            {statusChartData.map((_, index) => (
                              <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                            ))}
                          </Pie>
                          <Tooltip />
                        </PieChart>
                      </ResponsiveContainer>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle>Payment Methods</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ResponsiveContainer width="100%" height={300}>
                        <BarChart data={paymentMethodData}>
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="name" />
                          <YAxis tickFormatter={(value) => `${(value / 1000).toFixed(0)}K`} />
                          <Tooltip formatter={(value: number) => formatCurrency(value)} />
                          <Bar dataKey="value" fill="#4F46E5" />
                        </BarChart>
                      </ResponsiveContainer>
                    </CardContent>
                  </Card>
                </div>

                {/* Promise Stats */}
                <Card>
                  <CardHeader>
                    <CardTitle>Promise to Pay Summary</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                      <div className="text-center p-4 bg-gray-50 rounded-lg">
                        <p className="text-2xl font-bold">{summary.promiseStats.total}</p>
                        <p className="text-sm text-muted-foreground">Total Promises</p>
                      </div>
                      <div className="text-center p-4 bg-yellow-50 rounded-lg">
                        <p className="text-2xl font-bold text-yellow-600">{summary.promiseStats.pending}</p>
                        <p className="text-sm text-muted-foreground">Pending</p>
                      </div>
                      <div className="text-center p-4 bg-green-50 rounded-lg">
                        <p className="text-2xl font-bold text-green-600">{summary.promiseStats.kept}</p>
                        <p className="text-sm text-muted-foreground">Kept</p>
                      </div>
                      <div className="text-center p-4 bg-red-50 rounded-lg">
                        <p className="text-2xl font-bold text-red-600">{summary.promiseStats.broken}</p>
                        <p className="text-sm text-muted-foreground">Broken</p>
                      </div>
                      <div className="text-center p-4 bg-blue-50 rounded-lg">
                        <p className="text-xl font-bold text-blue-600">{formatCurrency(summary.promiseStats.totalAmount)}</p>
                        <p className="text-sm text-muted-foreground">Total Amount</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </>
            ) : null}
          </TabsContent>

          {/* Agent Performance Tab */}
          <TabsContent value="agents" className="mt-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between">
                <div>
                  <CardTitle>Agent Performance</CardTitle>
                  <CardDescription>Collection performance by agent</CardDescription>
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button 
                      disabled={downloadingAgents}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      {downloadingAgents ? (
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      ) : (
                        <Download className="h-4 w-4 mr-2" />
                      )}
                      Download
                      <ChevronDown className="h-4 w-4 ml-2" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent>
                    <DropdownMenuItem onClick={() => handleDownloadReport('agents', 'csv')}>
                      <FileDown className="h-4 w-4 mr-2" /> CSV
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleDownloadReport('agents', 'excel')}>
                      <FileSpreadsheet className="h-4 w-4 mr-2" /> Excel
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleDownloadReport('agents', 'pdf')}>
                      <FileText className="h-4 w-4 mr-2" /> PDF
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </CardHeader>
              <CardContent>
                {loading ? (
                  <div className="text-center py-8">Loading...</div>
                ) : (
                  <>
                    <ResponsiveContainer width="100%" height={300}>
                      <BarChart data={agentPerformance} layout="vertical">
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis type="number" domain={[0, 100]} tickFormatter={(v) => `${v}%`} />
                        <YAxis dataKey="name" type="category" width={100} />
                        <Tooltip formatter={(value: number) => `${value}%`} />
                        <Bar dataKey="collectionRate" fill="#4F46E5" name="Collection Rate" />
                      </BarChart>
                    </ResponsiveContainer>

                    <Table className="mt-6">
                      <TableHeader>
                        <TableRow>
                          <TableHead>Agent</TableHead>
                          <TableHead className="text-right">Files</TableHead>
                          <TableHead className="text-right">Paid</TableHead>
                          <TableHead className="text-right">To Collect</TableHead>
                          <TableHead className="text-right">Collected</TableHead>
                          <TableHead className="text-right">Rate</TableHead>
                          <TableHead className="text-right">Activities</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {agentPerformance.map((agent) => (
                          <TableRow key={agent.id}>
                            <TableCell className="font-medium">{agent.name}</TableCell>
                            <TableCell className="text-right">{agent.totalFiles}</TableCell>
                            <TableCell className="text-right text-green-600">{agent.paidFiles}</TableCell>
                            <TableCell className="text-right">{formatCurrency(agent.totalToCollect)}</TableCell>
                            <TableCell className="text-right">{formatCurrency(agent.totalCollected)}</TableCell>
                            <TableCell className="text-right">
                              <Badge variant={parseFloat(agent.collectionRate) >= 50 ? 'default' : 'secondary'}>
                                {agent.collectionRate}%
                              </Badge>
                            </TableCell>
                            <TableCell className="text-right">{agent.totalActivities}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Batch Analysis Tab */}
          <TabsContent value="batches" className="mt-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between">
                <div>
                  <CardTitle>Batch Analysis</CardTitle>
                  <CardDescription>Performance breakdown by batch</CardDescription>
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button 
                      disabled={downloadingBatches}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      {downloadingBatches ? (
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      ) : (
                        <Download className="h-4 w-4 mr-2" />
                      )}
                      Download
                      <ChevronDown className="h-4 w-4 ml-2" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent>
                    <DropdownMenuItem onClick={() => handleDownloadReport('batches', 'csv')}>
                      <FileDown className="h-4 w-4 mr-2" /> CSV
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleDownloadReport('batches', 'excel')}>
                      <FileSpreadsheet className="h-4 w-4 mr-2" /> Excel
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => handleDownloadReport('batches', 'pdf')}>
                      <FileText className="h-4 w-4 mr-2" /> PDF
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </CardHeader>
              <CardContent>
                {loading ? (
                  <div className="text-center py-8">Loading...</div>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Batch</TableHead>
                        <TableHead>Client</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead className="text-right">Files</TableHead>
                        <TableHead className="text-right">To Collect</TableHead>
                        <TableHead className="text-right">Collected</TableHead>
                        <TableHead className="text-right">Outstanding</TableHead>
                        <TableHead className="text-right">Rate</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {batchAnalysis.map((batch) => (
                        <TableRow key={batch.id}>
                          <TableCell className="font-medium">{batch.name}</TableCell>
                          <TableCell>{batch.clientName || '-'}</TableCell>
                          <TableCell>
                            <Badge variant={batch.isActive ? 'default' : 'secondary'}>
                              {batch.isActive ? 'Active' : 'Inactive'}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">{batch.totalFiles}</TableCell>
                          <TableCell className="text-right">{formatCurrency(batch.totalToCollect)}</TableCell>
                          <TableCell className="text-right text-green-600">{formatCurrency(batch.totalCollected)}</TableCell>
                          <TableCell className="text-right text-orange-600">{formatCurrency(batch.totalOutstanding)}</TableCell>
                          <TableCell className="text-right">
                            <Badge variant={parseFloat(batch.collectionRate) >= 50 ? 'default' : 'secondary'}>
                              {batch.collectionRate}%
                            </Badge>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Payment Trends Tab */}
          <TabsContent value="trends" className="mt-4">
            <Card>
              <CardHeader>
                <CardTitle>Payment Trends</CardTitle>
                <CardDescription>Monthly payment collection trends</CardDescription>
              </CardHeader>
              <CardContent>
                {loading ? (
                  <div className="text-center py-8">Loading...</div>
                ) : (
                  <>
                    <ResponsiveContainer width="100%" height={400}>
                      <AreaChart data={trendChartData}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="month" />
                        <YAxis tickFormatter={(value) => `${(value / 1000).toFixed(0)}K`} />
                        <Tooltip formatter={(value: number) => formatCurrency(value)} />
                        <Legend />
                        <Area
                          type="monotone"
                          dataKey="amount"
                          stroke="#4F46E5"
                          fill="#4F46E5"
                          fillOpacity={0.3}
                          name="Amount Collected"
                        />
                      </AreaChart>
                    </ResponsiveContainer>

                    <div className="grid grid-cols-3 gap-4 mt-6">
                      {trendChartData.map((trend, index) => (
                        <Card key={index}>
                          <CardContent className="pt-4">
                            <p className="text-sm font-medium text-muted-foreground">{trend.month}</p>
                            <p className="text-xl font-bold">{formatCurrency(trend.amount)}</p>
                            <p className="text-xs text-muted-foreground">{trend.count} payments</p>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Downloads Tab */}
          <TabsContent value="downloads" className="mt-4">
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <FileDown className="h-5 w-5" />
                    Report Downloads
                  </CardTitle>
                  <CardDescription>
                    Download comprehensive reports for the selected date range in CSV, Excel, or PDF format
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Summary Report Download Card */}
                    <Card className="border-2 border-green-200 bg-green-50/50">
                      <CardContent className="pt-6">
                        <div className="flex flex-col items-center text-center space-y-4">
                          <div className="p-4 bg-green-100 rounded-full">
                            <BarChart3 className="h-10 w-10 text-green-600" />
                          </div>
                          <div>
                            <h3 className="text-lg font-semibold">Collection Summary Report</h3>
                            <p className="text-sm text-muted-foreground mt-1">
                              Download overall collection performance summary
                            </p>
                          </div>
                          <div className="text-xs text-muted-foreground bg-white p-3 rounded-lg w-full">
                            <p className="font-medium mb-2">Includes:</p>
                            <ul className="space-y-1 text-left">
                              <li>• Total files, allocated & collected amounts</li>
                              <li>• File status breakdown</li>
                              <li>• Promise to pay statistics</li>
                              <li>• Payment method breakdown</li>
                            </ul>
                          </div>
                          <div className="text-sm text-muted-foreground">
                            Period: <span className="font-medium">{startDate}</span> to <span className="font-medium">{endDate}</span>
                          </div>
                          <div className="flex gap-2 w-full">
                            <Button 
                              onClick={() => handleDownloadReport('summary', 'csv')}
                              disabled={downloadingSummary}
                              className="flex-1 bg-green-600 hover:bg-green-700"
                              size="sm"
                            >
                              {downloadingSummary ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileDown className="h-4 w-4 mr-1" />}
                              CSV
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('summary', 'excel')}
                              disabled={downloadingSummary}
                              className="flex-1 bg-green-600 hover:bg-green-700"
                              size="sm"
                            >
                              {downloadingSummary ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileSpreadsheet className="h-4 w-4 mr-1" />}
                              Excel
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('summary', 'pdf')}
                              disabled={downloadingSummary}
                              className="flex-1 bg-green-600 hover:bg-green-700"
                              size="sm"
                            >
                              {downloadingSummary ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4 mr-1" />}
                              PDF
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    {/* Batch Analysis Download Card */}
                    <Card className="border-2 border-orange-200 bg-orange-50/50">
                      <CardContent className="pt-6">
                        <div className="flex flex-col items-center text-center space-y-4">
                          <div className="p-4 bg-orange-100 rounded-full">
                            <Layers className="h-10 w-10 text-orange-600" />
                          </div>
                          <div>
                            <h3 className="text-lg font-semibold">Batch Analysis Report</h3>
                            <p className="text-sm text-muted-foreground mt-1">
                              Download performance breakdown by batch
                            </p>
                          </div>
                          <div className="text-xs text-muted-foreground bg-white p-3 rounded-lg w-full">
                            <p className="font-medium mb-2">Includes:</p>
                            <ul className="space-y-1 text-left">
                              <li>• Batch names & client assignments</li>
                              <li>• Files per batch & collection rates</li>
                              <li>• Target amounts & progress</li>
                              <li>• Outstanding balances per batch</li>
                            </ul>
                          </div>
                          <div className="text-sm text-muted-foreground">
                            Period: <span className="font-medium">{startDate}</span> to <span className="font-medium">{endDate}</span>
                          </div>
                          <div className="flex gap-2 w-full">
                            <Button 
                              onClick={() => handleDownloadReport('batches', 'csv')}
                              disabled={downloadingBatches}
                              className="flex-1 bg-orange-600 hover:bg-orange-700"
                              size="sm"
                            >
                              {downloadingBatches ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileDown className="h-4 w-4 mr-1" />}
                              CSV
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('batches', 'excel')}
                              disabled={downloadingBatches}
                              className="flex-1 bg-orange-600 hover:bg-orange-700"
                              size="sm"
                            >
                              {downloadingBatches ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileSpreadsheet className="h-4 w-4 mr-1" />}
                              Excel
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('batches', 'pdf')}
                              disabled={downloadingBatches}
                              className="flex-1 bg-orange-600 hover:bg-orange-700"
                              size="sm"
                            >
                              {downloadingBatches ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4 mr-1" />}
                              PDF
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    {/* Agent Performance Download Card */}
                    <Card className="border-2 border-blue-200 bg-blue-50/50">
                      <CardContent className="pt-6">
                        <div className="flex flex-col items-center text-center space-y-4">
                          <div className="p-4 bg-blue-100 rounded-full">
                            <Users className="h-10 w-10 text-blue-600" />
                          </div>
                          <div>
                            <h3 className="text-lg font-semibold">Agent Performance Report</h3>
                            <p className="text-sm text-muted-foreground mt-1">
                              Download detailed performance metrics for all collection agents
                            </p>
                          </div>
                          <div className="text-xs text-muted-foreground bg-white p-3 rounded-lg w-full">
                            <p className="font-medium mb-2">Includes:</p>
                            <ul className="space-y-1 text-left">
                              <li>• Total files assigned & collection rates</li>
                              <li>• Calls made & SMS sent</li>
                              <li>• Promises kept/broken statistics</li>
                              <li>• Total amounts collected per agent</li>
                            </ul>
                          </div>
                          <div className="text-sm text-muted-foreground">
                            Period: <span className="font-medium">{startDate}</span> to <span className="font-medium">{endDate}</span>
                          </div>
                          <div className="flex gap-2 w-full">
                            <Button 
                              onClick={() => handleDownloadReport('agents', 'csv')}
                              disabled={downloadingAgents}
                              className="flex-1 bg-blue-600 hover:bg-blue-700"
                              size="sm"
                            >
                              {downloadingAgents ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileDown className="h-4 w-4 mr-1" />}
                              CSV
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('agents', 'excel')}
                              disabled={downloadingAgents}
                              className="flex-1 bg-blue-600 hover:bg-blue-700"
                              size="sm"
                            >
                              {downloadingAgents ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileSpreadsheet className="h-4 w-4 mr-1" />}
                              Excel
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('agents', 'pdf')}
                              disabled={downloadingAgents}
                              className="flex-1 bg-blue-600 hover:bg-blue-700"
                              size="sm"
                            >
                              {downloadingAgents ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4 mr-1" />}
                              PDF
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    {/* Manager Performance Download Card */}
                    <Card className="border-2 border-purple-200 bg-purple-50/50">
                      <CardContent className="pt-6">
                        <div className="flex flex-col items-center text-center space-y-4">
                          <div className="p-4 bg-purple-100 rounded-full">
                            <UserCheck className="h-10 w-10 text-purple-600" />
                          </div>
                          <div>
                            <h3 className="text-lg font-semibold">Manager Performance Report</h3>
                            <p className="text-sm text-muted-foreground mt-1">
                              Download performance metrics for all team managers
                            </p>
                          </div>
                          <div className="text-xs text-muted-foreground bg-white p-3 rounded-lg w-full">
                            <p className="font-medium mb-2">Includes:</p>
                            <ul className="space-y-1 text-left">
                              <li>• Agents managed & files overseen</li>
                              <li>• Team collection rates</li>
                              <li>• Average agent performance</li>
                              <li>• Top & lowest performing agents</li>
                            </ul>
                          </div>
                          <div className="text-sm text-muted-foreground">
                            Period: <span className="font-medium">{startDate}</span> to <span className="font-medium">{endDate}</span>
                          </div>
                          <div className="flex gap-2 w-full">
                            <Button 
                              onClick={() => handleDownloadReport('managers', 'csv')}
                              disabled={downloadingManagers}
                              className="flex-1 bg-purple-600 hover:bg-purple-700"
                              size="sm"
                            >
                              {downloadingManagers ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileDown className="h-4 w-4 mr-1" />}
                              CSV
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('managers', 'excel')}
                              disabled={downloadingManagers}
                              className="flex-1 bg-purple-600 hover:bg-purple-700"
                              size="sm"
                            >
                              {downloadingManagers ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileSpreadsheet className="h-4 w-4 mr-1" />}
                              Excel
                            </Button>
                            <Button 
                              onClick={() => handleDownloadReport('managers', 'pdf')}
                              disabled={downloadingManagers}
                              className="flex-1 bg-purple-600 hover:bg-purple-700"
                              size="sm"
                            >
                              {downloadingManagers ? <Loader2 className="h-4 w-4 animate-spin" /> : <FileText className="h-4 w-4 mr-1" />}
                              PDF
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                    <p className="text-sm text-muted-foreground">
                      <strong>Note:</strong> Reports are generated based on the date range selected in the filters above. 
                      CSV and Excel files can be opened in spreadsheet applications, while PDF provides a print-ready format.
                    </p>
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </ProtectedLayout>
  );
}
