"use client";

import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Activity, Gauge, RefreshCw } from "lucide-react";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";

const COLORS = {
  success: "#34d399",
  successDim: "rgba(52, 211, 153, 0.15)",
  warning: "#fbbf24",
  warningDim: "rgba(251, 191, 36, 0.15)",
  info: "#3b82f6",
  infoDim: "rgba(59, 130, 246, 0.15)",
  highlight: "#8b5cf6",
  highlightDim: "rgba(139, 92, 246, 0.15)",
  muted: "#71717a",
  grid: "rgba(255,255,255,0.04)",
  tooltipBg: "#18181b",
  tooltipBorder: "#27272a",
};

function hours(count: number): { time: string }[] {
  const now = new Date();
  return Array.from({ length: count }, (_, i) => {
    const d = new Date(now.getTime() - (count - 1 - i) * 3600_000);
    return { time: d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) };
  });
}

function sparkData(
  base: number,
  variance: number,
  count = 24
): { time: string; value: number }[] {
  return hours(count).map((h) => ({
    ...h,
    value: Math.max(0, base + (Math.random() - 0.5) * variance * 2),
  }));
}

const METRIC_CARDS = [
  { label: "Slow queries", value: "6", data: sparkData(6, 4), color: COLORS.success },
  { label: "Connections", value: "5/60", data: sparkData(5, 3), color: COLORS.success },
  { label: "Disk usage", value: "3%", data: sparkData(3, 1.5), color: COLORS.success },
  { label: "Disk IO", value: "1%", data: sparkData(1, 0.8), color: COLORS.info },
  { label: "Memory", value: "38%", data: sparkData(38, 8), color: COLORS.success },
  { label: "CPU", value: "2%", data: sparkData(2, 1.2), color: COLORS.success },
];

const SERVICE_DATA: {
  name: string;
  status: "healthy" | "unknown";
  color: string;
  dimColor: string;
  data: { time: string; value: number }[];
}[] = [
  {
    name: "Database",
    status: "healthy",
    color: COLORS.success,
    dimColor: COLORS.successDim,
    data: hours(24).map((h) => ({ ...h, value: 15 + Math.random() * 50 })),
  },
  {
    name: "Auth",
    status: "unknown",
    color: COLORS.warning,
    dimColor: COLORS.warningDim,
    data: hours(24).map((h) => ({ ...h, value: 5 + Math.random() * 20 })),
  },
  {
    name: "Realtime",
    status: "unknown",
    color: COLORS.warning,
    dimColor: COLORS.warningDim,
    data: hours(24).map((h) => ({
      ...h,
      value: Math.random() > 0.5 ? Math.random() * 30 : 0,
    })),
  },
  {
    name: "Storage",
    status: "unknown",
    color: COLORS.warning,
    dimColor: COLORS.warningDim,
    data: hours(24).map((h) => ({
      ...h,
      value: Math.random() > 0.6 ? Math.random() * 35 : 0,
    })),
  },
];

const API_REQUESTS_OVER_TIME = hours(24).map((h) => ({
  ...h,
  requests: Math.floor(Math.random() * 12),
}));

const API_ROUTES = [
  { route: "GET /auth/v1/health", count: 4 },
  { route: "GET /rest/v1", count: 3 },
  { route: "HEAD /rest-admin/v1/ready", count: 1 },
  { route: "POST /gateway/fetch", count: 1 },
  { route: "GET /health", count: 1 },
];

const MEMORY_DATA = hours(24).map((h) => ({
  ...h,
  used: 300 + Math.random() * 150,
  cached: 40 + Math.random() * 30,
}));

const CPU_DATA = hours(24).map((h) => ({
  ...h,
  usage: 0.5 + Math.random() * 4,
}));

function ChartTooltipContent({ payload, label }: { payload?: { name: string; value: number; color: string }[]; label?: string }) {
  if (!payload?.length) return null;
  return (
    <div
      className="rounded-md border px-3 py-2 text-xs shadow-lg"
      style={{
        backgroundColor: COLORS.tooltipBg,
        borderColor: COLORS.tooltipBorder,
      }}
    >
      <p className="mb-1 text-muted-foreground">{label}</p>
      {payload.map((entry) => (
        <p key={entry.name} style={{ color: entry.color }}>
          {entry.name}: {typeof entry.value === "number" ? entry.value.toFixed(1) : entry.value}
        </p>
      ))}
    </div>
  );
}

function MetricCard({
  label,
  value,
  data,
  color,
}: {
  label: string;
  value: string;
  data: { time: string; value: number }[];
  color: string;
}) {
  return (
    <div className="rounded-lg border border-border bg-card p-4">
      <p className="text-body-sm uppercase tracking-wider text-muted-foreground">
        {label}
      </p>
      <p className="mt-1 text-xl font-semibold">{value}</p>
      <div className="mt-3 h-10">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
            <defs>
              <linearGradient id={`grad-${label}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={color} stopOpacity={0.3} />
                <stop offset="100%" stopColor={color} stopOpacity={0} />
              </linearGradient>
            </defs>
            <Area
              type="monotone"
              dataKey="value"
              stroke={color}
              strokeWidth={1.5}
              fill={`url(#grad-${label})`}
              dot={false}
              isAnimationActive={false}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

function ServiceRow({
  name,
  status,
  color,
  dimColor,
  data,
}: {
  name: string;
  status: "healthy" | "unknown";
  color: string;
  dimColor: string;
  data: { time: string; value: number }[];
}) {
  return (
    <div className="border-b border-border last:border-b-0">
      <div className="flex items-center justify-between px-4 py-3">
        <p className="text-sm font-medium">{name}</p>
        <Badge variant={status === "healthy" ? "success" : "secondary"}>
          {status.toUpperCase()}
        </Badge>
      </div>
      <div className="px-4 pb-4 pt-1 h-20">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart data={data} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
            <Tooltip
              content={<ChartTooltipContent />}
              cursor={{ fill: dimColor }}
            />
            <Bar dataKey="value" radius={[2, 2, 0, 0]} isAnimationActive={false}>
              {data.map((entry, idx) => (
                <Cell
                  key={idx}
                  fill={entry.value > 0 ? color : "transparent"}
                  fillOpacity={0.8}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

export default function ObservabilityPage() {
  return (
    <div className="flex flex-1 min-h-0 overflow-auto">
      <div className="mx-auto w-full max-w-[1240px] px-6 py-8">
        <div className="flex items-start justify-between pb-6">
          <div>
            <h1 className="text-3xl font-semibold tracking-tight">
              Observability
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Service health, API gateway telemetry, and database performance.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm">
              <RefreshCw className="h-3.5 w-3.5" /> Refresh
            </Button>
            <Button variant="outline" size="sm">
              Last 24 hours
            </Button>
          </div>
        </div>

        <Tabs defaultValue="overview" className="space-y-0">
          <TabsList className="mb-5 h-10">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="api-gateway">API Gateway</TabsTrigger>
            <TabsTrigger value="database">Database</TabsTrigger>
          </TabsList>

          {/* ─── Overview ─── */}
          <TabsContent value="overview" className="mt-0 space-y-5">
            <div className="grid gap-4 md:grid-cols-3">
              {METRIC_CARDS.map((m) => (
                <MetricCard key={m.label} {...m} />
              ))}
            </div>

            <section className="rounded-lg border border-border bg-card overflow-hidden">
              <div className="border-b border-border px-4 py-3">
                <p className="text-sm font-semibold">Service Health</p>
              </div>
              {SERVICE_DATA.map((s) => (
                <ServiceRow key={s.name} {...s} />
              ))}
            </section>
          </TabsContent>

          {/* ─── API Gateway ─── */}
          <TabsContent value="api-gateway" className="mt-0 space-y-5">
            <section className="rounded-lg border border-border bg-card p-5">
              <div className="flex items-center justify-between">
                <p className="text-sm font-semibold">Requests over time</p>
                <Badge variant="secondary">Last 24 hours</Badge>
              </div>
              <div className="mt-4 h-64">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart
                    data={API_REQUESTS_OVER_TIME}
                    margin={{ top: 4, right: 4, left: -20, bottom: 0 }}
                  >
                    <defs>
                      <linearGradient id="gradReq" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor={COLORS.info} stopOpacity={0.25} />
                        <stop offset="100%" stopColor={COLORS.info} stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid stroke={COLORS.grid} vertical={false} />
                    <XAxis
                      dataKey="time"
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      interval="preserveStartEnd"
                    />
                    <YAxis
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      allowDecimals={false}
                    />
                    <Tooltip content={<ChartTooltipContent />} />
                    <Area
                      type="monotone"
                      dataKey="requests"
                      stroke={COLORS.info}
                      strokeWidth={2}
                      fill="url(#gradReq)"
                      dot={false}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </section>

            <section className="rounded-lg border border-border bg-card p-5">
              <div className="flex items-center justify-between">
                <p className="text-sm font-semibold">Total requests</p>
                <p className="text-xl font-semibold">10</p>
              </div>
              <div className="mt-4 h-40">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart
                    data={API_ROUTES}
                    layout="vertical"
                    margin={{ top: 0, right: 12, left: 0, bottom: 0 }}
                  >
                    <CartesianGrid stroke={COLORS.grid} horizontal={false} />
                    <XAxis
                      type="number"
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      allowDecimals={false}
                    />
                    <YAxis
                      type="category"
                      dataKey="route"
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      width={180}
                    />
                    <Tooltip content={<ChartTooltipContent />} />
                    <Bar
                      dataKey="count"
                      fill={COLORS.success}
                      fillOpacity={0.7}
                      radius={[0, 4, 4, 0]}
                      isAnimationActive={false}
                    />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </section>
          </TabsContent>

          {/* ─── Database ─── */}
          <TabsContent value="database" className="mt-0 space-y-5">
            <section className="rounded-lg border border-border bg-card p-5">
              <div className="flex items-center gap-2 text-sm font-semibold">
                <Gauge className="h-4 w-4" /> Memory usage
              </div>
              <p className="mt-1 text-2xl font-semibold">411.51 MB</p>
              <div className="mt-3 h-48">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart
                    data={MEMORY_DATA}
                    margin={{ top: 4, right: 4, left: -20, bottom: 0 }}
                  >
                    <defs>
                      <linearGradient id="gradMemUsed" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor={COLORS.success} stopOpacity={0.3} />
                        <stop offset="100%" stopColor={COLORS.success} stopOpacity={0} />
                      </linearGradient>
                      <linearGradient id="gradMemCached" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor={COLORS.warning} stopOpacity={0.3} />
                        <stop offset="100%" stopColor={COLORS.warning} stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid stroke={COLORS.grid} vertical={false} />
                    <XAxis
                      dataKey="time"
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      interval="preserveStartEnd"
                    />
                    <YAxis
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      unit=" MB"
                    />
                    <Tooltip content={<ChartTooltipContent />} />
                    <Area
                      type="monotone"
                      dataKey="used"
                      name="Used"
                      stackId="mem"
                      stroke={COLORS.success}
                      strokeWidth={1.5}
                      fill="url(#gradMemUsed)"
                    />
                    <Area
                      type="monotone"
                      dataKey="cached"
                      name="Cached"
                      stackId="mem"
                      stroke={COLORS.warning}
                      strokeWidth={1.5}
                      fill="url(#gradMemCached)"
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
              <div className="mt-3 flex gap-4 text-xs text-muted-foreground">
                <span className="flex items-center gap-1.5">
                  <span className="inline-block h-2 w-2 rounded-full" style={{ background: COLORS.success }} />
                  Used
                </span>
                <span className="flex items-center gap-1.5">
                  <span className="inline-block h-2 w-2 rounded-full" style={{ background: COLORS.warning }} />
                  Cached
                </span>
              </div>
            </section>

            <section className="rounded-lg border border-border bg-card p-5">
              <div className="flex items-center gap-2 text-sm font-semibold">
                <Activity className="h-4 w-4" /> CPU usage
              </div>
              <p className="mt-1 text-2xl font-semibold">1.56%</p>
              <div className="mt-3 h-48">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart
                    data={CPU_DATA}
                    margin={{ top: 4, right: 4, left: -20, bottom: 0 }}
                  >
                    <CartesianGrid stroke={COLORS.grid} vertical={false} />
                    <XAxis
                      dataKey="time"
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      interval="preserveStartEnd"
                    />
                    <YAxis
                      tick={{ fill: COLORS.muted, fontSize: 11 }}
                      tickLine={false}
                      axisLine={false}
                      unit="%"
                    />
                    <Tooltip content={<ChartTooltipContent />} />
                    <Line
                      type="monotone"
                      dataKey="usage"
                      name="CPU"
                      stroke={COLORS.success}
                      strokeWidth={2}
                      dot={false}
                    />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </section>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
