import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

import { PageHeader } from "@/components/common/PageHeader";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { StatusChip } from "@/components/common/StatusChip";
import { ServiceHealthCard } from "@/widgets/ServiceHealthCard";
import { QueueWidget } from "@/widgets/QueueWidget";
import { StorageWidget } from "@/widgets/StorageWidget";
import { useDashboardStats } from "@/hooks/useDocuments";
import { useHealth } from "@/hooks/useHealth";

export function SystemHealthPage() {
  const { data } = useDashboardStats();
  const { data: health } = useHealth();

  return (
    <>
      <PageHeader
        title="System health"
        description="Backing services, queue metrics, throughput, and storage growth."
        actions={
          <Badge variant={health?.status === "ok" ? "success" : "warning"} className="font-mono">
            v{health?.version ?? "—"}
          </Badge>
        }
      />

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        <ServiceHealthCard />
        <QueueWidget />
        <Card>
          <CardHeader>
            <CardTitle>Embeddings & reranker</CardTitle>
            <CardDescription>Inference latency & queue depth</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <Row label="Embedding model" value="BAAI/bge-m3" badge="cpu" />
            <Row label="Reranker" value="BAAI/bge-reranker-v2-m3" badge="cpu" />
            <Row label="Embedding p95" value="142 ms" tone="ok" />
            <Row label="Reranker p95" value="380 ms" tone="warning" />
            <Row label="Inference workers" value="2" />
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Throughput (24h)</CardTitle>
            <CardDescription>Documents & chunks processed per minute</CardDescription>
          </CardHeader>
          <CardContent className="h-[260px]">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={data?.throughput ?? []}>
                <XAxis dataKey="time" tickLine={false} axisLine={false} fontSize={11} stroke="hsl(var(--muted-foreground))" />
                <YAxis tickLine={false} axisLine={false} fontSize={11} stroke="hsl(var(--muted-foreground))" />
                <Tooltip
                  contentStyle={{
                    background: "hsl(var(--popover))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 12,
                    fontSize: 12,
                  }}
                />
                <Line type="monotone" dataKey="docs_per_min" stroke="hsl(var(--primary))" strokeWidth={2} dot={false} />
                <Line type="monotone" dataKey="chunks_per_min" stroke="hsl(var(--muted-foreground))" strokeWidth={1.5} dot={false} strokeDasharray="3 4" />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <StorageWidget totalBytes={data?.total_storage_bytes ?? 0} growth={data?.storage_growth ?? []} />
      </div>
    </>
  );
}

function Row({
  label,
  value,
  badge,
  tone,
}: {
  label: string;
  value: string;
  badge?: string;
  tone?: "ok" | "warning";
}) {
  return (
    <div className="flex items-center justify-between gap-3 rounded-xl border border-border/70 bg-card/40 px-3 py-2">
      <div className="text-xs font-medium text-muted-foreground">{label}</div>
      <div className="flex items-center gap-2 font-mono text-sm">
        {value}
        {badge && <Badge variant="muted" className="font-mono">{badge}</Badge>}
        {tone && <StatusChip tone={tone === "ok" ? "ok" : "warning"} label={tone} />}
      </div>
    </div>
  );
}
