"use client";

import { Fragment } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import type {
  DetailFinancialRow,
  FinancialStatementPeriod,
  SurfaceFinancialRow,
} from "@/lib/types";
import { cn } from "@/lib/utils";
import type {
  StatementInspectorSelection,
  StatementTreeNode,
  StatementTreeSection,
} from "@/lib/financials/statement-view-model";

type MatrixRow = SurfaceFinancialRow | DetailFinancialRow;

type StatementMatrixProps = {
  periods: FinancialStatementPeriod[];
  sections: StatementTreeSection[];
  selectedRowRef: StatementInspectorSelection | null;
  onToggleRow: (key: string) => void;
  onSelectRow: (selection: StatementInspectorSelection) => void;
  renderCellValue: (
    row: MatrixRow,
    periodId: string,
    previousPeriodId: string | null,
  ) => string;
  periodLabelFormatter: (value: string) => string;
  dense?: boolean;
};

function isSurfaceNode(
  node: StatementTreeNode,
): node is Extract<StatementTreeNode, { kind: "surface" }> {
  return node.kind === "surface";
}

function surfaceBadges(node: Extract<StatementTreeNode, { kind: "surface" }>) {
  const badges: Array<{
    label: string;
    tone: "default" | "warning" | "muted";
  }> = [];

  if (node.row.resolutionMethod === "formula_derived") {
    badges.push({
      label: "Formula",
      tone: node.row.confidence === "low" ? "warning" : "default",
    });
  }

  if (node.row.resolutionMethod === "not_meaningful") {
    badges.push({ label: "N/M", tone: "muted" });
  }

  if (node.row.confidence === "low") {
    badges.push({ label: "Low confidence", tone: "warning" });
  }

  const detailCount = node.row.detailCount ?? node.directDetailCount;
  if (detailCount > 0) {
    badges.push({ label: `${detailCount} details`, tone: "default" });
  }

  return badges;
}

function badgeClass(tone: "default" | "warning" | "muted", dense?: boolean) {
  const baseClasses = dense
    ? "rounded border px-1 py-0.5 text-[9px]"
    : "rounded border px-2 py-0.5 text-[10px]";

  if (tone === "warning") {
    return cn(
      baseClasses,
      "border-[#84614f] bg-[rgba(112,76,54,0.22)] text-[#ffd7bf]",
    );
  }

  if (tone === "muted") {
    return cn(
      baseClasses,
      "border-[color:var(--line-weak)] bg-[rgba(80,85,92,0.16)] text-[color:var(--terminal-muted)]",
    );
  }

  return cn(
    baseClasses,
    "border-[color:var(--line-weak)] bg-[rgba(88,102,122,0.16)] text-[color:var(--terminal-bright)]",
  );
}

function renderNodes(
  props: StatementMatrixProps & { nodes: StatementTreeNode[]; dense?: boolean },
) {
  const { dense = false } = props;
  const buttonSize = dense ? "size-6" : "size-8";
  const buttonClass = dense ? "rounded" : "rounded-lg";
  const labelSize = dense ? "text-[13px]" : "text-sm";
  const detailLabelSize = dense ? "text-[11px]" : "text-xs";
  const paddingY = dense ? "py-1.5" : "py-2";
  const gapClass = dense ? "gap-1.5" : "gap-2";

  return props.nodes.map((node) => {
    const labelIndent =
      node.kind === "detail" ? node.level * 16 + 16 : node.level * 16;
    const canToggle = isSurfaceNode(node) && node.expandable;
    const nextSelection: StatementInspectorSelection =
      node.kind === "surface"
        ? { kind: "surface", key: node.row.key }
        : {
            kind: "detail",
            key: node.row.key,
            parentKey: node.parentSurfaceKey,
          };
    const rowClass = cn(
      "financial-matrix-row",
      node.kind === "detail" && "financial-matrix-row-detail",
    );
    const stickyCellClass = cn(
      "financial-matrix-sticky-cell",
      node.kind === "detail" && "financial-matrix-sticky-cell-detail",
    );

    return (
      <Fragment key={node.id}>
        <tr className={rowClass}>
          <td className={stickyCellClass}>
            <div
              className={cn("flex min-w-0 items-start", gapClass)}
              style={{ paddingLeft: `${labelIndent}px` }}
            >
              {canToggle ? (
                <button
                  type="button"
                  aria-label={`${node.expanded ? "Collapse" : "Expand"} ${node.row.label} details`}
                  aria-expanded={node.expanded}
                  aria-controls={`statement-children-${node.id}`}
                  className={cn(
                    "mt-0.5 inline-flex shrink-0 items-center justify-center border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] text-[color:var(--terminal-bright)] transition hover:border-[color:var(--line-strong)]",
                    buttonSize,
                    buttonClass,
                  )}
                  onClick={(event) => {
                    event.stopPropagation();
                    props.onToggleRow(node.row.key);
                  }}
                >
                  {node.expanded ? (
                    <ChevronDown className="size-3.5" />
                  ) : (
                    <ChevronRight className="size-3.5" />
                  )}
                </button>
              ) : (
                <span
                  className={cn(
                    "inline-flex shrink-0 items-center justify-center text-[color:var(--terminal-muted)]",
                    buttonSize,
                  )}
                  aria-hidden="true"
                >
                  {node.kind === "detail" ? "·" : ""}
                </span>
              )}
              <button
                type="button"
                className={cn(
                  "flex min-w-0 flex-1 flex-col items-start gap-1 text-left",
                  paddingY,
                )}
                onClick={() => props.onSelectRow(nextSelection)}
              >
                <span
                  className={cn(
                    "block max-w-full truncate",
                    labelSize,
                    node.kind === "detail"
                      ? cn(
                          detailLabelSize,
                          "text-[color:var(--terminal-muted)]",
                        )
                      : "text-[color:var(--terminal-bright)]",
                    node.kind === "surface" &&
                      node.level > 0 &&
                      "text-[color:var(--accent)]",
                  )}
                  title={node.row.label}
                >
                  {node.row.label}
                </span>
                {node.kind === "detail" ? (
                  <span
                    className="block max-w-full truncate text-[10px] text-[color:var(--terminal-muted)]"
                    title={node.row.localName}
                  >
                    {node.row.localName}
                    {node.row.residualFlag ? " · residual" : ""}
                  </span>
                ) : surfaceBadges(node).length > 0 ? (
                  <div className="flex flex-wrap gap-1">
                    {surfaceBadges(node).map((badge) => (
                      <span
                        key={`${node.row.key}-${badge.label}`}
                        className={badgeClass(badge.tone, dense)}
                      >
                        {badge.label}
                      </span>
                    ))}
                  </div>
                ) : null}
              </button>
            </div>
          </td>
          {props.periods.map((period, index) => (
            <td
              key={`${node.id}-${period.id}`}
              className={cn(
                "financial-matrix-value-cell font-mono text-xs",
                node.kind === "detail" && "text-[color:var(--terminal-muted)]",
              )}
            >
              {props.renderCellValue(
                node.row,
                period.id,
                index > 0 ? (props.periods[index - 1]?.id ?? null) : null,
              )}
            </td>
          ))}
        </tr>
        {isSurfaceNode(node) && node.expanded ? (
          <>
            <tr id={`statement-children-${node.id}`} className="sr-only">
              <td colSpan={props.periods.length + 1}>
                Expanded children for {node.row.label}
              </td>
            </tr>
            {renderNodes({
              ...props,
              nodes: node.children,
              dense,
            })}
          </>
        ) : null}
      </Fragment>
    );
  });
}

export function StatementMatrix({
  periods,
  sections,
  selectedRowRef,
  onToggleRow,
  onSelectRow,
  renderCellValue,
  periodLabelFormatter,
  dense = false,
}: StatementMatrixProps) {
  return (
    <div className="financial-matrix-wrap">
      <table className="financial-matrix">
        <colgroup>
          <col className="financial-matrix-metric-col" />
          {periods.map((period) => (
            <col
              key={`col-${period.id}`}
              className="financial-matrix-period-col"
            />
          ))}
        </colgroup>
        <thead>
          <tr>
            <th className="financial-matrix-header">Metric</th>
            {periods.map((period) => (
              <th key={period.id} className="financial-matrix-header">
                <div className="flex flex-col gap-1">
                  <span className="text-sm font-medium text-[color:var(--terminal-bright)]">
                    {periodLabelFormatter(
                      period.periodEnd ?? period.filingDate,
                    )}
                  </span>
                  <span className="text-[11px] tracking-normal text-[color:var(--terminal-muted)]">
                    {period.filingType} · {period.periodLabel}
                  </span>
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {sections.map((section) => (
            <Fragment key={section.key}>
              {section.label ? (
                <tr className="financial-matrix-section-row">
                  <td
                    colSpan={periods.length + 1}
                    className="financial-matrix-section-cell"
                  >
                    {section.label}
                  </td>
                </tr>
              ) : null}
              {renderNodes({
                periods,
                sections,
                selectedRowRef,
                onToggleRow,
                onSelectRow,
                renderCellValue,
                periodLabelFormatter,
                dense,
                nodes: section.nodes,
              })}
            </Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
}
