please make this compoejnt super awome and porlery fit and porpelry fomrat and structier liek eveyrthing right now is broken and merges and collides with aeverythign make it super good and awosme and operfect and wokring , fo nwo use the mock data dn i will implemnt the api call later but for youir refernce i am giving yo uthe backnd endpoint logic oto nad but i want hte frnrtend compo to be the best and super wokring advacned and super best 
"""
'use client'

import { useState, useEffect, useMemo, useCallback } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
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 { ScrollArea } from "@/components/ui/scroll-area"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { useToast } from "@/components/ui/use-toast"
import { Loader2, RefreshCw, AlertTriangle, CheckCircle, XCircle, Clock, Zap } from 'lucide-react'
import { format, subDays, parseISO } from "date-fns"
import { DateRange } from "react-day-picker"
import { cn } from "@/lib/utils"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Calendar } from "@/components/ui/calendar"
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts'

// Mock function to fetch analytics data
const fetchAnalytics = async (startDate, endDate, groupBy, urls, statusCodes, minResponseTime, maxResponseTime) => {
  // Simulate API call delay
  await new Promise(resolve => setTimeout(resolve, 1000))

  // Generate mock data based on parameters
  const generateMockData = (days) => {
    return Array.from({ length: days }, (_, i) => ({
      date: format(subDays(new Date(), days - 1 - i), 'yyyy-MM-dd'),
      totalChecks: Math.floor(Math.random() * 1000) + 500,
      successfulChecks: Math.floor(Math.random() * 900) + 100,
      failedChecks: Math.floor(Math.random() * 100),
      averageResponseTime: Math.floor(Math.random() * 500) + 100,
    }))
  }

  const mockData = generateMockData(30) // Generate 30 days of mock data

  return {
    totalChecks: mockData.reduce((sum, day) => sum + day.totalChecks, 0),
    successfulChecks: mockData.reduce((sum, day) => sum + day.successfulChecks, 0),
    failedChecks: mockData.reduce((sum, day) => sum + day.failedChecks, 0),
    averageResponseTime: Math.floor(mockData.reduce((sum, day) => sum + day.averageResponseTime, 0) / mockData.length),
    statusCodeDistribution: [
      { statusCode: 200, count: 9000, percentage: "90.00%" },
      { statusCode: 404, count: 400, percentage: "4.00%" },
      { statusCode: 500, count: 100, percentage: "1.00%" },
      { statusCode: 403, count: 300, percentage: "3.00%" },
      { statusCode: 301, count: 200, percentage: "2.00%" },
    ],
    uptimePerUrl: [
      { url: "https://example.com", successCount: 4750, totalCount: 5000, uptimePercentage: "95.00%" },
      { url: "https://api.example.com", successCount: 4800, totalCount: 5000, uptimePercentage: "96.00%" },
      { url: "https://blog.example.com", successCount: 4900, totalCount: 5000, uptimePercentage: "98.00%" },
      { url: "https://shop.example.com", successCount: 4700, totalCount: 5000, uptimePercentage: "94.00%" },
    ],
    checksOverTime: mockData,
    responseTimeDistribution: [
      { range: "0-100ms", count: 5000, percentage: "50.00%" },
      { range: "101-300ms", count: 3000, percentage: "30.00%" },
      { range: "301-500ms", count: 1500, percentage: "15.00%" },
      { range: "501-1000ms", count: 400, percentage: "4.00%" },
      { range: "1000ms+", count: 100, percentage: "1.00%" },
    ],
    topSlowestUrls: [
      { url: "https://slowapi.example.com", averageResponseTime: "750.00ms", totalChecks: 1000 },
      { url: "https://api.example.com/heavy-operation", averageResponseTime: "500.00ms", totalChecks: 500 },
      { url: "https://example.com/large-page", averageResponseTime: "450.00ms", totalChecks: 750 },
      { url: "https://shop.example.com/checkout", averageResponseTime: "400.00ms", totalChecks: 1200 },
      { url: "https://blog.example.com/feed", averageResponseTime: "350.00ms", totalChecks: 2000 },
    ],
    recentIssues: [
      { url: "https://example.com/broken-page", statusCode: 404, checkedAt: "2023-05-03T12:00:00Z", responseTime: "150.00ms" },
      { url: "https://api.example.com", statusCode: 500, checkedAt: "2023-05-03T11:55:00Z", responseTime: "2500.00ms" },
      { url: "https://shop.example.com/product", statusCode: 403, checkedAt: "2023-05-03T11:50:00Z", responseTime: "100.00ms" },
      { url: "https://blog.example.com/post", statusCode: 502, checkedAt: "2023-05-03T11:45:00Z", responseTime: "3000.00ms" },
      { url: "https://example.com/slow-page", statusCode: 200, checkedAt: "2023-05-03T11:40:00Z", responseTime: "5000.00ms" },
    ],
  }
}

function DatePickerWithRange({
  className,
  date,
  setDate,
}: {
  className?: string
  date: DateRange | undefined
  setDate: (date: DateRange | undefined) => void
}) {
  return (
    <div className={cn("grid gap-2", className)}>
      <Popover>
        <PopoverTrigger asChild>
          <Button
            id="date"
            variant={"outline"}
            className={cn(
              "w-[300px] justify-start text-left font-normal",
              !date && "text-muted-foreground"
            )}
          >
            <Calendar className="mr-2 h-4 w-4" />
            {date?.from ? (
              date.to ? (
                <>
                  {format(date.from, "LLL dd, y")} -{" "}
                  {format(date.to, "LLL dd, y")}
                </>
              ) : (
                format(date.from, "LLL dd, y")
              )
            ) : (
              <span>Pick a date range</span>
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            initialFocus
            mode="range"
            defaultMonth={date?.from}
            selected={date}
            onSelect={setDate}
            numberOfMonths={2}
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

export default function AdvancedAnalyticsDashboard() {
  const [analytics, setAnalytics] = useState(null)
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: subDays(new Date(), 30),
    to: new Date(),
  })
  const [groupBy, setGroupBy] = useState('day')
  const [isLoading, setIsLoading] = useState(true)
  const [isRealtime, setIsRealtime] = useState(false)
  const [urlFilter, setUrlFilter] = useState('')
  const [statusCodeFilter, setStatusCodeFilter] = useState('')
  const [responseTimeRange, setResponseTimeRange] = useState([0, 5000])
  const { toast } = useToast()

  const loadAnalytics = useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await fetchAnalytics(
        dateRange.from,
        dateRange.to,
        groupBy,
        urlFilter,
        statusCodeFilter,
        responseTimeRange[0],
        responseTimeRange[1]
      )
      setAnalytics(data)
    } catch (error) {
      console.error('Failed to fetch analytics:', error)
      toast({
        title: "Error",
        description: "Failed to fetch analytics data. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }, [dateRange, groupBy, urlFilter, statusCodeFilter, responseTimeRange, toast])

  useEffect(() => {
    loadAnalytics()
  }, [loadAnalytics])

  useEffect(() => {
    if (isRealtime) {
      const interval = setInterval(() => {
        loadAnalytics()
      }, 5000) // Refresh every 5 seconds in realtime mode
      return () => clearInterval(interval)
    }
  }, [isRealtime, loadAnalytics])

  const filteredChecksOverTime = useMemo(() => {
    if (!analytics) return []
    return analytics.checksOverTime.filter(check => {
      const checkDate = parseISO(check.date)
      return checkDate >= dateRange.from && checkDate <= dateRange.to
    })
  }, [analytics, dateRange])

  if (isLoading && !analytics) {
    return (
      <div className="flex h-screen items-center justify-center">
        <Loader2 className="h-16 w-16 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <div className="container mx-auto p-4 space-y-8">
      <div className="flex justify-between items-center">
        <h1 className="text-4xl font-bold">Advanced Analytics Dashboard</h1>
        <div className="flex items-center space-x-4">
          <Switch
            checked={isRealtime}
            onCheckedChange={setIsRealtime}
            id="realtime-mode"
          />
          <Label htmlFor="realtime-mode">Realtime Updates</Label>
          <Button onClick={loadAnalytics} disabled={isLoading}>
            {isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
            Refresh Data
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Checks</CardTitle>
            <Zap className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{analytics?.totalChecks.toLocaleString()}</div>
            <p className="text-xs text-muted-foreground">
              +{((analytics?.totalChecks || 0) * 0.1).toFixed(0)} since last period
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Success Rate</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {analytics ? ((analytics.successfulChecks / analytics.totalChecks) * 100).toFixed(2) : 0}%
            </div>
            <p className="text-xs text-muted-foreground">
              {analytics?.successfulChecks.toLocaleString()} successful checks
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Failed Checks</CardTitle>
            <XCircle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{analytics?.failedChecks.toLocaleString()}</div>
            <p className="text-xs text-muted-foreground">
              {analytics ? ((analytics.failedChecks / analytics.totalChecks) * 100).toFixed(2) : 0}% failure rate
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Avg Response Time</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{analytics?.averageResponseTime.toFixed(2)}ms</div>
            <p className="text-xs text-muted-foreground">
              Across all checks
            </p>
          </CardContent>
        </Card>
      </div>

      <div className="flex flex-wrap gap-4 items-center justify-between">
        <DatePickerWithRange date={dateRange} setDate={setDateRange} />
        <Select value={groupBy} onValueChange={setGroupBy}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Group by" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="hour">Hour</SelectItem>
            <SelectItem value="day">Day</SelectItem>
            <SelectItem value="week">Week</SelectItem>
            <SelectItem value="month">Month</SelectItem>
          </SelectContent>
        </Select>
        <div className="flex items-center space-x-2">
          <Input
            placeholder="Filter by URL"
            value={urlFilter}
            onChange={(e) => setUrlFilter(e.target.value)}
            className="w-64"
          />
          <Input
            placeholder="Status Codes (e.g., 200,404)"
            value={statusCodeFilter}
            onChange={(e) => setStatusCodeFilter(e.target.value)}
            className="w-48"
          />
        </div>
        <div className="flex items-center space-x-2">
          <Label>Response Time Range (ms):</Label>
          <Slider
            min={0}
            max={5000}
            step={100}
            value={responseTimeRange}
            onValueChange={setResponseTimeRange}
            className="w-64"
          />
          <span>{responseTimeRange[0]}ms - {responseTimeRange[1]}ms</span>
        </div>
      </div>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="performance">Performance</TabsTrigger>
          <TabsTrigger value="issues">Issues</TabsTrigger>
        </TabsList>
        <TabsContent value="overview" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Checks Over Time</CardTitle>
            </CardHeader>
            <CardContent className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={filteredChecksOverTime}>
                  <defs>
                    <linearGradient id="colorTotal" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
                      <stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
                    </linearGradient>
                    <linearGradient id="colorSuccess" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#82ca9d" stopOpacity={0.8}/>
                      <stop offset="95%" stopColor="#82ca9d" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <XAxis dataKey="date" />
                  <YAxis />
                  <CartesianGrid strokeDasharray="3 3" />
                  <Tooltip />
                  <Legend />
                  <Area type="monotone" dataKey="totalChecks" stroke="#8884d8" fillOpacity={1} fill="url(#colorTotal)" />
                  <Area type="monotone" dataKey="successfulChecks" stroke="#82ca9d" fillOpacity={1} fill="url(#colorSuccess)" />
                </AreaChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
          <div className="grid gap-4 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>Status Code Distribution</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={analytics?.statusCodeDistribution}
                      dataKey="count"
                      nameKey="statusCode"
                      cx="50%"
                      cy="50%"
                      outerRadius={80}
                      fill="#8884d8"
                      label
                    >
                      {analytics?.statusCodeDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={`hsl(${index * 45}, 70%, 60%)`} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Uptime Per URL</CardTitle>
              </CardHeader>
              <CardContent className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={analytics?.uptimePerUrl}>
                    <XAxis dataKey="url" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="uptimePercentage" fill="#82ca9d" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
        <TabsContent value="performance" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Response Time Distribution</CardTitle>
            </CardHeader>
            <CardContent className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={analytics?.responseTimeDistribution}>
                  <XAxis dataKey="range" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="count" fill="#8884d8" />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Top Slowest URLs</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>URL</TableHead>
                    <TableHead>Avg Response Time</TableHead>
                    <TableHead>Total Checks</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {analytics?.topSlowestUrls.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell className="font-medium">{item.url}</TableCell>
                      <TableCell>{item.averageResponseTime}</TableCell>
                      <TableCell>{item.totalChecks}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="issues" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Recent Issues</CardTitle>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-[400px]">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>URL</TableHead>
                      <TableHead>Status Code</TableHead>
                      <TableHead>Checked At</TableHead>
                      <TableHead>Response Time</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {analytics?.recentIssues.map((issue, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{issue.url}</TableCell>
                        <TableCell>
                          <Badge variant={issue.statusCode >= 500 ? "destructive" : "warning"}>
                            {issue.statusCode}
                          </Badge>
                        </TableCell>
                        <TableCell>{new Date(issue.checkedAt).toLocaleString()}</TableField>
                        <TableCell>{issue.responseTime}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
"""
"""
exports.getAnalytics = async (req, res) => {
    try {
        const userId = req.user.id;

        // Validate and parse query parameters
        const parsed = analyticsSchema.parse(req.query);
        const { startDate, endDate, urls, statusCodes, minResponseTime, maxResponseTime, groupBy, page, limit } = parsed;

        // Build the match criteria for MongoDB aggregation
        const matchCriteria = { user: new mongoose.Types.ObjectId(userId) };

        if (startDate || endDate) {
            matchCriteria.checkedAt = {};
            if (startDate) {
                matchCriteria.checkedAt.$gte = new Date(startDate);
            }
            if (endDate) {
                matchCriteria.checkedAt.$lte = new Date(endDate);
            }
        }

        if (urls) {
            const urlsArray = urls.split(',').map(url => url.trim());
            matchCriteria.url = { $in: urlsArray };
        }

        if (statusCodes) {
            const statusCodesArray = statusCodes.split(',').map(code => parseInt(code.trim()));
            matchCriteria.statusCode = { $in: statusCodesArray };
        }

        if (minResponseTime || maxResponseTime) {
            matchCriteria.responseTime = {};
            if (minResponseTime) {
                matchCriteria.responseTime.$gte = parseInt(minResponseTime, 10);
            }
            if (maxResponseTime) {
                matchCriteria.responseTime.$lte = parseInt(maxResponseTime, 10);
            }
        }

        /**
         * Aggregation Pipelines
         */

        // Total Checks
        const totalChecksPromise = Log.countDocuments(matchCriteria).exec();

        // Successful Checks (2xx)
        const successfulChecksPromise = Log.countDocuments({
            ...matchCriteria,
            statusCode: { $gte: 200, $lt: 300 },
        }).exec();

        // Failed Checks (4xx and 5xx)
        const failedChecksPromise = Log.countDocuments({
            ...matchCriteria,
            statusCode: { $gte: 400 },
        }).exec();

        // Status Code Distribution
        const statusCodeDistributionPromise = Log.aggregate([
            { $match: matchCriteria },
            {
                $group: {
                    _id: '$statusCode',
                    count: { $sum: 1 },
                },
            },
            { $sort: { count: -1 } },
        ]).exec();

        // Uptime Percentage per URL
        const uptimePerUrlPromise = Log.aggregate([
            { $match: { ...matchCriteria, statusCode: { $gte: 200, $lt: 300 } } },
            {
                $group: {
                    _id: '$url',
                    successCount: { $sum: 1 },
                },
            },
            {
                $lookup: {
                    from: 'logs',
                    let: { url: '$_id' },
                    pipeline: [
                        { $match: { 
                            $expr: { $eq: ['$url', '$$url'] },
                            ...(startDate || endDate ? {
                                ...(startDate ? { $gte: ['$checkedAt', new Date(startDate)] } : {}),
                                ...(endDate ? { $lte: ['$checkedAt', new Date(endDate)] } : {}),
                            } : {})
                        } },
                        { $count: 'totalCount' },
                    ],
                    as: 'total',
                },
            },
            {
                $addFields: {
                    totalCount: { $ifNull: [{ $arrayElemAt: ['$total.totalCount', 0] }, 0] },
                },
            },
            {
                $project: {
                    _id: 1,
                    successCount: 1,
                    totalCount: 1,
                    uptimePercentage: {
                        $cond: [
                            { $eq: ['$totalCount', 0] },
                            0,
                            { $multiply: [{ $divide: ['$successCount', '$totalCount'] }, 100] },
                        ],
                    },
                },
            },
        ]).exec();

        // Checks Over Time with Average Response Time
        const checksOverTimePromise = Log.aggregate([
            { $match: matchCriteria },
            {
                $group: {
                    _id: {
                        year: { $year: '$checkedAt' },
                        month: { $month: '$checkedAt' },
                        week: { $week: '$checkedAt' },
                        day: { $dayOfMonth: '$checkedAt' },
                        hour: { $hour: '$checkedAt' },
                    },
                    count: { $sum: 1 },
                    averageResponseTime: { $avg: '$responseTime' },
                },
            },
            {
                $project: {
                    _id: 0,
                    period: getPeriodExpression(groupBy),
                    count: 1,
                    averageResponseTime: 1,
                },
            },
            {
                $group: {
                    _id: '$period',
                    total: { $sum: '$count' },
                    averageResponseTime: { $avg: '$averageResponseTime' },
                },
            },
            { $sort: { '_id': 1 } },
        ]).exec();

        // Response Time Distribution
        const responseTimeDistributionPromise = Log.aggregate([
            { $match: matchCriteria },
            {
                $bucket: {
                    groupBy: '$responseTime',
                    boundaries: [0, 100, 300, 500, 1000, 3000, 5000, Infinity],
                    default: '5000+',
                    output: {
                        count: { $sum: 1 },
                        averageResponseTime: { $avg: '$responseTime' },
                    },
                },
            },
            { $sort: { _id: 1 } },
        ]).exec();

        // Top Slowest URLs
        const topSlowestUrlsPromise = Log.aggregate([
            { $match: matchCriteria },
            {
                $group: {
                    _id: '$url',
                    averageResponseTime: { $avg: '$responseTime' },
                    totalChecks: { $sum: 1 },
                },
            },
            { $sort: { averageResponseTime: -1 } },
            { $limit: 10 },
        ]).exec();

        // Recent Issues
        const recentIssuesPromise = Log.find({
            ...matchCriteria,
            statusCode: { $gte: 400 }, // Client and Server errors
        })
            .sort({ checkedAt: -1 })
            .limit(10)
            .select('url statusCode checkedAt screenshotUrl responseTime')
            .exec();

        // Execute all aggregation promises concurrently
        const [
            totalChecks,
            successfulChecks,
            failedChecks,
            statusCodeDistribution,
            uptimePerUrl,
            checksOverTime,
            responseTimeDistribution,
            topSlowestUrls,
            recentIssues,
        ] = await Promise.all([
            totalChecksPromise,
            successfulChecksPromise,
            failedChecksPromise,
            statusCodeDistributionPromise,
            uptimePerUrlPromise,
            checksOverTimePromise,
            responseTimeDistributionPromise,
            topSlowestUrlsPromise,
            recentIssuesPromise,
        ]);

        // Calculate success and failure percentages with safe defaults
        const successPercentage = totalChecks > 0 ? (((successfulChecks / totalChecks) * 100) || 0).toFixed(2) : '0.00';
        const failurePercentage = totalChecks > 0 ? (((failedChecks / totalChecks) * 100) || 0).toFixed(2) : '0.00';

        // Structure the analytics response
        const analytics = {
            totalChecks,
            successfulChecks,
            successPercentage: `${successPercentage}%`,
            failedChecks,
            failurePercentage: `${failurePercentage}%`,
            statusCodeDistribution: statusCodeDistribution.map(item => ({
                statusCode: item._id,
                count: item.count,
                percentage: totalChecks > 0 ? `${(((item.count / totalChecks) * 100) || 0).toFixed(2)}%` : '0.00%',
            })),
            uptimePerUrl: uptimePerUrl.map(item => ({
                url: item._id,
                successCount: item.successCount,
                totalCount: item.totalCount,
                uptimePercentage: `${(item.uptimePercentage || 0).toFixed(2)}%`,
            })),
            checksOverTime: checksOverTime.map(item => ({
                period: formatPeriod(item._id, groupBy),
                count: item.total,
                averageResponseTime: `${(item.averageResponseTime || 0).toFixed(2)}ms`,
            })),
            responseTimeDistribution: responseTimeDistribution.map(item => ({
                range: formatResponseTimeRange(item._id),
                count: item.count,
                averageResponseTime: item.averageResponseTime ? `${item.averageResponseTime.toFixed(2)}ms` : 'N/A',
            })),
            topSlowestUrls: topSlowestUrls.map(item => ({
                url: item._id,
                averageResponseTime: `${(item.averageResponseTime || 0).toFixed(2)}ms`,
                totalChecks: item.totalChecks,
            })),
            recentIssues,
        };

        // Send the analytics data as a JSON response
        res.status(200).json({ analytics });
    } catch (error) {
        if (error instanceof z.ZodError) {
            // If validation fails, send a 400 response with error details
            return res.status(400).json({
                message: 'Invalid query parameters',
                errors: error.errors.map((err) => ({
                    field: err.path.join('.'),
                    message: err.message,
                })),
            });
        }

        // Log unexpected errors and send a 500 response
        logger.error('Get Analytics Error:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
};

/**
 * Helper functions for formatting
 */

/**
 * Formats the period string based on the groupBy parameter.
 *
 * @param {Object} periodObj - Object containing date parts.
 * @param {string} groupBy - Grouping parameter ('hour', 'day', 'week', 'month').
 * @returns {string} - Formatted period string.
 */
const formatPeriod = (periodObj, groupBy) => {
    const { year, month, week, day, hour } = periodObj;
    switch (groupBy) {
        case 'hour':
            return `${month}/${day}/${year} ${hour}:00`;
        case 'day':
            return `${month}/${day}/${year}`;
        case 'week':
            return `Week ${week}, ${year}`;
        case 'month':
            return `${month}/${year}`;
        default:
            return `${month}/${day}/${year}`;
    }
};

/**
 * Formats the response time range for distribution buckets.
 *
 * @param {string|number} range - The range identifier from the aggregation.
 * @returns {string} - Formatted range string.
 */
const formatResponseTimeRange = (range) => {
    if (range === '5000+') return '5000+ms';
    return `${range[0]}-${range[1]}ms`;
};

/**
 * Returns the MongoDB aggregation expression based on the groupBy parameter.
 *
 * @param {string} groupBy - Grouping parameter ('hour', 'day', 'week', 'month').
 * @returns {Object} - Aggregation expression.
 */
const getPeriodExpression = (groupBy) => ({
    hour: {
        year: { $year: '$checkedAt' },
        month: { $month: '$checkedAt' },
        day: { $dayOfMonth: '$checkedAt' },
        hour: { $hour: '$checkedAt' },
    },
    day: {
        year: { $year: '$checkedAt' },
        month: { $month: '$checkedAt' },
        day: { $dayOfMonth: '$checkedAt' },
    },
    week: {
        year: { $year: '$checkedAt' },
        week: { $week: '$checkedAt' },
    },
    month: {
        year: { $year: '$checkedAt' },
        month: { $month: '$checkedAt' },
    },
}[groupBy]);
"""
"""
router.get('/analytics', authenticate, ensureVerified, userController.getAnalytics);

"""
make it comeplte and give me total i will be working in nextjs app router and typescritp and tailwind makei t good and workjing