import { OptionsInvalidIsinOverrideForm } from "../_components/override-form";
import type { OptionsInvalidIsinOverrideValues } from "../_components/schema";
import { fetchBackendOptionsInvalidIsins } from "../_lib/options-invalid-isin-server-api";

type PageProps = {
  searchParams: Promise<{
    stock_id?: string;
    underlier?: string;
    parent_isin?: string;
    f_type?: string;
    f_type_label?: string;
    m_date?: string;
    t_o_o?: string;
    t_o_t?: string;
    price?: string;
    name?: string;
    underlying_name?: string;
    is_live?: string;
  }>;
};

export default async function OptionsInvalidIsinOverridePage({
  searchParams,
}: PageProps) {
  const params = await searchParams;
  const stockId = Number.parseInt(params.stock_id ?? "", 10);
  const underlier = (params.underlier ?? "").trim();
  const parentIsin = (params.parent_isin ?? "").trim();

  const list = await fetchBackendOptionsInvalidIsins();
  const matched =
    list.rows.find((row) => stockId > 0 && row.stockId === stockId) ??
    list.rows.find(
      (row) =>
        row.underlier === underlier &&
        (!parentIsin || row.parentIsin === parentIsin),
    ) ??
    null;

  const defaults: OptionsInvalidIsinOverrideValues = {
    stockId:
      matched?.stockId ??
      (Number.isFinite(stockId) && stockId > 0 ? stockId : undefined),
    oldUnderlier: matched?.underlier || underlier,
    oldParentIsin: matched?.parentIsin || parentIsin,
    fType: matched?.fType || (params.f_type ?? "").trim() || undefined,
    mDate: matched?.mDate || (params.m_date ?? "").trim() || undefined,
    tOo: matched?.tOo || (params.t_o_o ?? "").trim() || undefined,
    tOt: matched?.tOt || (params.t_o_t ?? "").trim() || undefined,
    price: matched?.price || (params.price ?? "").trim() || undefined,
    realUnderlyingIsin: "",
  };

  return (
    <OptionsInvalidIsinOverrideForm
      defaults={defaults}
      details={{
        name: matched?.name || (params.name ?? "").trim(),
        underlyingName:
          matched?.underlyingName || (params.underlying_name ?? "").trim(),
        fTypeLabel: matched?.fTypeLabel || (params.f_type_label ?? "").trim(),
        mDate: defaults.mDate || "",
        price: defaults.price || "",
        isLive: matched?.isLive ?? (params.is_live ?? "").trim() === "1",
      }}
    />
  );
}
