"use client";

import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { ProtectedLayout } from "@/components/protected-layout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/hooks/use-toast";
import {
  Phone,
  MessageSquare,
  Mail,
  ArrowUpRight,
  ArrowDownLeft,
  Clock,
  User,
  Filter,
  RefreshCw,
  Inbox,
  Send,
  CheckCircle,
  XCircle,
  AlertCircle,
  Eye,
  Reply,
  Search,
  Users,
} from "lucide-react";
import { format } from "date-fns";

interface Communication {
  id: string;
  collectionFileId: string;
  type: string;
  direction: string;
  channel: string;
  phoneNumber?: string;
  content: string;
  status: string;
  duration?: number;
  outcome?: string;
  isAutomated: boolean;
  createdAt: string;
  collectionFile?: {
    id: string;
    customerName: string;
    phoneNumber: string;
  };
}

interface InboundSms {
  id: string;
  collectionFileId?: string;
  from: string;
  to: string;
  message: string;
  isRead: boolean;
  isReplied: boolean;
  receivedAt: string;
  collectionFile?: {
    id: string;
    customerName: string;
    phoneNumber: string;
  };
}

interface DetailItem {
  id: string;
  customerName?: string;
  phoneNumber?: string;
  agentName?: string;
  agentRole?: string;
  date?: string;
  status?: string;
  content?: string;
  channel?: string;
  outcome?: string;
  message?: string;
  direction?: string;
  [key: string]: unknown;
}

interface UserBreakdown {
  name: string;
  role: string;
  count: number;
  [key: string]: unknown;
}

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

  const [communications, setCommunications] = useState<Communication[]>([]);
  const [inboundMessages, setInboundMessages] = useState<InboundSms[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [channelFilter, setChannelFilter] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedMessage, setSelectedMessage] = useState<InboundSms | null>(null);
  const [replyText, setReplyText] = useState("");
  const [isSendingReply, setIsSendingReply] = useState(false);

  // Details dialog state
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [detailsCategory, setDetailsCategory] = useState("");
  const [detailsTitle, setDetailsTitle] = useState("");
  const [detailsData, setDetailsData] = useState<DetailItem[]>([]);
  const [detailsSummary, setDetailsSummary] = useState<Record<string, unknown>>({});
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [detailsTab, setDetailsTab] = useState("details");

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

  const fetchCommunications = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (channelFilter !== "all") params.append("channel", channelFilter);
      params.append("limit", "100");

      const response = await fetch(`/api/communications?${params}`);
      if (response.ok) {
        const data = await response.json();
        setCommunications(data.communications || []);
      }
    } catch (error) {
      console.error("Error fetching communications:", error);
    }
  }, [channelFilter]);

  const fetchInboundMessages = useCallback(async () => {
    try {
      const response = await fetch("/api/sms/webhook?limit=50");
      if (response.ok) {
        const data = await response.json();
        setInboundMessages(data.messages || []);
        setUnreadCount(data.unreadCount || 0);
      }
    } catch (error) {
      console.error("Error fetching inbound messages:", error);
    }
  }, []);

  useEffect(() => {
    if (status === "authenticated") {
      Promise.all([fetchCommunications(), fetchInboundMessages()]).finally(() => {
        setIsLoading(false);
      });
    }
  }, [status, fetchCommunications, fetchInboundMessages]);

  const fetchDetails = async (category: string, title: string) => {
    setDetailsLoading(true);
    setDetailsDialogOpen(true);
    setDetailsCategory(category);
    setDetailsTitle(title);
    setDetailsTab("details");

    try {
      const response = await fetch(`/api/dashboard/details?category=${category}&period=all`);
      if (response.ok) {
        const data = await response.json();
        setDetailsData(data.data || []);
        setDetailsSummary(data.summary || {});
      }
    } catch (error) {
      console.error("Error fetching details:", error);
      toast({ title: "Error", description: "Failed to fetch details", variant: "destructive" });
    } finally {
      setDetailsLoading(false);
    }
  };

  const handleMarkAsRead = async (id: string) => {
    try {
      const response = await fetch(`/api/sms/webhook/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isRead: true }),
      });

      if (response.ok) {
        setInboundMessages((prev) =>
          prev.map((m) => (m.id === id ? { ...m, isRead: true } : m))
        );
        setUnreadCount((prev) => Math.max(0, prev - 1));
      }
    } catch (error) {
      console.error("Error marking as read:", error);
    }
  };

  const handleSendReply = async () => {
    if (!selectedMessage || !replyText.trim()) return;

    setIsSendingReply(true);
    try {
      const smsResponse = await fetch("/api/sms", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          phoneNumber: selectedMessage.from,
          message: replyText,
          collectionFileId: selectedMessage.collectionFileId,
        }),
      });

      if (smsResponse.ok) {
        await fetch(`/api/sms/webhook/${selectedMessage.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ replyMessage: replyText }),
        });

        toast({
          title: "Reply Sent",
          description: "Your reply has been sent successfully.",
        });

        setSelectedMessage(null);
        setReplyText("");
        fetchInboundMessages();
      } else {
        throw new Error("Failed to send reply");
      }
    } catch (error) {
      console.error("Error sending reply:", error);
      toast({
        title: "Error",
        description: "Failed to send reply. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsSendingReply(false);
    }
  };

  const getChannelIcon = (channel: string) => {
    switch (channel) {
      case "CALL":
        return <Phone className="h-4 w-4" />;
      case "SMS":
        return <MessageSquare className="h-4 w-4" />;
      case "EMAIL":
        return <Mail className="h-4 w-4" />;
      default:
        return <MessageSquare className="h-4 w-4" />;
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "COMPLETED":
      case "DELIVERED":
      case "SENT":
        return <Badge className="bg-green-100 text-green-800"><CheckCircle className="h-3 w-3 mr-1" />Completed</Badge>;
      case "FAILED":
        return <Badge className="bg-red-100 text-red-800"><XCircle className="h-3 w-3 mr-1" />Failed</Badge>;
      case "PENDING":
        return <Badge className="bg-yellow-100 text-yellow-800"><AlertCircle className="h-3 w-3 mr-1" />Pending</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

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

  const filteredCommunications = communications.filter((c) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      c.collectionFile?.customerName?.toLowerCase().includes(query) ||
      c.phoneNumber?.toLowerCase().includes(query) ||
      c.content?.toLowerCase().includes(query)
    );
  });

  const callsCount = communications.filter((c) => c.channel === "CALL").length;
  const smsCount = communications.filter((c) => c.channel === "SMS").length;
  const emailCount = communications.filter((c) => c.channel === "EMAIL").length;

  if (status === "loading" || isLoading) {
    return (
      <ProtectedLayout>
        <div className="flex items-center justify-center h-64">
          <RefreshCw className="h-8 w-8 animate-spin text-blue-600" />
        </div>
      </ProtectedLayout>
    );
  }

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Communication Center</h1>
            <p className="text-gray-600 mt-1">View all customer interactions in one place</p>
          </div>
          <Button
            onClick={() => {
              fetchCommunications();
              fetchInboundMessages();
            }}
            variant="outline"
          >
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </Button>
        </div>

        {/* Summary Cards - Clickable */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-blue-300"
            onClick={() => fetchDetails('calls', 'Total Calls')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-100 rounded-full">
                  <Phone className="h-6 w-6 text-blue-600" />
                </div>
                <div className="flex-1">
                  <p className="text-2xl font-bold">{callsCount}</p>
                  <p className="text-sm text-gray-600">Total Calls</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>

          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-green-300"
            onClick={() => fetchDetails('sms', 'SMS Sent')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-green-100 rounded-full">
                  <MessageSquare className="h-6 w-6 text-green-600" />
                </div>
                <div className="flex-1">
                  <p className="text-2xl font-bold">{smsCount}</p>
                  <p className="text-sm text-gray-600">SMS Sent</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>

          <Card 
            className="cursor-pointer hover:shadow-lg transition-all hover:border-purple-300"
            onClick={() => fetchDetails('activities', 'Emails')}
          >
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-purple-100 rounded-full">
                  <Mail className="h-6 w-6 text-purple-600" />
                </div>
                <div className="flex-1">
                  <p className="text-2xl font-bold">{emailCount}</p>
                  <p className="text-sm text-gray-600">Emails</p>
                </div>
                <Eye className="h-4 w-4 text-gray-400" />
              </div>
            </CardContent>
          </Card>

          <Card className={`${unreadCount > 0 ? "border-orange-300 bg-orange-50" : ""}`}>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className={`p-3 rounded-full ${unreadCount > 0 ? "bg-orange-100" : "bg-gray-100"}`}>
                  <Inbox className={`h-6 w-6 ${unreadCount > 0 ? "text-orange-600" : "text-gray-600"}`} />
                </div>
                <div>
                  <p className="text-2xl font-bold">{unreadCount}</p>
                  <p className="text-sm text-gray-600">Unread Replies</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        <Tabs defaultValue="all" className="w-full">
          <TabsList>
            <TabsTrigger value="all">All Communications</TabsTrigger>
            <TabsTrigger value="inbox" className="relative">
              Inbox
              {unreadCount > 0 && (
                <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
                  {unreadCount}
                </span>
              )}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="all" className="mt-4">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>Communication History</CardTitle>
                    <CardDescription>All calls, SMS, and emails</CardDescription>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                      <Input
                        placeholder="Search..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-9 w-64"
                      />
                    </div>
                    <Select value={channelFilter} onValueChange={setChannelFilter}>
                      <SelectTrigger className="w-32">
                        <Filter className="h-4 w-4 mr-2" />
                        <SelectValue placeholder="Channel" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">All</SelectItem>
                        <SelectItem value="CALL">Calls</SelectItem>
                        <SelectItem value="SMS">SMS</SelectItem>
                        <SelectItem value="EMAIL">Email</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {filteredCommunications.length === 0 ? (
                    <p className="text-center text-gray-500 py-8">No communications found</p>
                  ) : (
                    filteredCommunications.map((comm) => (
                      <div
                        key={comm.id}
                        className="flex items-start gap-4 p-4 border rounded-lg hover:bg-gray-50 cursor-pointer"
                        onClick={() => {
                          if (comm.collectionFileId) {
                            router.push(`/files/${comm.collectionFileId}`);
                          }
                        }}
                      >
                        <div className={`p-2 rounded-full ${comm.direction === "INBOUND" ? "bg-green-100" : "bg-blue-100"}`}>
                          {getChannelIcon(comm.channel)}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">
                              {comm.collectionFile?.customerName || "Unknown"}
                            </span>
                            {comm.direction === "INBOUND" ? (
                              <ArrowDownLeft className="h-4 w-4 text-green-600" />
                            ) : (
                              <ArrowUpRight className="h-4 w-4 text-blue-600" />
                            )}
                            {comm.isAutomated && (
                              <Badge variant="outline" className="text-xs">Automated</Badge>
                            )}
                          </div>
                          <p className="text-sm text-gray-600 truncate">{comm.content}</p>
                          <div className="flex items-center gap-4 mt-1 text-xs text-gray-500">
                            <span className="flex items-center gap-1">
                              <Clock className="h-3 w-3" />
                              {format(new Date(comm.createdAt), "MMM d, yyyy HH:mm")}
                            </span>
                            {comm.phoneNumber && (
                              <span className="flex items-center gap-1">
                                <Phone className="h-3 w-3" />
                                {comm.phoneNumber}
                              </span>
                            )}
                            {comm.duration && (
                              <span>{Math.floor(comm.duration / 60)}:{(comm.duration % 60).toString().padStart(2, "0")}</span>
                            )}
                          </div>
                        </div>
                        <div className="flex flex-col items-end gap-1">
                          {getStatusBadge(comm.status)}
                          {comm.outcome && (
                            <span className="text-xs text-gray-500">{comm.outcome}</span>
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="inbox" className="mt-4">
            <Card>
              <CardHeader>
                <CardTitle>Incoming Messages</CardTitle>
                <CardDescription>Customer replies and incoming SMS</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {inboundMessages.length === 0 ? (
                    <p className="text-center text-gray-500 py-8">No incoming messages</p>
                  ) : (
                    inboundMessages.map((msg) => (
                      <div
                        key={msg.id}
                        className={`flex items-start gap-4 p-4 border rounded-lg ${
                          !msg.isRead ? "bg-blue-50 border-blue-200" : "hover:bg-gray-50"
                        }`}
                      >
                        <div className="p-2 rounded-full bg-green-100">
                          <ArrowDownLeft className="h-4 w-4 text-green-600" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">
                              {msg.collectionFile?.customerName || msg.from}
                            </span>
                            {!msg.isRead && (
                              <Badge className="bg-blue-100 text-blue-800">New</Badge>
                            )}
                            {msg.isReplied && (
                              <Badge className="bg-green-100 text-green-800">Replied</Badge>
                            )}
                          </div>
                          <p className="text-sm text-gray-700 mt-1">{msg.message}</p>
                          <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                            <span className="flex items-center gap-1">
                              <Clock className="h-3 w-3" />
                              {format(new Date(msg.receivedAt), "MMM d, yyyy HH:mm")}
                            </span>
                            <span className="flex items-center gap-1">
                              <Phone className="h-3 w-3" />
                              {msg.from}
                            </span>
                          </div>
                        </div>
                        <div className="flex flex-col gap-2">
                          {!msg.isRead && (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleMarkAsRead(msg.id);
                              }}
                            >
                              <Eye className="h-4 w-4 mr-1" />
                              Mark Read
                            </Button>
                          )}
                          <Button
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleMarkAsRead(msg.id);
                              setSelectedMessage(msg);
                            }}
                          >
                            <Reply className="h-4 w-4 mr-1" />
                            Reply
                          </Button>
                          {msg.collectionFileId && (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={(e) => {
                                e.stopPropagation();
                                router.push(`/files/${msg.collectionFileId}`);
                              }}
                            >
                              <User className="h-4 w-4 mr-1" />
                              View File
                            </Button>
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Reply Dialog */}
        <Dialog open={!!selectedMessage} onOpenChange={() => setSelectedMessage(null)}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Reply to {selectedMessage?.collectionFile?.customerName || selectedMessage?.from}</DialogTitle>
              <DialogDescription>
                Original message: {selectedMessage?.message}
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <Textarea
                placeholder="Type your reply..."
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                rows={4}
              />
              <p className="text-xs text-gray-500">{replyText.length}/160 characters</p>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setSelectedMessage(null)}>
                Cancel
              </Button>
              <Button
                onClick={handleSendReply}
                disabled={!replyText.trim() || isSendingReply}
              >
                {isSendingReply ? (
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Send className="h-4 w-4 mr-2" />
                )}
                Send Reply
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Details Dialog */}
        <Dialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
          <DialogContent className="max-w-4xl max-h-[80vh]">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                {detailsCategory === 'calls' && <Phone className="h-5 w-5 text-blue-600" />}
                {detailsCategory === 'sms' && <MessageSquare className="h-5 w-5 text-green-600" />}
                {detailsCategory === 'activities' && <Mail className="h-5 w-5 text-purple-600" />}
                {detailsTitle}
              </DialogTitle>
              <DialogDescription>
                Detailed breakdown of {detailsTitle.toLowerCase()}
              </DialogDescription>
            </DialogHeader>

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

                <TabsContent value="details">
                  <div className="space-y-4">
                    {/* Summary */}
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <Card>
                        <CardContent className="pt-4">
                          <p className="text-sm text-muted-foreground">Total Records</p>
                          <p className="text-2xl font-bold">{detailsSummary.count as number || 0}</p>
                        </CardContent>
                      </Card>
                    </div>

                    {/* Data Table */}
                    <ScrollArea className="h-[400px] rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Customer</TableHead>
                            <TableHead>Phone</TableHead>
                            {canViewUserBreakdown && <TableHead>Agent</TableHead>}
                            <TableHead>Outcome/Status</TableHead>
                            <TableHead>Date</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {detailsData.length === 0 ? (
                            <TableRow>
                              <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                                No records found
                              </TableCell>
                            </TableRow>
                          ) : (
                            detailsData.map((item) => (
                              <TableRow key={item.id}>
                                <TableCell className="font-medium">{item.customerName || 'Unknown'}</TableCell>
                                <TableCell>{item.phoneNumber || '-'}</TableCell>
                                {canViewUserBreakdown && (
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <span>{item.agentName}</span>
                                      <Badge variant="outline" className={`text-xs ${getRoleBadgeColor(item.agentRole || '')}`}>
                                        {item.agentRole}
                                      </Badge>
                                    </div>
                                  </TableCell>
                                )}
                                <TableCell>{item.outcome || item.status || '-'}</TableCell>
                                <TableCell>
                                  {item.date ? format(new Date(item.date), 'MMM d, yyyy HH:mm') : '-'}
                                </TableCell>
                              </TableRow>
                            ))
                          )}
                        </TableBody>
                      </Table>
                    </ScrollArea>
                  </div>
                </TabsContent>

                {canViewUserBreakdown && (
                  <TabsContent value="byUser">
                    <ScrollArea className="h-[400px]">
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-1">
                        {(detailsSummary.byUser as UserBreakdown[] || []).map((user, idx) => (
                          <Card key={idx}>
                            <CardContent className="pt-4">
                              <div className="flex items-center justify-between mb-2">
                                <div className="flex items-center gap-2">
                                  <Users className="h-4 w-4 text-muted-foreground" />
                                  <span className="font-medium">{user.name}</span>
                                </div>
                                <Badge variant="outline" className={getRoleBadgeColor(user.role)}>
                                  {user.role}
                                </Badge>
                              </div>
                              <div className="space-y-1 text-sm">
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">Records:</span>
                                  <span className="font-medium">{user.count}</span>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </ScrollArea>
                  </TabsContent>
                )}
              </Tabs>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </ProtectedLayout>
  );
}
