import { useQuery } from "@tanstack/react-query";
import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis } from "recharts";
import { Badge } from "@/components/ui/badge";
import { apiRequest } from "@/lib/queryClient";
import type { OverviewResponse } from "./types";

const StatCard = ({ label, value }: { label: string; value: number | string }) => (
  <div className="rounded-xl border border-border/60 bg-card/70 p-4 shadow-sm">
    <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">{label}</p>
    <p className="mt-2 text-2xl font-semibold">{value}</p>
  </div>
);

export default function AdminOverview() {
  const overviewQuery = useQuery<OverviewResponse>({
    queryKey: ["admin/overview"],
    queryFn: async () => {
      const res = await apiRequest("GET", "admin/overview");
      return res.json();
    },
  });

  if (overviewQuery.isLoading) {
    return <div className="text-sm text-muted-foreground">Loading overview…</div>;
  }

  if (!overviewQuery.data) {
    return <div className="text-sm text-muted-foreground">No data.</div>;
  }

  const data = overviewQuery.data;

  const runStatusData = [
    { name: "RUNNING", value: data.running_runs },
    { name: "STOPPED", value: data.stopped_runs },
    { name: "ERROR", value: data.error_runs },
  ];

  const activityData = [
    { name: "Orders", value: data.orders_last_24h },
    { name: "Trades", value: data.trades_last_24h },
    { name: "SIP", value: data.sip_executed_last_24h },
  ];

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Overview</p>
            <h2 className="text-2xl font-semibold">System health snapshot</h2>
          </div>
          <Badge variant="secondary">Admin</Badge>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <StatCard label="Total Users" value={data.total_users} />
        <StatCard label="Active Users (24h)" value={data.users_logged_in_last_24h} />
        <StatCard label="Total Runs" value={data.total_runs} />
        <StatCard label="Running Runs" value={data.running_runs} />
        <StatCard label="Paper Runs" value={data.paper_runs_count} />
        <StatCard label="Live Runs" value={data.live_runs_count} />
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
          <p className="text-sm font-semibold">Run Status</p>
          <div className="h-64 mt-4">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={runStatusData}>
                <XAxis dataKey="name" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} />
                <Bar dataKey="value" fill="hsl(var(--chart-1))" radius={[6, 6, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
          <p className="text-sm font-semibold">Activity (last 24h)</p>
          <div className="h-64 mt-4">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={activityData}>
                <XAxis dataKey="name" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} />
                <Bar dataKey="value" fill="hsl(var(--chart-2))" radius={[6, 6, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
        <p className="text-sm font-semibold">Latest Errors</p>
        {data.top_errors.length === 0 ? (
          <p className="text-sm text-muted-foreground mt-4">No recent errors.</p>
        ) : (
          <div className="mt-4 space-y-3">
            {data.top_errors.map((err, idx) => (
              <div
                key={`${err.ts}-${idx}`}
                className="rounded-lg border border-border/60 bg-background/60 p-3 text-sm"
              >
                <div className="flex items-center justify-between">
                  <span className="font-semibold">{err.event}</span>
                  <span className="text-xs text-muted-foreground">{err.ts}</span>
                </div>
                <p className="text-xs text-muted-foreground">
                  {err.source} • {err.user_id ?? "unknown"} • {err.run_id ?? "n/a"}
                </p>
                <p className="mt-1">{err.message ?? "No message"}</p>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
