"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";

import { DataTable } from "@/components/data-table";
import { SectionHeading } from "@/components/section-heading";
import { addWidgetToDashboards } from "@/lib/dashboards";
import { formatNumber, formatTimestamp } from "@/lib/format";
import type { MicrostructureSignalSummary, SignalSummary } from "@/lib/api/types";

function microValue(values: Record<string, unknown>, key: string): number | null {
  const value = values[key];
  return typeof value === "number" ? value : null;
}

function vvixValues(signal: SignalSummary) {
  const v = signal.latest_values;
  return {
    dvol: formatNumber(v.dvol),
    "rvvix 14d": formatNumber(v.rvvix_14d),
    "rvvix 30d": formatNumber(v.rvvix_30d),
    "qvvix 30d": formatNumber(v.qvvix_30d),
  };
}

function razorValues(signal: SignalSummary) {
  const v = signal.latest_values;
  return {
    pnl: formatNumber(v.razor_pnl),
    vrp: formatNumber(v.razor_vrp),
    "pnl z": formatNumber(v.razor_pnl_zscore),
    "vrp z": formatNumber(v.razor_vrp_zscore),
  };
}

export function SignalList({
  signals,
  microstructureSignals,
  microstructureEnabled,
}: {
  signals: SignalSummary[];
  microstructureSignals: MicrostructureSignalSummary[];
  microstructureEnabled: boolean;
}) {
  const router = useRouter();

  const vvix = signals.filter((s) => s.family === "vvix");
  const razor = signals.filter((s) => s.family === "razor");

  const vvixRows = vvix.map((signal) => ({
    symbol: signal.symbol,
    source: signal.latest_source ?? "—",
    ...vvixValues(signal),
    quality: signal.latest_quality ?? "unknown",
    updated: formatTimestamp(signal.latest_updated_at),
    actions: "add chart",
    _id: signal.id,
  }));

  const razorRows = razor.map((signal) => ({
    symbol: signal.symbol,
    source: signal.latest_source ?? "—",
    ...razorValues(signal),
    quality: signal.latest_quality ?? "unknown",
    updated: formatTimestamp(signal.latest_updated_at),
    actions: "add chart",
    _id: signal.id,
  }));

  return (
    <div className="pageStack">
      <SectionHeading
        kicker="Signals"
        title="Signal families"
        description="All signal families with quality, source, and freshness."
      />
      {vvix.length > 0 && (
        <div className="panel">
          <div className="panelHeader"><h3>VVIX</h3></div>
          <DataTable
            columns={["symbol", "source", "dvol", "rvvix 14d", "rvvix 30d", "qvvix 30d", "quality", "updated", "actions"]}
            rows={vvixRows}
            statusColumn="quality"
            onRowClick={(row) => router.push(`/signals/${row._id}`)}
            renderCell={(row, column) => {
              if (column !== "actions") return undefined;
              const signal = vvix.find((item) => item.id === row._id);
              if (!signal) return "—";
              return (
                <button
                  className="tabItem"
                  onClick={(event) => {
                    event.stopPropagation();
                    addWidgetToDashboards({
                      kind: "chart",
                      family: "signal",
                      sourceId: signal.id,
                      title: signal.name,
                      filters: { source: signal.latest_source ?? "dvol" },
                      colSpan: 6,
                      rowSpan: 1,
                    });
                  }}
                >
                  add
                </button>
              );
            }}
          />
        </div>
      )}
      {razor.length > 0 && (
        <div className="panel">
          <div className="panelHeader"><h3>Razor</h3></div>
          <DataTable
            columns={["symbol", "source", "pnl", "vrp", "pnl z", "vrp z", "quality", "updated", "actions"]}
            rows={razorRows}
            statusColumn="quality"
            onRowClick={(row) => router.push(`/signals/${row._id}`)}
            renderCell={(row, column) => {
              if (column !== "actions") return undefined;
              const signal = razor.find((item) => item.id === row._id);
              if (!signal) return "—";
              return (
                <button
                  className="tabItem"
                  onClick={(event) => {
                    event.stopPropagation();
                    addWidgetToDashboards({
                      kind: "chart",
                      family: "signal",
                      sourceId: signal.id,
                      title: signal.name,
                      filters: { source: signal.latest_source ?? "synthetic_7d_atm" },
                      colSpan: 6,
                      rowSpan: 1,
                    });
                  }}
                >
                  add
                </button>
              );
            }}
          />
        </div>
      )}
      {microstructureEnabled && microstructureSignals.length > 0 && (
        <div className="panel">
          <div className="panelHeader"><h3>Microstructure</h3></div>
          <DataTable
            columns={["signal", "prob up", "prob down", "expected move", "tradability", "quality", "updated"]}
            rows={microstructureSignals.map((signal) => ({
              signal: signal.name,
              "prob up": formatNumber(microValue(signal.latest_values, "prob_up")),
              "prob down": formatNumber(microValue(signal.latest_values, "prob_down")),
              "expected move": formatNumber(microValue(signal.latest_values, "expected_move_bps")),
              tradability: formatNumber(microValue(signal.latest_values, "tradability_score")),
              quality: signal.latest_quality ?? "unknown",
              updated: formatTimestamp(signal.latest_updated_at),
              _id: signal.id,
            }))}
            statusColumn="quality"
            onRowClick={() => router.push("/microstructure/predictions")}
          />
          <div style={{ marginTop: 10, fontSize: 12 }}>
            <Link href="/microstructure" style={{ color: "var(--accent)" }}>
              Open microstructure workspace
            </Link>
          </div>
        </div>
      )}
    </div>
  );
}
