'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { HTTPStats } from '@/types/monitoring';
import { formatLatency, formatPercent } from '@/hooks/use-monitoring';
import { Activity, AlertTriangle, Clock, Gauge } from 'lucide-react';

interface HTTPStatsProps {
  stats?: HTTPStats;
}

export function HTTPStatsOverview({ stats }: HTTPStatsProps) {
  if (!stats) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>HTTP Statistics</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-4 text-muted-foreground">
            No HTTP statistics available
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="grid gap-4 md: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 Requests</CardTitle>
          <Activity className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{(stats.requests_total ?? 0).toLocaleString()}</div>
          <p className="text-xs text-muted-foreground">
            {(stats.requests_per_minute ?? 0).toFixed(2)} req/min
          </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 Latency</CardTitle>
          <Clock className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{formatLatency(stats.avg_latency_ms)}</div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Error Rate</CardTitle>
          <AlertTriangle className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{formatPercent((stats.error_rate ?? 0) * 100)}</div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Throughput</CardTitle>
          <Gauge className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{(stats.requests_per_minute ?? 0).toFixed(2)}</div>
          <p className="text-xs text-muted-foreground">requests per minute</p>
        </CardContent>
      </Card>
    </div>
  );
}

export function HTTPEndpointStats({ stats }: HTTPStatsProps) {
  if (!stats?.by_endpoint || Object.keys(stats.by_endpoint).length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Endpoint Statistics</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-4 text-muted-foreground">
            No endpoint statistics available
          </div>
        </CardContent>
      </Card>
    );
  }

  // Sort endpoints by request count (descending)
  const sortedEndpoints = Object.entries(stats.by_endpoint)
    .sort((a, b) => b[1].count - a[1].count)
    .slice(0, 20); // Show top 20

  return (
    <Card>
      <CardHeader>
        <CardTitle>Top Endpoints by Traffic</CardTitle>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Endpoint</TableHead>
              <TableHead className="text-right">Requests</TableHead>
              <TableHead className="text-right">Avg Latency</TableHead>
              <TableHead className="text-right">P95 Latency</TableHead>
              <TableHead className="text-right">Error Rate</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedEndpoints.map(([endpoint, data]) => {
              const errorRatePercent = (data.error_rate ?? 0) * 100;
              return (
                <TableRow key={endpoint}>
                  <TableCell className="font-mono text-sm">{endpoint}</TableCell>
                  <TableCell className="text-right">{data.count.toLocaleString()}</TableCell>
                  <TableCell className="text-right">{formatLatency(data.avg_latency_ms)}</TableCell>
                  <TableCell className="text-right">{formatLatency(data.p95_latency_ms)}</TableCell>
                  <TableCell className="text-right">
                    <span className={errorRatePercent > 5 ? 'text-red-500' : ''}>
                      {formatPercent(errorRatePercent)}
                    </span>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
