make this compoent super good and awome and wokr perfectly let ethe mock databe as it is i want it to be 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>
  )
}
"""
i am going ot use it in nextjs app and typescript and tailwind make it best and compelte and super good and poreprly fit and align and structure everything compent