import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link } from "wouter";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import type { RunsResponse } from "./types";
import { fetchAdminJson, getAdminErrorMessage } from "./api";

export default function AdminRuns() {
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState("");
  const [mode, setMode] = useState("");
  const [userId, setUserId] = useState("");
  const pageSize = 20;

  const queryString = useMemo(() => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("page_size", String(pageSize));
    if (status) params.set("status", status);
    if (mode) params.set("mode", mode);
    if (userId.trim()) params.set("user_id", userId.trim());
    return params.toString();
  }, [page, pageSize, status, mode, userId]);

  const runsQuery = useQuery<RunsResponse>({
    queryKey: ["admin/runs", page, status, mode, userId],
    queryFn: async () => {
      const data = await fetchAdminJson<RunsResponse>(`admin/runs?${queryString}`);
      if (!data) {
        throw new Error("No admin runs response returned.");
      }
      return data;
    },
  });

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

  if (runsQuery.isError) {
    return (
      <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
        {getAdminErrorMessage(runsQuery.error, "Failed to load runs.")}
      </div>
    );
  }

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

  const totalPages = Math.max(1, Math.ceil(data.total / data.page_size));

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
        <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Runs</p>
        <h2 className="text-2xl font-semibold">Strategy runs</h2>
        <div className="mt-4 grid gap-3 md:grid-cols-3">
          <Input
            placeholder="Filter by user_id"
            value={userId}
            onChange={(e) => {
              setUserId(e.target.value);
              setPage(1);
            }}
          />
          <Input
            placeholder="Status (RUNNING/STOPPED/ERROR)"
            value={status}
            onChange={(e) => {
              setStatus(e.target.value.toUpperCase());
              setPage(1);
            }}
          />
          <Input
            placeholder="Mode (PAPER/LIVE)"
            value={mode}
            onChange={(e) => {
              setMode(e.target.value.toUpperCase());
              setPage(1);
            }}
          />
        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="text-muted-foreground">
            <tr>
              <th className="px-4 py-2 text-left">Run</th>
              <th className="px-4 py-2 text-left">User</th>
              <th className="px-4 py-2 text-left">Status</th>
              <th className="px-4 py-2 text-left">Mode</th>
              <th className="px-4 py-2 text-left">Orders</th>
              <th className="px-4 py-2 text-left">Trades</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border/60">
            {data.runs.map((run) => (
              <tr key={run.run_id}>
                <td className="px-4 py-2">
                  <Link href={`/admin/runs/${run.run_id}`}>
                    <a className="text-primary hover:underline">{run.run_id}</a>
                  </Link>
                </td>
                <td className="px-4 py-2 text-xs">{run.user_id}</td>
                <td className="px-4 py-2 text-xs">{run.status}</td>
                <td className="px-4 py-2 text-xs">{run.mode ?? "-"}</td>
                <td className="px-4 py-2 text-xs">{run.order_count}</td>
                <td className="px-4 py-2 text-xs">{run.trade_count}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex items-center justify-between">
        <Button
          variant="outline"
          disabled={page <= 1}
          onClick={() => setPage((p) => Math.max(1, p - 1))}
        >
          Prev
        </Button>
        <span className="text-xs text-muted-foreground">
          Page {page} of {totalPages}
        </span>
        <Button
          variant="outline"
          disabled={page >= totalPages}
          onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
        >
          Next
        </Button>
      </div>
    </div>
  );
}
