"use client";

import { useRouter } from "next/navigation";

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

import { COMPOSITE_DASHBOARDS } from "./composite-config";

function labelize(key: string) {
  return key.replace(/_/g, " ").replace(/\b\w/g, (match) => match.toUpperCase());
}

function fmtValue(value: unknown) {
  return typeof value === "number" ? formatMetricValue(value) : "—";
}

export function CompositeList({ signals }: { signals: CompositeSignalSummary[] }) {
  const router = useRouter();

  const rows = COMPOSITE_DASHBOARDS.map((dashboard) => {
    const signal = signals.find((item) => item.id === dashboard.signalId) ?? null;
    const entries = Object.entries(signal?.latest_values ?? {}).slice(0, 4);
    return {
      dashboard: dashboard.title,
      scope: dashboard.scopeLabel,
      primary: entries[0] ? `${labelize(entries[0][0])}: ${fmtValue(entries[0][1])}` : "—",
      secondary: entries[1] ? `${labelize(entries[1][0])}: ${fmtValue(entries[1][1])}` : "—",
      tertiary: entries[2] ? `${labelize(entries[2][0])}: ${fmtValue(entries[2][1])}` : "—",
      quality: signal?.latest_quality ?? "unknown",
      updated: formatTimestamp(signal?.latest_updated_at ?? null),
      actions: "add",
      _id: dashboard.id,
      _signalId: dashboard.signalId,
      _title: dashboard.title,
    };
  });

  return (
    <div className="pageStack">
      <SectionHeading
        kicker="Composite"
        title="Composite market state"
        description="Fear/greed, direction, and fragility separated into interpretable asset and market views."
      />
      <div className="panel">
        <div className="panelHeader"><h3>Dashboards</h3></div>
        <DataTable
          columns={["dashboard", "scope", "primary", "secondary", "tertiary", "quality", "updated", "actions"]}
          rows={rows}
          statusColumn="quality"
          onRowClick={(row) => router.push(`/composite/${row._id}`)}
          renderCell={(row, column) => {
            if (column !== "actions") return undefined;
            return (
              <button
                className="tabItem"
                onClick={(event) => {
                    event.stopPropagation();
                    addWidgetToDashboards({
                      kind: "chart",
                      family: "composite",
                      sourceId: String(row._signalId),
                      title: String(row._title),
                      filters: {},
                      colSpan: 6,
                      rowSpan: 1,
                  });
                }}
              >
                add
              </button>
            );
          }}
        />
      </div>
    </div>
  );
}
