"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import { MetricCard } from "@/components/metric-card";
import { SectionHeading } from "@/components/section-heading";
import { StatusBadge } from "@/components/status-badge";
import { getExecutionAccounts, getExecutionHealth, getExecutionVenues } from "@/lib/api/client";
import { formatMetricValue } from "@/lib/format";
import type {
  ExecutionAccountSummary,
  ExecutionHealthRecord,
  ExecutionVenueSummary,
} from "@/lib/api/types";

import { EXECUTION_SECTIONS } from "./execution-config";

export function ExecutionList({
  venues,
  accounts,
  health,
}: {
  venues: ExecutionVenueSummary[];
  accounts: ExecutionAccountSummary[];
  health: ExecutionHealthRecord[];
}) {
  const [snapshot, setSnapshot] = useState({ venues, accounts, health });
  const [loading, setLoading] = useState(
    venues.length === 0 && accounts.length === 0 && health.length === 0,
  );

  useEffect(() => {
    let cancelled = false;
    async function load() {
      setLoading(true);
      const [nextVenues, nextAccounts, nextHealth] = await Promise.all([
        getExecutionVenues(),
        getExecutionAccounts(),
        getExecutionHealth(),
      ]);
      if (cancelled) {
        return;
      }
      setSnapshot({
        venues: nextVenues,
        accounts: nextAccounts,
        health: nextHealth,
      });
      setLoading(false);
    }

    void load();
    return () => {
      cancelled = true;
    };
  }, []);

  const onlineCount = snapshot.health.filter((item) => item.status === "online").length;
  return (
    <div className="pageStack">
      <SectionHeading
        kicker="Execution"
        title="DEX operator control"
        description="Venue-aware operator workflows for Derive, Hyperliquid, Lighter, and Bebop."
      />
      <div className="gridCols4">
        <MetricCard label="Venues" value={String(snapshot.venues.length)} tone="ok" />
        <MetricCard label="Accounts" value={String(snapshot.accounts.length)} tone="neutral" />
        <MetricCard label="Healthy venues" value={String(onlineCount)} tone={onlineCount > 0 ? "ok" : "warn"} />
        <MetricCard
          label="Private WS"
          value={formatMetricValue(snapshot.health.filter((item) => item.private_ws_connected).length, "count")}
          tone="neutral"
        />
      </div>
      <div className="panel">
        <div className="panelHeader"><h3>Venue capabilities</h3></div>
        <ul className="summaryList">
          {snapshot.venues.map((venue) => (
            <li key={venue.venue}>
              <span>
                <strong>{venue.venue}</strong> · {venue.supported_instrument_types.join(", ")}
              </span>
              <strong>{venue.supported_order_types.join(", ")}</strong>
            </li>
          ))}
          {!loading && snapshot.venues.length === 0 ? (
            <li>
              <span>Execution venues are temporarily unavailable.</span>
              <strong>Check the execution API on the host.</strong>
            </li>
          ) : null}
        </ul>
      </div>
      <div className="panel">
        <div className="panelHeader"><h3>Accounts</h3></div>
        <ul className="summaryList">
          {loading ? (
            <li>
              <span>Loading execution accounts…</span>
              <strong>Fetching current venue state.</strong>
            </li>
          ) : snapshot.accounts.length === 0 ? (
            <li>
              <span>No execution accounts configured.</span>
              <strong>Provide `config/execution_accounts.json` on the host.</strong>
            </li>
          ) : (
            snapshot.accounts.map((account) => (
              <li key={`${account.venue}-${account.label}`}>
                <span>
                  <strong>{account.label}</strong> · {account.venue} · {account.enabled_assets.join(", ")}
                </span>
                <StatusBadge label={account.kill_switch ? "KILL" : account.enabled ? "ENABLED" : "DISABLED"} tone={account.kill_switch ? "error" : account.enabled ? "ok" : "warn"} />
              </li>
            ))
          )}
        </ul>
      </div>
      <div className="tabBar">
        {EXECUTION_SECTIONS.map((section) => (
          <Link key={section.id} href={`/execution/${section.id}`} className="tabItem">
            {section.title}
          </Link>
        ))}
      </div>
    </div>
  );
}
