"use client";

import { useEffect, useState } from "react";

import { DataTable } from "@/components/data-table";
import { MetricCard } from "@/components/metric-card";
import { SectionHeading } from "@/components/section-heading";
import { SignalLineChart } from "@/components/line-chart";
import { StatusBadge } from "@/components/status-badge";
import { getRuns, getRunsSummary, getSignalLatest, getSignalSeries } from "@/lib/api/client";
import { formatNumber, formatTimestamp } from "@/lib/format";
import { DEFAULT_INITIAL_RANGE_DAYS, RANGE_OPTIONS, rangeWindowIso, seriesMaxPoints } from "@/lib/ranges";
import type { RunRecord, RunsSummary, SignalSeriesResponse, SignalSummary } from "@/lib/api/types";
import { useStream } from "@/lib/ws/use-stream";

export function SignalWorkspace({
  signalId,
  initialLatest,
  initialSeries,
  initialRuns,
  initialRunSummary,
  initialSource,
}: {
  signalId: string;
  initialLatest: SignalSummary | null;
  initialSeries: SignalSeriesResponse | null;
  initialRuns: RunRecord[];
  initialRunSummary: RunsSummary;
  initialSource: string;
}) {
  const [source, setSource] = useState(initialLatest?.latest_source ?? initialSource);
  const [rangeDays, setRangeDays] = useState(DEFAULT_INITIAL_RANGE_DAYS);
  const [quality, setQuality] = useState("all");
  const [latest, setLatest] = useState(initialLatest);
  const [series, setSeries] = useState(initialSeries);
  const [runs, setRuns] = useState(initialRuns);
  const [summary, setSummary] = useState(initialRunSummary);
  const [fetching, setFetching] = useState(false);

  useStream((event) => {
    if (event.event === "signal.updated" || event.event === "run.updated") {
      void refresh();
    }
  });

  useEffect(() => {
    void refresh();
  }, [source, rangeDays, quality]);

  useEffect(() => {
    if (initialLatest?.latest_source) {
      setSource(initialLatest.latest_source);
    }
  }, [initialLatest?.latest_source]);

  async function refresh() {
    setFetching(true);
    const nextLatest = await getSignalLatest(signalId, source);
    const { start, end } = rangeWindowIso(rangeDays, nextLatest?.latest_updated_at ?? latest?.latest_updated_at);
    const [nextSeries, nextRuns, nextSummary] = await Promise.all([
      getSignalSeries(
        signalId,
        source,
        start,
        end,
        quality === "all" ? undefined : quality,
        seriesMaxPoints(rangeDays),
      ),
      getRuns({ limit: 12 }),
      getRunsSummary(),
    ]);
    setLatest(nextLatest);
    setSeries(nextSeries);
    setRuns(nextRuns);
    setSummary(nextSummary);
    setFetching(false);
  }

  const family = latest?.family ?? (signalId.includes("razor") ? "razor" : "vvix");
  const isRazor = family === "razor";
  const headingTitle = latest?.name ? `${latest.name} workspace` : `${signalId} workspace`;
  const headingDescription = isRazor
    ? "Razor PnL, VRP companion, z-scores, and regime state."
    : "DVOL/BVIX, realized VVIX, qVVIX, surface quality, and operational context.";
  const qualityOptions = isRazor
    ? ["all", "ok", "initializing"]
    : ["all", "ok", "low_coverage", "insufficient_data"];
  const lines = isRazor
    ? [
        { key: "razor_pnl", label: "Razor PnL", color: "#6ac2ff" },
        { key: "razor_vrp", label: "Razor VRP", color: "#ffd166" },
        { key: "razor_pnl_zscore", label: "Razor PnL Z", color: "#f58549" },
        { key: "razor_vrp_zscore", label: "Razor VRP Z", color: "#8dd3c7" },
      ]
    : [
        { key: "dvol", label: "DVOL", color: "#6ac2ff" },
        { key: "rvvix_14d", label: "rVVIX 14D", color: "#ffd166" },
        { key: "rvvix_30d", label: "rVVIX 30D", color: "#f58549" },
        { key: "qvvix_30d", label: "qVVIX 30D", color: "#8dd3c7" },
      ];
  const chartData = (series?.points ?? []).map((point) => ({
    ts: point.ts,
    dvol: point.dvol,
    rvvix_14d: point.rvvix_14d,
    rvvix_30d: point.rvvix_30d,
    qvvix_30d: point.qvvix_30d,
    razor_pnl: point.razor_pnl,
    razor_vrp: point.razor_vrp,
    razor_pnl_zscore: point.razor_pnl_zscore,
    razor_vrp_zscore: point.razor_vrp_zscore,
  }));

  const runRows = runs.slice(0, 8).map((run) => ({
    ts: formatTimestamp(run.logical_ts),
    dataset: run.dataset,
    status: run.status,
    rows: run.rows_written_raw,
    duration: `${(run.duration_ms / 1000).toFixed(1)}s`,
  }));

  return (
    <div className="pageStack">
      <SectionHeading kicker="Signals" title={headingTitle} description={headingDescription} />
      <div className="twoCol">
        <div className="twoColNarrow">
          <div className="panel">
            <div className="toolbar" style={{ flexDirection: "column", alignItems: "stretch", gap: 8 }}>
              <label>
                Source
                <select value={source} onChange={(event) => setSource(event.target.value)}>
                  {(latest?.available_sources ?? [source]).map((item) => (
                    <option key={item} value={item}>{item}</option>
                  ))}
                </select>
              </label>
              <label>
                Range
                <select value={rangeDays} onChange={(event) => setRangeDays(Number(event.target.value))}>
                  {RANGE_OPTIONS.map((days) => (
                    <option key={days} value={days}>{days}d</option>
                  ))}
                </select>
              </label>
              <label>
                Quality
                <select value={quality} onChange={(event) => setQuality(event.target.value)}>
                  {qualityOptions.map((item) => (
                    <option key={item} value={item}>{item}</option>
                  ))}
                </select>
              </label>
            </div>
          </div>
          <StatusBadge
            label={fetching ? "LOADING" : summary.gap_count || summary.failed_count ? "ATTENTION" : "STABLE"}
            tone={fetching ? "neutral" : summary.gap_count || summary.failed_count ? "warn" : "ok"}
          />
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {isRazor ? (
              <>
                <MetricCard label="Razor PnL" value={formatNumber(latest?.latest_values.razor_pnl)} tone="ok" />
                <MetricCard label="Razor VRP" value={formatNumber(latest?.latest_values.razor_vrp)} tone="warn" />
                <MetricCard label="PnL Z-Score" value={formatNumber(latest?.latest_values.razor_pnl_zscore)} tone="warn" />
                <MetricCard
                  label="Trade Band"
                  value={String(series?.points.at(-1)?.trade_band ?? "neutral").replace("_", " ")}
                  tone={series?.points.at(-1)?.trade_band === "double_buy" ? "live" : series?.points.at(-1)?.trade_band === "double_sell" ? "warn" : "neutral"}
                />
              </>
            ) : (
              <>
                <MetricCard label="DVOL" value={formatNumber(latest?.latest_values.dvol)} tone="ok" />
                <MetricCard label="rVVIX 14D" value={formatNumber(latest?.latest_values.rvvix_14d)} tone="warn" />
                <MetricCard label="rVVIX 30D" value={formatNumber(latest?.latest_values.rvvix_30d)} tone="warn" />
                <MetricCard label="qVVIX 30D" value={formatNumber(latest?.latest_values.qvvix_30d)} tone="live" />
              </>
            )}
          </div>
          <div className="panel">
            <div className="panelHeader"><h3>Context</h3></div>
            <ul className="summaryList">
              <li><span>Points</span><strong>{series?.points.length ?? 0}</strong></li>
              <li><span>Gaps</span><strong>{summary.gap_count}</strong></li>
              <li><span>Failures</span><strong>{summary.failed_count}</strong></li>
              <li><span>Quality</span><strong>{latest?.latest_quality ?? "unknown"}</strong></li>
              {isRazor ? (
                <li><span>Active band</span><strong>{series?.points.at(-1)?.trade_band ?? "neutral"}</strong></li>
              ) : null}
            </ul>
          </div>
        </div>
        <div className="twoColWide">
          <SignalLineChart
            data={chartData}
            lines={lines}
            referenceLines={isRazor ? [{ y: 0, label: "zero" }] : undefined}
            dualAxis={isRazor}
          />
          <div className="panel">
            <div className="panelHeader"><h3>Recent runs</h3></div>
            <DataTable
              columns={["ts", "dataset", "status", "rows", "duration"]}
              rows={runRows}
              statusColumn="status"
            />
          </div>
        </div>
      </div>
    </div>
  );
}
