"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ProtectedLayout } from "@/components/protected-layout";
import { FileText, DollarSign, TrendingUp, AlertCircle, Users, Clock, RefreshCw, Phone, MessageSquare, Zap, Calendar, Eye, User, X } from "lucide-react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  Legend,
} from "recharts";

interface DashboardStats {
  totalFiles: number;
  totalToCollect: number;
  totalCollected: number;
  outstandingBalance: number;
  collectionRate: number;
  statusBreakdown: {
    NEW: number;
    IN_PROGRESS: number;
    PAID: number;
    DEFAULTED: number;
  };
  pendingPromises: number;
}

interface AgentPerformance {
  id: string;
  name: string;
  totalFiles: number;
  totalToCollect: number;
  totalCollected: number;
  collectionRate: number;
}

interface CollectionTrend {
  month: string;
  amount: number;
}

interface RecentFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  status: string;
  outstandingBalance: number;
  createdAt: string;
}

interface RealtimeData {
  timestamp: string;
  today: {
    collected: number;
    paymentsCount: number;
    promisesAmount: number;
    promisesCount: number;
    activities: Record<string, number>;
    totalActivities: number;
  };
  overall: {
    totalFiles: number;
    totalToCollect: number;
    totalOutstanding: number;
    totalCollected: number;
    collectionRate: string;
  };
  recentPayments: Array<{
    id: string;
    amount: number;
    method: string;
    customerName: string;
    agentName: string;
    createdAt: string;
  }>;
  pendingPromises: Array<{
    id: string;
    amount: number;
    customerName: string;
    phoneNumber: string;
    agentName: string;
    promisedDate: string;
  }>;
  topAgents: Array<{
    id: string;
    name: string;
    todayCollected: number;
    callsMade: number;
    totalActivities: number;
  }>;
}

const COLORS = ["#3b82f6", "#eab308", "#22c55e", "#ef4444"];

interface DetailItem {
  id: string;
  [key: string]: unknown;
}

interface UserSummary {
  name: string;
  role: string;
  count: number;
  amount?: number;
  outstanding?: number;
  totalToCollect?: number;
  collected?: number;
  types?: Record<string, number>;
}

interface DetailsSummary {
  total?: number;
  totalToCollect?: number;
  totalCollected?: number;
  count: number;
  byUser?: UserSummary[];
  byAgent?: UserSummary[];
  byType?: Record<string, number>;
  byStatus?: Record<string, { count: number; amount: number }>;
}

interface DetailsResponse {
  category: string;
  period: string;
  data: DetailItem[];
  summary: DetailsSummary;
  isAdmin: boolean;
  isManager: boolean;
  userRole: string;
}

export default function DashboardPage() {
  const { data: session } = useSession() || {};
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [agentPerformance, setAgentPerformance] = useState<AgentPerformance[]>([]);
  const [collectionTrends, setCollectionTrends] = useState<CollectionTrend[]>([]);
  const [recentFiles, setRecentFiles] = useState<RecentFile[]>([]);
  const [realtimeData, setRealtimeData] = useState<RealtimeData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  
  // Details dialog state
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [detailsCategory, setDetailsCategory] = useState<string>("");
  const [detailsTitle, setDetailsTitle] = useState<string>("");
  const [detailsData, setDetailsData] = useState<DetailsResponse | null>(null);
  const [detailsLoading, setDetailsLoading] = useState(false);

  const fetchDashboardData = useCallback(async () => {
    try {
      const res = await fetch("/api/dashboard");
      if (res.ok) {
        const data = await res.json();
        setStats(data.stats);
        setAgentPerformance(data.agentPerformance || []);
        setCollectionTrends(data.collectionTrends || []);
        setRecentFiles(data.recentFiles || []);
      }
    } catch (error) {
      console.error("Error fetching dashboard data:", error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchRealtimeData = useCallback(async () => {
    try {
      setIsRefreshing(true);
      const res = await fetch("/api/dashboard/realtime");
      if (res.ok) {
        const data = await res.json();
        setRealtimeData(data);
        setLastUpdated(new Date());
      }
    } catch (error) {
      console.error("Error fetching realtime data:", error);
    } finally {
      setIsRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchDashboardData();
    fetchRealtimeData();
  }, [fetchDashboardData, fetchRealtimeData]);

  // Auto-refresh every 30 seconds when enabled
  useEffect(() => {
    if (!autoRefresh) return;
    
    const interval = setInterval(() => {
      fetchRealtimeData();
    }, 30000);

    return () => clearInterval(interval);
  }, [autoRefresh, fetchRealtimeData]);

  // Fetch details for a category
  const fetchDetails = useCallback(async (category: string, title: string, period: string = 'today') => {
    setDetailsCategory(category);
    setDetailsTitle(title);
    setDetailsDialogOpen(true);
    setDetailsLoading(true);
    setDetailsData(null);
    
    try {
      const res = await fetch(`/api/dashboard/details?category=${category}&period=${period}`);
      if (res.ok) {
        const data = await res.json();
        setDetailsData(data);
      }
    } catch (error) {
      console.error("Error fetching details:", error);
    } finally {
      setDetailsLoading(false);
    }
  }, []);

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

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

  const formatShortCurrency = (amount: number) => {
    if (amount >= 1000000) return `KES ${(amount / 1000000).toFixed(1)}M`;
    if (amount >= 1000) return `KES ${(amount / 1000).toFixed(0)}K`;
    return formatCurrency(amount);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "NEW": return "bg-blue-100 text-blue-800";
      case "IN_PROGRESS": return "bg-yellow-100 text-yellow-800";
      case "PAID": return "bg-green-100 text-green-800";
      case "DEFAULTED": return "bg-red-100 text-red-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const statusData = stats ? [
    { name: "New", value: stats.statusBreakdown.NEW, color: "#3b82f6" },
    { name: "In Progress", value: stats.statusBreakdown.IN_PROGRESS, color: "#eab308" },
    { name: "Paid", value: stats.statusBreakdown.PAID, color: "#22c55e" },
    { name: "Defaulted", value: stats.statusBreakdown.DEFAULTED, color: "#ef4444" },
  ].filter(d => d.value > 0) : [];

  const isAdminOrManager = session?.user?.role === "ADMIN" || session?.user?.role === "MANAGER";

  if (isLoading) {
    return (
      <ProtectedLayout>
        <div className="flex h-screen items-center justify-center">
          <div className="text-lg">Loading dashboard...</div>
        </div>
      </ProtectedLayout>
    );
  }

  return (
    <ProtectedLayout>
      <div className="p-8">
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
            <p className="text-gray-600 mt-1">
              Welcome back, {session?.user?.name}! Here&apos;s your collection overview.
            </p>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <Switch
                id="auto-refresh"
                checked={autoRefresh}
                onCheckedChange={setAutoRefresh}
              />
              <Label htmlFor="auto-refresh" className="text-sm">Auto-refresh</Label>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={fetchRealtimeData}
              disabled={isRefreshing}
            >
              <RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
              Refresh
            </Button>
            {lastUpdated && (
              <span className="text-xs text-muted-foreground">
                Last updated: {lastUpdated.toLocaleTimeString()}
              </span>
            )}
          </div>
        </div>

        {/* Today's Live Activity - Real-time Section */}
        {realtimeData && (
          <div className="mb-8">
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Zap className="h-5 w-5 text-yellow-500" />
              Today&apos;s Activity
              <Badge variant="outline" className="ml-2 animate-pulse bg-green-50">LIVE</Badge>
              <span className="text-xs text-muted-foreground ml-2">(Click any card to view details)</span>
            </h2>
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
              <Card 
                className="border-green-200 bg-green-50/50 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => fetchDetails('collections', "Today's Collections", 'today')}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Today&apos;s Collections</CardTitle>
                  <div className="flex items-center gap-1">
                    <Eye className="h-3 w-3 text-muted-foreground" />
                    <DollarSign className="h-4 w-4 text-green-600" />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-green-600">
                    {formatCurrency(realtimeData.today.collected)}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {realtimeData.today.paymentsCount} payments received
                  </p>
                </CardContent>
              </Card>

              <Card 
                className="border-blue-200 bg-blue-50/50 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => fetchDetails('promises', "Promises Made", 'today')}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Promises Made</CardTitle>
                  <div className="flex items-center gap-1">
                    <Eye className="h-3 w-3 text-muted-foreground" />
                    <Calendar className="h-4 w-4 text-blue-600" />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-blue-600">
                    {realtimeData.today.promisesCount}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {formatCurrency(realtimeData.today.promisesAmount)} promised
                  </p>
                </CardContent>
              </Card>

              <Card 
                className="border-purple-200 bg-purple-50/50 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => fetchDetails('calls', "Calls Made", 'today')}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Calls Made</CardTitle>
                  <div className="flex items-center gap-1">
                    <Eye className="h-3 w-3 text-muted-foreground" />
                    <Phone className="h-4 w-4 text-purple-600" />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-purple-600">
                    {realtimeData.today.activities?.CALL || 0}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Today&apos;s outbound calls
                  </p>
                </CardContent>
              </Card>

              <Card 
                className="border-orange-200 bg-orange-50/50 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => fetchDetails('sms', "SMS Sent", 'today')}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">SMS Sent</CardTitle>
                  <div className="flex items-center gap-1">
                    <Eye className="h-3 w-3 text-muted-foreground" />
                    <MessageSquare className="h-4 w-4 text-orange-600" />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-orange-600">
                    {realtimeData.today.activities?.SMS || 0}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Messages sent today
                  </p>
                </CardContent>
              </Card>

              <Card 
                className="border-gray-200 bg-gray-50/50 cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => fetchDetails('activities', "Total Activities", 'today')}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Total Activities</CardTitle>
                  <div className="flex items-center gap-1">
                    <Eye className="h-3 w-3 text-muted-foreground" />
                    <Clock className="h-4 w-4 text-gray-600" />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-gray-600">
                    {realtimeData.today.totalActivities}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    All interactions today
                  </p>
                </CardContent>
              </Card>
            </div>
          </div>
        )}

        {/* Summary Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-8">
          <Card 
            className="cursor-pointer hover:shadow-md transition-shadow"
            onClick={() => fetchDetails('files', "Total Files", 'all')}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Files</CardTitle>
              <div className="flex items-center gap-1">
                <Eye className="h-3 w-3 text-muted-foreground" />
                <FileText className="h-4 w-4 text-muted-foreground" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.totalFiles || 0}</div>
              <p className="text-xs text-muted-foreground">Active collection files</p>
            </CardContent>
          </Card>

          <Card 
            className="cursor-pointer hover:shadow-md transition-shadow"
            onClick={() => fetchDetails('tocollect', "Total to Collect", 'all')}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total to Collect</CardTitle>
              <div className="flex items-center gap-1">
                <Eye className="h-3 w-3 text-muted-foreground" />
                <DollarSign className="h-4 w-4 text-muted-foreground" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatShortCurrency(stats?.totalToCollect || 0)}</div>
              <p className="text-xs text-muted-foreground">Target amount</p>
            </CardContent>
          </Card>

          <Card 
            className="cursor-pointer hover:shadow-md transition-shadow"
            onClick={() => fetchDetails('collected', "Total Collected", 'all')}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Collected</CardTitle>
              <div className="flex items-center gap-1">
                <Eye className="h-3 w-3 text-muted-foreground" />
                <TrendingUp className="h-4 w-4 text-green-600" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{formatShortCurrency(stats?.totalCollected || 0)}</div>
              <p className="text-xs text-muted-foreground">{(stats?.collectionRate || 0).toFixed(1)}% collection rate</p>
            </CardContent>
          </Card>

          <Card 
            className="cursor-pointer hover:shadow-md transition-shadow"
            onClick={() => fetchDetails('outstanding', "Outstanding Balance", 'all')}
          >
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Outstanding</CardTitle>
              <div className="flex items-center gap-1">
                <Eye className="h-3 w-3 text-muted-foreground" />
                <AlertCircle className="h-4 w-4 text-red-600" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-600">{formatShortCurrency(stats?.outstandingBalance || 0)}</div>
              <p className="text-xs text-muted-foreground">{stats?.pendingPromises || 0} pending promises</p>
            </CardContent>
          </Card>
        </div>

        {/* Charts Row */}
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 mb-8">
          {/* Status Distribution */}
          <Card>
            <CardHeader>
              <CardTitle>Status Distribution</CardTitle>
              <CardDescription>Files by current status</CardDescription>
            </CardHeader>
            <CardContent>
              {statusData.length > 0 ? (
                <div className="h-[200px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={statusData}
                        cx="50%"
                        cy="50%"
                        innerRadius={40}
                        outerRadius={80}
                        paddingAngle={2}
                        dataKey="value"
                        label={({ name, value }) => `${name}: ${value}`}
                      >
                        {statusData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              ) : (
                <div className="h-[200px] flex items-center justify-center text-gray-500">No data</div>
              )}
            </CardContent>
          </Card>

          {/* Collection Trends */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>Collection Trends</CardTitle>
              <CardDescription>Monthly collections over the last 6 months</CardDescription>
            </CardHeader>
            <CardContent>
              {collectionTrends.length > 0 ? (
                <div className="h-[200px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={collectionTrends}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                      <YAxis tickFormatter={(value) => formatShortCurrency(value)} tick={{ fontSize: 12 }} />
                      <Tooltip formatter={(value: number) => formatCurrency(value)} />
                      <Line type="monotone" dataKey="amount" stroke="#22c55e" strokeWidth={2} dot={{ fill: "#22c55e" }} />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              ) : (
                <div className="h-[200px] flex items-center justify-center text-gray-500">No data</div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Agent Performance (Admin/Manager only) */}
        {isAdminOrManager && agentPerformance.length > 0 && (
          <Card className="mb-8">
            <CardHeader>
              <CardTitle className="flex items-center gap-2"><Users className="h-5 w-5" />Agent Performance</CardTitle>
              <CardDescription>Collection performance by agent</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={agentPerformance} layout="vertical" margin={{ left: 100 }}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" tickFormatter={(value) => formatShortCurrency(value)} />
                    <YAxis type="category" dataKey="name" tick={{ fontSize: 12 }} />
                    <Tooltip formatter={(value: number) => formatCurrency(value)} />
                    <Legend />
                    <Bar dataKey="totalCollected" name="Collected" fill="#22c55e" />
                    <Bar dataKey="totalToCollect" name="Target" fill="#e5e7eb" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
              <div className="mt-4 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {agentPerformance.map((agent) => (
                  <div key={agent.id} className="p-4 border rounded-lg">
                    <p className="font-semibold">{agent.name}</p>
                    <div className="mt-2 space-y-1 text-sm">
                      <p>Files: {agent.totalFiles}</p>
                      <p>Collected: {formatCurrency(agent.totalCollected)}</p>
                      <p className="flex items-center gap-2">
                        Rate: 
                        <span className={agent.collectionRate >= 50 ? "text-green-600 font-semibold" : "text-yellow-600 font-semibold"}>
                          {agent.collectionRate.toFixed(1)}%
                        </span>
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Recent Files */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Recent Files</CardTitle>
              <CardDescription>Latest collection files added</CardDescription>
            </div>
            <Link href="/files" className="text-sm text-blue-600 hover:underline">View all</Link>
          </CardHeader>
          <CardContent>
            {recentFiles.length === 0 ? (
              <p className="text-gray-500 text-center py-4">No files found.</p>
            ) : (
              <div className="space-y-4">
                {recentFiles.map((file) => (
                  <Link key={file.id} href={`/files/${file.id}`} className="block">
                    <div className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors">
                      <div>
                        <p className="font-medium">{file.customerName}</p>
                        <p className="text-sm text-gray-500">{file.phoneNumber}</p>
                      </div>
                      <div className="text-right">
                        <Badge className={getStatusColor(file.status)}>{file.status.replace("_", " ")}</Badge>
                        <p className="text-sm font-medium mt-1">{formatCurrency(file.outstandingBalance)} due</p>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Details Dialog */}
        <Dialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
          <DialogContent className="max-w-4xl max-h-[85vh]">
            <DialogHeader>
              <DialogTitle className="flex items-center justify-between">
                <span className="flex items-center gap-2">
                  <Eye className="h-5 w-5" />
                  {detailsTitle}
                </span>
                <Button variant="ghost" size="icon" onClick={() => setDetailsDialogOpen(false)}>
                  <X className="h-4 w-4" />
                </Button>
              </DialogTitle>
            </DialogHeader>
            
            {detailsLoading ? (
              <div className="flex items-center justify-center py-12">
                <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : detailsData ? (
              <Tabs defaultValue="details" className="w-full">
                <TabsList className="mb-4">
                  <TabsTrigger value="details">Details</TabsTrigger>
                  {(detailsData.isAdmin || detailsData.isManager) && (
                    <TabsTrigger value="breakdown">By User/Agent</TabsTrigger>
                  )}
                </TabsList>

                {/* Summary Section */}
                <div className="mb-4 p-4 bg-muted rounded-lg">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                      <p className="text-xs text-muted-foreground">Total Records</p>
                      <p className="text-lg font-bold">{detailsData.summary.count}</p>
                    </div>
                    {detailsData.summary.total !== undefined && (
                      <div>
                        <p className="text-xs text-muted-foreground">Total Amount</p>
                        <p className="text-lg font-bold text-green-600">{formatCurrency(detailsData.summary.total)}</p>
                      </div>
                    )}
                    {detailsData.summary.totalToCollect !== undefined && (
                      <div>
                        <p className="text-xs text-muted-foreground">To Collect</p>
                        <p className="text-lg font-bold">{formatCurrency(detailsData.summary.totalToCollect)}</p>
                      </div>
                    )}
                    {detailsData.summary.totalCollected !== undefined && (
                      <div>
                        <p className="text-xs text-muted-foreground">Collected</p>
                        <p className="text-lg font-bold text-green-600">{formatCurrency(detailsData.summary.totalCollected)}</p>
                      </div>
                    )}
                  </div>
                </div>

                <TabsContent value="details">
                  <ScrollArea className="h-[400px]">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          {detailsCategory === 'collections' || detailsCategory === 'collected' ? (
                            <>
                              <TableHead>Customer</TableHead>
                              <TableHead>Amount</TableHead>
                              <TableHead>Method</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Recorded By</TableHead>}
                              <TableHead>Date</TableHead>
                            </>
                          ) : detailsCategory === 'promises' ? (
                            <>
                              <TableHead>Customer</TableHead>
                              <TableHead>Amount</TableHead>
                              <TableHead>Status</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Agent</TableHead>}
                              <TableHead>Promise Date</TableHead>
                            </>
                          ) : detailsCategory === 'calls' ? (
                            <>
                              <TableHead>Customer</TableHead>
                              <TableHead>Phone</TableHead>
                              <TableHead>Outcome</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Agent</TableHead>}
                              <TableHead>Date</TableHead>
                            </>
                          ) : detailsCategory === 'sms' ? (
                            <>
                              <TableHead>Phone</TableHead>
                              <TableHead>Message</TableHead>
                              <TableHead>Status</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Sent By</TableHead>}
                              <TableHead>Date</TableHead>
                            </>
                          ) : detailsCategory === 'activities' ? (
                            <>
                              <TableHead>Type</TableHead>
                              <TableHead>Customer</TableHead>
                              <TableHead>Outcome</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Agent</TableHead>}
                              <TableHead>Date</TableHead>
                            </>
                          ) : (
                            <>
                              <TableHead>Customer</TableHead>
                              <TableHead>Phone</TableHead>
                              <TableHead>Status</TableHead>
                              {(detailsData.isAdmin || detailsData.isManager) && <TableHead>Agent</TableHead>}
                              <TableHead>Amount</TableHead>
                            </>
                          )}
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {detailsData.data.map((item) => (
                          <TableRow key={item.id}>
                            {detailsCategory === 'collections' || detailsCategory === 'collected' ? (
                              <>
                                <TableCell>
                                  <div>
                                    <p className="font-medium">{String(item.customerName)}</p>
                                    <p className="text-xs text-muted-foreground">{String(item.phoneNumber)}</p>
                                  </div>
                                </TableCell>
                                <TableCell className="font-medium text-green-600">
                                  {formatCurrency(Number(item.amount))}
                                </TableCell>
                                <TableCell>
                                  <Badge variant="outline">{String(item.method)}</Badge>
                                </TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell className="text-sm">
                                  {new Date(String(item.date)).toLocaleDateString()}
                                </TableCell>
                              </>
                            ) : detailsCategory === 'promises' ? (
                              <>
                                <TableCell>
                                  <div>
                                    <p className="font-medium">{String(item.customerName)}</p>
                                    <p className="text-xs text-muted-foreground">{String(item.phoneNumber)}</p>
                                  </div>
                                </TableCell>
                                <TableCell className="font-medium text-blue-600">
                                  {formatCurrency(Number(item.amount))}
                                </TableCell>
                                <TableCell>
                                  <Badge variant={String(item.status) === 'FULFILLED' ? 'default' : 'outline'}>
                                    {String(item.status)}
                                  </Badge>
                                </TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell className="text-sm">
                                  {new Date(String(item.promisedDate)).toLocaleDateString()}
                                </TableCell>
                              </>
                            ) : detailsCategory === 'calls' ? (
                              <>
                                <TableCell className="font-medium">{String(item.customerName)}</TableCell>
                                <TableCell>{String(item.phoneNumber)}</TableCell>
                                <TableCell>
                                  <Badge variant="outline">{String(item.outcome) || 'N/A'}</Badge>
                                </TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell className="text-sm">
                                  {new Date(String(item.date)).toLocaleDateString()}
                                </TableCell>
                              </>
                            ) : detailsCategory === 'sms' ? (
                              <>
                                <TableCell>{String(item.phoneNumber)}</TableCell>
                                <TableCell>
                                  <p className="truncate max-w-[200px]" title={String(item.message)}>
                                    {String(item.message)}
                                  </p>
                                </TableCell>
                                <TableCell>
                                  <Badge variant={String(item.status) === 'SENT' ? 'default' : 'outline'}>
                                    {String(item.status)}
                                  </Badge>
                                </TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell className="text-sm">
                                  {new Date(String(item.date)).toLocaleDateString()}
                                </TableCell>
                              </>
                            ) : detailsCategory === 'activities' ? (
                              <>
                                <TableCell>
                                  <Badge variant="outline">{String(item.type)}</Badge>
                                </TableCell>
                                <TableCell className="font-medium">{String(item.customerName)}</TableCell>
                                <TableCell>{String(item.outcome) || 'N/A'}</TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell className="text-sm">
                                  {new Date(String(item.date)).toLocaleDateString()}
                                </TableCell>
                              </>
                            ) : (
                              <>
                                <TableCell>
                                  <Link href={`/files/${item.id}`} className="text-blue-600 hover:underline font-medium">
                                    {String(item.customerName)}
                                  </Link>
                                </TableCell>
                                <TableCell>{String(item.phoneNumber)}</TableCell>
                                <TableCell>
                                  <Badge className={getStatusColor(String(item.status))}>
                                    {String(item.status).replace('_', ' ')}
                                  </Badge>
                                </TableCell>
                                {(detailsData.isAdmin || detailsData.isManager) && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-3 w-3" />
                                      <span>{String(item.agentName)}</span>
                                      <Badge className={`text-xs ${getRoleBadgeColor(String(item.agentRole))}`}>
                                        {String(item.agentRole)}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell>
                                  <div>
                                    <p className={Number(item.outstandingBalance) > 0 ? 'text-red-600 font-medium' : 'text-green-600 font-medium'}>
                                      {formatCurrency(Number(item.outstandingBalance))}
                                    </p>
                                    <p className="text-xs text-muted-foreground">of {formatCurrency(Number(item.totalToCollect))}</p>
                                  </div>
                                </TableCell>
                              </>
                            )}
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                    {detailsData.data.length === 0 && (
                      <div className="text-center py-8 text-muted-foreground">
                        No records found for this period
                      </div>
                    )}
                  </ScrollArea>
                </TabsContent>

                {(detailsData.isAdmin || detailsData.isManager) && (
                  <TabsContent value="breakdown">
                    <ScrollArea className="h-[400px]">
                      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                        {(detailsData.summary.byUser || detailsData.summary.byAgent || []).map((user, index) => (
                          <Card key={index} className="p-4">
                            <div className="flex items-center gap-3 mb-3">
                              <div className="h-10 w-10 rounded-full bg-muted flex items-center justify-center">
                                <User className="h-5 w-5 text-muted-foreground" />
                              </div>
                              <div>
                                <p className="font-medium">{user.name}</p>
                                <Badge className={`text-xs ${getRoleBadgeColor(user.role)}`}>
                                  {user.role}
                                </Badge>
                              </div>
                            </div>
                            <div className="space-y-2 text-sm">
                              <div className="flex justify-between">
                                <span className="text-muted-foreground">Records</span>
                                <span className="font-medium">{user.count}</span>
                              </div>
                              {user.amount !== undefined && (
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">Amount</span>
                                  <span className="font-medium text-green-600">{formatCurrency(user.amount)}</span>
                                </div>
                              )}
                              {user.outstanding !== undefined && (
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">Outstanding</span>
                                  <span className="font-medium text-red-600">{formatCurrency(user.outstanding)}</span>
                                </div>
                              )}
                              {user.totalToCollect !== undefined && (
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">To Collect</span>
                                  <span className="font-medium">{formatCurrency(user.totalToCollect)}</span>
                                </div>
                              )}
                              {user.collected !== undefined && (
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">Collected</span>
                                  <span className="font-medium text-green-600">{formatCurrency(user.collected)}</span>
                                </div>
                              )}
                              {user.types && Object.keys(user.types).length > 0 && (
                                <div className="pt-2 border-t mt-2">
                                  <p className="text-xs text-muted-foreground mb-1">Activity Breakdown:</p>
                                  <div className="flex flex-wrap gap-1">
                                    {Object.entries(user.types).map(([type, count]) => (
                                      <Badge key={type} variant="outline" className="text-xs">
                                        {type}: {count}
                                      </Badge>
                                    ))}
                                  </div>
                                </div>
                              )}
                            </div>
                          </Card>
                        ))}
                      </div>
                      {(detailsData.summary.byUser?.length === 0 && detailsData.summary.byAgent?.length === 0) && (
                        <div className="text-center py-8 text-muted-foreground">
                          No user breakdown available
                        </div>
                      )}
                    </ScrollArea>
                  </TabsContent>
                )}
              </Tabs>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Failed to load details
              </div>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}
