import { useQuery } from "@tanstack/react-query";
import { AlertCircle, RotateCw, ShieldCheck } from "lucide-react";
import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis } from "recharts";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { fetchAdminJson, getAdminErrorMessage } from "./api";
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>
);

function isOverviewEmpty(data: OverviewResponse) {
  return (
    data.total_users === 0 &&
    data.total_runs === 0 &&
    data.users_logged_in_last_24h === 0 &&
    data.orders_last_24h === 0 &&
    data.trades_last_24h === 0 &&
    data.sip_executed_last_24h === 0 &&
    data.unresolved_orders === 0 &&
    data.blocked_strategies === 0 &&
    data.open_support_tickets === 0 &&
    data.top_errors.length === 0
  );
}

export default function AdminOverview() {
  const overviewQuery = useQuery<OverviewResponse>({
    queryKey: ["admin/overview"],
    queryFn: async () => {
      const data = await fetchAdminJson<OverviewResponse>("admin/overview");
      if (!data) {
        throw new Error("No overview response returned.");
      }
      return data;
    },
  });

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

  if (overviewQuery.isError) {
    return (
      <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-5 text-sm text-destructive">
        <div className="flex items-start gap-3">
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
          <div className="space-y-3">
            <div>
              <p className="font-semibold">Admin overview unavailable</p>
              <p className="mt-1 text-sm text-destructive/90">
                {getAdminErrorMessage(overviewQuery.error, "Failed to load admin overview.")}
              </p>
            </div>
            <Button
              variant="outline"
              size="sm"
              className="border-destructive/30 bg-transparent text-destructive hover:bg-destructive/10"
              onClick={() => void overviewQuery.refetch()}
            >
              <RotateCw className="mr-2 h-4 w-4" />
              Retry
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (!overviewQuery.data) {
    return (
      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 text-sm text-muted-foreground shadow-sm">
        No admin metrics yet.
      </div>
    );
  }

  const data = overviewQuery.data;
  const needsAttention =
    data.error_runs > 0 ||
    data.unresolved_orders > 0 ||
    data.blocked_strategies > 0 ||
    data.open_support_tickets > 0;

  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 },
  ];

  if (isOverviewEmpty(data)) {
    return (
      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
        <div className="flex items-center gap-3">
          <ShieldCheck className="h-5 w-5 text-primary" />
          <div>
            <p className="text-sm font-semibold text-foreground">No admin metrics yet</p>
            <p className="text-sm text-muted-foreground">
              The admin API is reachable, but no users, runs, or support activity have been recorded yet.
            </p>
          </div>
        </div>
        <div className="mt-4">
          <Button variant="outline" size="sm" onClick={() => void overviewQuery.refetch()}>
            <RotateCw className="mr-2 h-4 w-4" />
            Retry
          </Button>
        </div>
      </div>
    );
  }

  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 gap-4">
          <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>
          <div className="flex items-center gap-2">
            <Badge variant={needsAttention ? "secondary" : "default"}>
              {needsAttention ? "Needs attention" : "Healthy"}
            </Badge>
            <Button variant="outline" size="sm" onClick={() => void overviewQuery.refetch()}>
              <RotateCw className="mr-2 h-4 w-4" />
              Retry
            </Button>
          </div>
        </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} />
        <StatCard label="Unresolved Orders" value={data.unresolved_orders} />
        <StatCard label="Blocked Strategies" value={data.blocked_strategies} />
        <StatCard label="Open Support Tickets" value={data.open_support_tickets} />
      </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="mt-4 h-64">
            <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="mt-4 h-64">
            <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="mt-4 text-sm text-muted-foreground">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>
  );
}
