import {
  formatBlotterFieldDisplay,
  getColumnsBySection,
  isFullWidthColumn,
  mergeSelectOptions,
  ORDER_BLOTTER_SECTION_ORDER,
  ORDER_BLOTTER_SECTION_TITLES,
  type OrderBlotterColumnDef,
} from "@/lib/order-blotter/column-registry";
import { cn } from "@/lib/utils";
import type { ReactNode } from "react";

import type { OrderBlotterDetail } from "./detail-types";

const labelCell =
  "border border-border/60 bg-muted/50 px-2 py-1.5 text-left align-top font-semibold text-[11px] text-primary";
const valueCell =
  "border border-border/60 bg-card px-2 py-1.5 align-top text-foreground break-words";
const valueEmpty = "text-muted-foreground italic";

function MetaRow({
  cells,
}: {
  cells: { label: string; value: string; colSpan?: number }[];
}) {
  if (cells.length === 2) {
    return (
      <tr>
        <th scope="row" className={cn(labelCell, "w-[14%]")}>
          {cells[0].label}
        </th>
        <td className={cn(valueCell, "w-[36%]")}>{cells[0].value}</td>
        <th scope="row" className={cn(labelCell, "w-[14%]")}>
          {cells[1].label}
        </th>
        <td className={cn(valueCell, "w-[36%]")}>{cells[1].value}</td>
      </tr>
    );
  }

  const cell = cells[0];
  return (
    <tr>
      <th scope="row" className={cn(labelCell, "w-[14%]")}>
        {cell.label}
      </th>
      <td colSpan={cell.colSpan ?? 3} className={valueCell}>
        {cell.value}
      </td>
    </tr>
  );
}

function SectionTable({
  columns,
  fields,
  selectOptions,
  editable,
  onFieldChange,
}: {
  columns: OrderBlotterColumnDef[];
  fields: Record<string, string>;
  selectOptions: Record<string, Record<string, string>>;
  editable?: boolean;
  onFieldChange?: (key: string, value: string) => void;
}) {
  const rows: ReactNode[] = [];
  let i = 0;

  const renderValue = (col: OrderBlotterColumnDef) => {
    const raw = fields[col.key] ?? "";
    if (editable && onFieldChange) {
      return (
        <input
          className="w-full border-0 bg-transparent p-0 text-xs text-foreground outline-none"
          value={raw}
          onChange={(e) => onFieldChange(col.key, e.target.value)}
        />
      );
    }
    const value = formatBlotterFieldDisplay(col.key, raw, selectOptions);
    return <span className={cn(value === "—" && valueEmpty)}>{value}</span>;
  };

  while (i < columns.length) {
    const col = columns[i];

    if (isFullWidthColumn(col)) {
      rows.push(
        <tr key={col.key}>
          <th scope="row" className={cn(labelCell, "w-[18%]")}>
            {col.label}
          </th>
          <td colSpan={3} className={valueCell}>
            {renderValue(col)}
          </td>
        </tr>,
      );
      i += 1;
      continue;
    }

    const colB = i + 1 < columns.length && !isFullWidthColumn(columns[i + 1]) ? columns[i + 1] : null;

    rows.push(
      <tr key={col.key}>
        <th scope="row" className={cn(labelCell, "w-[18%]")}>
          {col.label}
        </th>
        <td className={cn(valueCell, "w-[32%]")}>{renderValue(col)}</td>
        {colB ? (
          <>
            <th scope="row" className={cn(labelCell, "w-[18%]")}>
              {colB.label}
            </th>
            <td className={cn(valueCell, "w-[32%]")}>{renderValue(colB)}</td>
          </>
        ) : (
          <>
            <th scope="row" className={cn(labelCell, "bg-muted/30")} />
            <td className={cn(valueCell, "bg-muted/20")} />
          </>
        )}
      </tr>,
    );

    i += colB ? 2 : 1;
  }

  return (
    <table className="mb-2.5 w-full table-fixed border-collapse overflow-hidden rounded-b-lg border border-border/60 border-t-0">
      <tbody>{rows}</tbody>
    </table>
  );
}

export function OrderBlotterViewDocument({
  detail,
  editable,
  onFieldChange,
}: {
  detail: OrderBlotterDetail;
  editable?: boolean;
  onFieldChange?: (key: string, value: string) => void;
}) {
  const columnsBySection = getColumnsBySection();
  const selectOptions = mergeSelectOptions(detail.selectOptions);
  const txnId =
    detail.transactionId != null && detail.transactionId > 0 ? String(detail.transactionId) : "—";
  const snLabel = detail.id > 0 ? String(detail.id) : "New";

  return (
    <div className="text-xs leading-snug text-foreground">
      <div className="mb-3 border-b border-border/70 pb-2.5 text-center">
        <h2 className="m-0 font-bold text-lg uppercase tracking-wide text-primary">Order Blotter</h2>
        <p className="m-0 text-muted-foreground">Register S/N {snLabel}</p>
      </div>

      <div className="mb-3 overflow-hidden rounded-xl border border-border/60">
        <table className="w-full table-fixed border-collapse">
          <tbody>
            <MetaRow
              cells={[
                { label: "S/N", value: snLabel },
                { label: "Transaction ID", value: txnId },
              ]}
            />
            {detail.portfolioLabel ? (
              <MetaRow cells={[{ label: "Portfolio", value: detail.portfolioLabel, colSpan: 3 }]} />
            ) : null}
            <MetaRow
              cells={[
                { label: "Order #", value: detail.indexOrderNumber ?? "—" },
                { label: "Client", value: detail.indexClientName ?? "—" },
              ]}
            />
            <MetaRow cells={[{ label: "Created", value: detail.createdAt || "—", colSpan: 3 }]} />
          </tbody>
        </table>
      </div>

      {ORDER_BLOTTER_SECTION_ORDER.map((sectionId) => {
        const sectionColumns = columnsBySection[sectionId];
        if (!sectionColumns?.length) return null;
        const sectionTitle =
          detail.sectionTitles?.[sectionId]?.trim() || ORDER_BLOTTER_SECTION_TITLES[sectionId];

        return (
          <section key={sectionId} className="overflow-hidden">
            <div className="rounded-t-lg border border-border/60 border-b-0 bg-primary px-2.5 py-1.5 font-bold text-[11px] uppercase tracking-wider text-primary-foreground">
              {sectionTitle}
            </div>
            <SectionTable
              columns={sectionColumns}
              fields={detail.fields}
              selectOptions={selectOptions}
              editable={editable}
              onFieldChange={onFieldChange}
            />
          </section>
        );
      })}
    </div>
  );
}
