"use client";

import { toastApiError } from "@/lib/toast-api-error";
import * as React from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";

import { ArrowLeft } from "lucide-react";
import { toast } from "sonner";

import { getCustomerTransactionModule } from "@/app/customer/_lib/customer-asset-modules";
import type { CustomerTransactionModuleId } from "@/app/customer/_lib/customer-asset-modules";
import { CustomerMutationError } from "@/app/customer/_lib/customer-mutation-error";
import { loadStockFundFormOptionsClient } from "@/app/customer/[tenant]/stock-funds/_lib/stock-funds-api";
import { loadBondFormOptionsClient } from "@/app/customer/[tenant]/bond/_lib/bond-api";
import { loadBondFundFormOptionsClient } from "@/app/customer/[tenant]/bond-funds/_lib/bond-funds-api";
import { loadCommodityFormOptionsClient } from "@/app/customer/[tenant]/commodity/_lib/commodity-api";
import { COMMODITY_SALE_TRANSACTION_TYPE } from "@/app/customer/[tenant]/commodity/_lib/map-commodity-form-values";
import { loadCryptoFormOptionsClient } from "@/app/customer/[tenant]/crypto/_lib/crypto-api";
import { CRYPTO_RESALE_TRANSACTION_TYPE } from "@/app/customer/[tenant]/crypto/_lib/map-crypto-form-values";
import { loadCallDepositFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/call-deposit/_lib/call-deposit-api";
import { loadFixedDepositFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/fixed-deposit/_lib/fixed-deposit-api";
import { loadFxAccumulatorFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/fx-accumulator/_lib/fx-accumulator-api";
import { loadLeverageFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/leverage/_lib/leverage-api";
import { loadSwapsFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/swaps/_lib/swaps-api";
import { loadCurrencyConversionFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/currency-conversion/_lib/currency-conversion-api";
import { loadCashWithdrawalFormOptionsClient } from "@/app/customer/[tenant]/fx-currency/cash-withdrawal/_lib/cash-withdrawal-api";
import { loadMixedFundFormOptionsClient } from "@/app/customer/[tenant]/mixed-funds/_lib/mixed-funds-api";
import { loadOtherAssetFormOptionsClient } from "@/app/customer/[tenant]/other-assets/_lib/other-assets-api";
import { OTHER_ASSET_SALE_TRANSACTION_TYPE } from "@/app/customer/[tenant]/other-assets/_lib/map-other-asset-form-values";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { ModuleTransactionFormValues } from "@/components/form/schemas/module-transaction-schema";
import type {
  BondFormValues,
  BondFundsFormValues,
} from "@/components/form/schemas/bond-transaction-schema";
import { BOND_SALE_TRANSACTION_TYPE } from "@/components/form/schemas/bond-transaction-schema";
import type { CallDepositFormValues } from "@/components/form/schemas/call-deposit-transaction-schema";
import {
  DEPOSIT_SALE_TRANSACTION_TYPE,
  type DepositFormValues,
} from "@/components/form/schemas/deposit-transaction-schema";
import type {
  CryptoFormValues,
  OtherAssetsFormValues,
} from "@/components/form/schemas/extended-stock-transaction-schema";
import type { FxAccumulatorFormValues } from "@/components/form/schemas/fx-accumulator-transaction-schema";
import type { CurrencyConversionFormValues } from "@/components/form/schemas/currency-conversion-transaction-schema";
import type { CashWithdrawalFormValues } from "@/components/form/schemas/cash-withdrawal-transaction-schema";
import type { SwapsFormValues } from "@/components/form/schemas/swaps-transaction-schema";

import { loadStructureCreateContextClient } from "@/app/customer/[tenant]/structure/_lib/structure-api";
import { useCustomerModuleListPath } from "./list-table-form-actions";
import { mapListRowToFormValues } from "./map-row-to-form-values";
import { getModuleIcon } from "./module-icons";
import { BondTransactionForm } from "./bond-transaction-form";
import { CallDepositTransactionForm } from "./call-deposit-transaction-form";
import { CurrencyConversionTransactionForm } from "./currency-conversion-transaction-form";
import { CashWithdrawalTransactionForm } from "./cash-withdrawal-transaction-form";
import { DepositTransactionForm } from "./deposit-transaction-form";
import { FxAccumulatorTransactionForm } from "./fx-accumulator-transaction-form";
import { ModuleTransactionForm } from "./module-transaction-form";
import { StockTransactionForm } from "./stock-transaction-form";
import { StructureTransactionForm } from "./structure-transaction-form";
import { SwapsTransactionForm } from "./swaps-transaction-form";
import type { TransactionModuleFormConfig } from "./types";
import {
  SALE_TRANSACTION_TYPE,
  type StructureFormValues,
} from "@/components/form/schemas/structure-transaction-schema";

type TransactionModuleFormPageProps = {
  config: TransactionModuleFormConfig;
};

export function TransactionModuleFormPage({ config }: TransactionModuleFormPageProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const listPath = useCustomerModuleListPath(config.returnListPath ?? config.listPath);
  const recordId = searchParams.get("id")?.trim() || null;
  const refId = searchParams.get("refId")?.trim() || null;
  const parentId = searchParams.get("pid")?.trim() || null;
  const childKind = searchParams.get("child")?.trim() || null;
  const tempId = searchParams.get("temp_id")?.trim() || null;
  const expiredId = searchParams.get("expired_id")?.trim() || null;
  const hideFromTemp = searchParams.get("hide")?.trim() === "1";
  const transactionModule = getCustomerTransactionModule(
    config.moduleId as CustomerTransactionModuleId,
  );
  const seedRow = refId ? transactionModule.getByRefId(refId) : undefined;
  const isEdit = Boolean(recordId || seedRow);
  /** Legacy quick-update (`by_hidden` / `hide=1`) — same prefill as create, update-style UI. */
  const isTempQuickUpdate = Boolean(tempId && hideFromTemp && !isEdit);
  const showUpdateChrome = isEdit || isTempQuickUpdate;
  const isStructureSale = config.moduleId === "structure" && Boolean(parentId) && !isEdit;
  const isBondSale = config.moduleId === "bond" && Boolean(parentId) && !isEdit;
  const isBondFundSale = config.moduleId === "bond-funds" && Boolean(parentId) && !isEdit;
  // Yii1 commodity sale is pid without child; option/accumulator use dedicated child forms.
  const isCommoditySale =
    config.moduleId === "commodity" &&
    Boolean(parentId) &&
    !isEdit &&
    (!childKind || childKind === "sale");
  const isOtherAssetSale = config.moduleId === "other-assets" && Boolean(parentId) && !isEdit;
  // Yii1 Crypto Resale via crypto_sale/create?pid= — keeps parent Ref. ID (uid).
  const isCryptoResale = config.moduleId === "crypto" && Boolean(parentId) && !isEdit;
  // Yii1 Fixed/Call Deposit sale via create?pid= — t_o_t=1473, keep parent uid.
  const isFixedDepositSale = config.moduleId === "fixed-deposit" && Boolean(parentId) && !isEdit;
  const isCallDepositSale = config.moduleId === "call-deposit" && Boolean(parentId) && !isEdit;
  // Yii1 Leverage sale via leverage_form/create?pid= — t_o_t=1473, keep parent uid, negate amount.
  const isLeverageSale = config.moduleId === "leverage" && Boolean(parentId) && !isEdit;
  const isDepositSale = isFixedDepositSale || isCallDepositSale;
  const isBondLikeSale = isBondSale || isBondFundSale;
  const isParentPidSale =
    isBondLikeSale || isCommoditySale || isOtherAssetSale || isCryptoResale || isDepositSale || isLeverageSale;
  const shouldPrefillFromTemp = Boolean(
    !recordId && !seedRow && tempId && transactionModule.fetchCreateContext,
  );
  /** Yii1 update?id=&temp_id=: overlay temp attributes onto the ledger edit form. */
  const shouldOverlayTempOnEdit = Boolean(
    recordId && tempId && transactionModule.fetchCreateContext,
  );

  const [initialValues, setInitialValues] = React.useState<
    | ModuleTransactionFormValues
    | StructureFormValues
    | BondFormValues
    | BondFundsFormValues
    | DepositFormValues
    | CallDepositFormValues
    | FxAccumulatorFormValues
    | SwapsFormValues
    | CurrencyConversionFormValues
    | CashWithdrawalFormValues
    | OtherAssetsFormValues
    | CryptoFormValues
    | undefined
  >(seedRow ? mapListRowToFormValues(seedRow) : undefined);
  const [isLoadingRecord, setIsLoadingRecord] = React.useState(
    Boolean(
      (recordId && transactionModule.fetchById) ||
        isStructureSale ||
        isParentPidSale ||
        shouldPrefillFromTemp ||
        shouldOverlayTempOnEdit,
    ),
  );
  const [loadError, setLoadError] = React.useState<string | null>(null);

  const title = showUpdateChrome
    ? `Edit ${config.singularName}`
    : isCryptoResale
      ? `New ${config.singularName} Resale`
      : isStructureSale || isParentPidSale
        ? `New ${config.singularName} Sale`
        : `New ${config.singularName} transaction`;
  const formKey =
    recordId && tempId
      ? `${recordId}-temp-${tempId}`
      : (recordId ??
        refId ??
        parentId ??
        (tempId ? `temp-${tempId}${isTempQuickUpdate ? "-hide" : ""}` : "new"));
  const icon = React.createElement(getModuleIcon(config.icon), { className: "size-5" });
  const bondLikeSaleRefId = isBondLikeSale
    ? ((initialValues as BondFormValues | BondFundsFormValues | undefined)?.r_no?.trim() ?? "")
    : "";
  const commoditySaleRefId = isCommoditySale
    ? ((initialValues as ModuleTransactionFormValues | undefined)?.r_no?.trim() ?? "")
    : "";
  const otherAssetSaleRefId = isOtherAssetSale
    ? ((initialValues as OtherAssetsFormValues | undefined)?.r_no?.trim() ?? "")
    : "";
  const cryptoResaleRefId = isCryptoResale
    ? ((initialValues as CryptoFormValues | undefined)?.r_no?.trim() ?? "")
    : "";
  const cryptoResaleUid = isCryptoResale
    ? ((initialValues as CryptoFormValues | undefined)?.uid?.trim() ?? "")
    : "";
  const depositSaleUid = isDepositSale
    ? ((initialValues as DepositFormValues | CallDepositFormValues | undefined)?.uid?.trim() ?? "")
    : "";
  const leverageSaleUid = isLeverageSale
    ? ((initialValues as DepositFormValues | undefined)?.uid?.trim() ?? "")
    : "";

  React.useEffect(() => {
    if (
      (config.moduleId === "bond" ||
        config.moduleId === "bond-funds" ||
        config.moduleId === "commodity" ||
        config.moduleId === "other-assets" ||
        config.moduleId === "crypto" ||
        config.moduleId === "leverage" ||
        config.moduleId === "fixed-deposit" ||
        config.moduleId === "call-deposit") &&
      parentId &&
      !recordId &&
      transactionModule.fetchById &&
      // Commodity option/accumulator use dedicated child forms, not the sale prefill path.
      !(config.moduleId === "commodity" && childKind && childKind !== "sale")
    ) {
      let cancelled = false;
      queueMicrotask(() => {
        if (cancelled) return;
        setIsLoadingRecord(true);
        setLoadError(null);
      });

      void transactionModule
        .fetchById(parentId)
        .then((values) => {
          if (cancelled) return;
          if (!values) {
            setLoadError(`${config.singularName} record was not found.`);
            return;
          }
          const saleType =
            config.moduleId === "commodity"
              ? COMMODITY_SALE_TRANSACTION_TYPE
              : config.moduleId === "other-assets"
                ? OTHER_ASSET_SALE_TRANSACTION_TYPE
                : config.moduleId === "crypto"
                  ? CRYPTO_RESALE_TRANSACTION_TYPE
                  : config.moduleId === "fixed-deposit" ||
                      config.moduleId === "call-deposit" ||
                      config.moduleId === "leverage"
                    ? DEPOSIT_SALE_TRANSACTION_TYPE
                    : BOND_SALE_TRANSACTION_TYPE;

          if (config.moduleId === "call-deposit") {
            // Yii1 Call sale clears commission / b_1 / b_2.
            const callValues = values as CallDepositFormValues;
            setInitialValues({
              ...callValues,
              parent_id: parentId,
              uid: callValues.uid,
              transaction: saleType,
              commission: 0,
              b_1: "0",
              b_2: "0",
              amount: -Math.abs(Number(callValues.amount) || Number(callValues.price) || 0),
              price: Math.abs(Number(callValues.price) || Number(callValues.amount) || 0),
            });
            return;
          }

          if (config.moduleId === "fixed-deposit") {
            const depositValues = values as DepositFormValues;
            setInitialValues({
              ...depositValues,
              parent_id: parentId,
              uid: depositValues.uid,
              transaction: saleType,
              amount: -Math.abs(Number(depositValues.amount) || Number(depositValues.price) || 0),
              price: Math.abs(Number(depositValues.price) || Number(depositValues.amount) || 0),
            });
            return;
          }

          if (config.moduleId === "leverage") {
            const leverageValues = values as DepositFormValues;
            setInitialValues({
              ...leverageValues,
              parent_id: parentId,
              uid: leverageValues.uid,
              transaction: saleType,
              amount: -Math.abs(Number(leverageValues.amount) || Number(leverageValues.price) || 0),
              price: Math.abs(Number(leverageValues.price) || Number(leverageValues.amount) || 0),
              m_date: leverageValues.t_date,
            });
            return;
          }

          setInitialValues({
            ...(values as
              | BondFormValues
              | BondFundsFormValues
              | ModuleTransactionFormValues
              | OtherAssetsFormValues
              | CryptoFormValues),
            parent_id: parentId,
            transaction: saleType,
          });
        })
        .catch((error) => {
          if (cancelled) return;
          setLoadError(
            error instanceof Error
              ? error.message
              : `${config.singularName} ${config.moduleId === "crypto" ? "resale" : "sale"} form could not be loaded.`,
          );
        })
        .finally(() => {
          if (!cancelled) setIsLoadingRecord(false);
        });

      return () => {
        cancelled = true;
      };
    }

    if (config.moduleId === "structure" && parentId && !recordId) {
      let cancelled = false;
      queueMicrotask(() => {
        if (cancelled) return;
        setIsLoadingRecord(true);
        setLoadError(null);
      });

      void loadStructureCreateContextClient(parentId)
        .then((values) => {
          if (cancelled) return;
          setInitialValues(values);
        })
        .catch((error) => {
          if (cancelled) return;
          setLoadError(
            error instanceof Error
              ? error.message
              : `${config.singularName} sale form could not be loaded.`,
          );
        })
        .finally(() => {
          if (!cancelled) setIsLoadingRecord(false);
        });

      return () => {
        cancelled = true;
      };
    }

    if (shouldOverlayTempOnEdit && recordId && tempId && transactionModule.fetchCreateContext) {
      let cancelled = false;

      void (async () => {
        try {
          const [ledgerValues, tempResult] = await Promise.all([
            transactionModule.fetchById ? transactionModule.fetchById(recordId) : Promise.resolve(null),
            transactionModule.fetchCreateContext!({
              tempId,
              expiredId,
              pid: parentId,
              hide: hideFromTemp || undefined,
            }),
          ]);

          if (cancelled) return;

          const tempValues = tempResult?.values;
          if (!tempValues && !ledgerValues) {
            setLoadError(`${config.singularName} record was not found.`);
            return;
          }

          if (!tempValues) {
            setInitialValues(ledgerValues ?? undefined);
            return;
          }

          // Yii1 ApiDataInsertion on update: copy temp attrs onto loaded row; keep id/user_id/uid.
          const ledger = (ledgerValues ?? {}) as Record<string, unknown>;
          const merged: Record<string, unknown> = {
            ...ledger,
            ...tempValues,
            temp_id: tempId,
          };
          const ledgerUserId = String(ledger.user_id ?? "").trim();
          const tempUserId = String(merged.user_id ?? "").trim();
          if (!tempUserId && ledgerUserId) {
            merged.user_id = ledgerUserId;
          }
          const ledgerUid = String(ledger.uid ?? "").trim();
          const tempUid = String(merged.uid ?? "").trim();
          if (!tempUid && ledgerUid) {
            merged.uid = ledgerUid;
          }

          setInitialValues(
            merged as
              | ModuleTransactionFormValues
              | StructureFormValues
              | BondFormValues
              | BondFundsFormValues
              | DepositFormValues
              | CallDepositFormValues
              | FxAccumulatorFormValues
              | SwapsFormValues
              | CurrencyConversionFormValues,
          );
        } catch (error) {
          if (cancelled) return;
          setLoadError(
            error instanceof Error
              ? error.message
              : `${config.singularName} could not be loaded from temp.`,
          );
        } finally {
          if (!cancelled) setIsLoadingRecord(false);
        }
      })();

      return () => {
        cancelled = true;
      };
    }

    if (recordId && transactionModule.fetchById) {
      let cancelled = false;

      void transactionModule
        .fetchById(recordId)
        .then((values) => {
          if (cancelled) return;
          if (!values) {
            setLoadError(`${config.singularName} record was not found.`);
            return;
          }
          setInitialValues(values);
        })
        .catch((error) => {
          if (cancelled) return;
          setLoadError(
            error instanceof Error ? error.message : `${config.singularName} could not be loaded.`,
          );
        })
        .finally(() => {
          if (!cancelled) setIsLoadingRecord(false);
        });

      return () => {
        cancelled = true;
      };
    }

    if (shouldPrefillFromTemp && tempId && transactionModule.fetchCreateContext) {
      let cancelled = false;

      void transactionModule
        .fetchCreateContext({
          tempId,
          expiredId,
          pid: parentId,
          hide: isTempQuickUpdate || undefined,
        })
        .then((result) => {
          if (cancelled) return;
          if (!result?.values) {
            setLoadError("Temp transaction data could not be loaded.");
            return;
          }

          const ledgerId = result.transactionId?.trim();
          if (ledgerId) {
            // Already inserted: open as update form (all modules).
            const next = new URLSearchParams();
            next.set("id", ledgerId);
            if (tempId) next.set("temp_id", tempId);
            if (hideFromTemp) next.set("hide", "1");
            if (childKind) next.set("child", childKind);
            if (expiredId) next.set("expired_id", expiredId);
            router.replace(`?${next.toString()}`);
            return;
          }

          setInitialValues(
            result.values as
              | ModuleTransactionFormValues
              | StructureFormValues
              | BondFormValues
              | BondFundsFormValues
              | DepositFormValues
              | CallDepositFormValues
              | FxAccumulatorFormValues
              | SwapsFormValues
              | CurrencyConversionFormValues,
          );
        })
        .catch((error) => {
          if (cancelled) return;

          // Already in ledger: open edit for any temp prefill (all modules).
          if (
            error instanceof CustomerMutationError &&
            error.alreadyInserted &&
            error.transactionId
          ) {
            const next = new URLSearchParams();
            next.set("id", error.transactionId);
            if (childKind) next.set("child", childKind);
            if (tempId) next.set("temp_id", tempId);
            if (hideFromTemp) next.set("hide", "1");
            router.replace(`?${next.toString()}`);
            return;
          }

          const message =
            error instanceof Error ? error.message : "Temp transaction data could not be loaded.";
          setLoadError(message);
        })
        .finally(() => {
          if (!cancelled) setIsLoadingRecord(false);
        });

      return () => {
        cancelled = true;
      };
    }

    setIsLoadingRecord(false);
  }, [
    childKind,
    config.moduleId,
    config.singularName,
    expiredId,
    hideFromTemp,
    isTempQuickUpdate,
    parentId,
    recordId,
    router,
    shouldOverlayTempOnEdit,
    shouldPrefillFromTemp,
    tempId,
    transactionModule,
  ]);

  const handleSubmit = React.useCallback(
    async (
      values:
        | ModuleTransactionFormValues
        | StructureFormValues
        | BondFormValues
        | BondFundsFormValues
        | DepositFormValues
        | CallDepositFormValues
        | FxAccumulatorFormValues
        | SwapsFormValues
        | CurrencyConversionFormValues
        | CashWithdrawalFormValues
        | OtherAssetsFormValues
        | CryptoFormValues,
    ) => {
      try {
        const updateId = recordId || seedRow?.id || seedRow?.refId;
        if ((isEdit || Boolean(recordId)) && updateId) {
          const updatePayload = tempId
            ? ({ ...(values as Record<string, unknown>), temp_id: tempId } as unknown as typeof values)
            : values;
          await transactionModule.update(updateId, updatePayload as never);
          toast.success(`${config.singularName} updated`, {
            description: `The ${config.singularName.toLowerCase()} was saved successfully.`,
          });
        } else {
          const payload =
            isStructureSale && parentId
              ? ({
                  ...(values as StructureFormValues),
                  parent_id: (values as StructureFormValues).parent_id || parentId,
                  t_o_t: SALE_TRANSACTION_TYPE,
                } satisfies StructureFormValues)
              : isBondLikeSale && parentId
                ? ({
                    ...(values as BondFormValues | BondFundsFormValues),
                    parent_id:
                      (values as BondFormValues | BondFundsFormValues).parent_id || parentId,
                    r_no: bondLikeSaleRefId || (values as BondFormValues | BondFundsFormValues).r_no,
                    transaction: BOND_SALE_TRANSACTION_TYPE,
                  } satisfies BondFormValues | BondFundsFormValues)
              : isCommoditySale && parentId
                ? ({
                    ...(values as ModuleTransactionFormValues),
                    parent_id: (values as ModuleTransactionFormValues).parent_id || parentId,
                    r_no: commoditySaleRefId || (values as ModuleTransactionFormValues).r_no,
                    transaction: COMMODITY_SALE_TRANSACTION_TYPE,
                  } satisfies ModuleTransactionFormValues)
                : isOtherAssetSale && parentId
                  ? ({
                      ...(values as OtherAssetsFormValues),
                      parent_id: (values as OtherAssetsFormValues).parent_id || parentId,
                      r_no: otherAssetSaleRefId || (values as OtherAssetsFormValues).r_no,
                      transaction: OTHER_ASSET_SALE_TRANSACTION_TYPE,
                    } satisfies OtherAssetsFormValues)
                  : isCryptoResale && parentId
                    ? ({
                        ...(values as CryptoFormValues),
                        parent_id: (values as CryptoFormValues).parent_id || parentId,
                        r_no: cryptoResaleRefId || (values as CryptoFormValues).r_no,
                        // Yii1 TransferFields copies parent uid — keep it on resale.
                        uid: cryptoResaleUid || (values as CryptoFormValues).uid,
                        transaction: CRYPTO_RESALE_TRANSACTION_TYPE,
                      } satisfies CryptoFormValues)
                    : isLeverageSale && parentId
                      ? ({
                          ...(values as DepositFormValues),
                          parent_id: (values as DepositFormValues).parent_id || parentId,
                          uid: leverageSaleUid || (values as DepositFormValues).uid,
                          transaction: DEPOSIT_SALE_TRANSACTION_TYPE,
                        } satisfies DepositFormValues)
                    : isDepositSale && parentId
                      ? config.moduleId === "call-deposit"
                        ? ({
                            ...(values as CallDepositFormValues),
                            parent_id: (values as CallDepositFormValues).parent_id || parentId,
                            uid: depositSaleUid || (values as CallDepositFormValues).uid,
                            transaction: DEPOSIT_SALE_TRANSACTION_TYPE,
                          } satisfies CallDepositFormValues)
                        : ({
                            ...(values as DepositFormValues),
                            parent_id: (values as DepositFormValues).parent_id || parentId,
                            uid: depositSaleUid || (values as DepositFormValues).uid,
                            transaction: DEPOSIT_SALE_TRANSACTION_TYPE,
                          } satisfies DepositFormValues)
                      : values;
          const createPayload =
            tempId && !isEdit
              ? { ...(payload as Record<string, unknown>), temp_id: tempId }
              : payload;
          await transactionModule.create(createPayload as never);
          toast.success(isTempQuickUpdate ? "Transaction updated" : "Transaction created", {
            description: "The transaction was saved successfully.",
          });
        }

        router.push(listPath);
      } catch (error) {
        toastApiError(error, "Transaction could not be saved.");
        throw error;
      }
    },
    [
      config.singularName,
      bondLikeSaleRefId,
      commoditySaleRefId,
      otherAssetSaleRefId,
      cryptoResaleRefId,
      cryptoResaleUid,
      depositSaleUid,
      leverageSaleUid,
      isBondLikeSale,
      isCommoditySale,
      isOtherAssetSale,
      isCryptoResale,
      isLeverageSale,
      isDepositSale,
      isEdit,
      isTempQuickUpdate,
      isStructureSale,
      listPath,
      parentId,
      recordId,
      router,
      seedRow,
      tempId,
      transactionModule,
    ],
  );

  return (
    <div className="flex min-h-full w-full min-w-0 flex-1 flex-col bg-muted/20">
      <div className="flex w-full min-w-0 flex-1 flex-col gap-6 px-4 pt-6 pb-24 lg:gap-8 lg:px-6 lg:pt-8">
        <header className="flex w-full min-w-0 flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="flex min-w-0 items-start gap-4">
            <div className="flex size-11 shrink-0 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary shadow-xs">
              {icon}
            </div>
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <h1 className="font-semibold text-2xl tracking-tight text-foreground">{title}</h1>
                <Badge variant={showUpdateChrome ? "secondary" : "outline"} className="font-normal">
                  {isTempQuickUpdate ? "Quick update" : isEdit ? "Editing" : "Draft"}
                </Badge>
              </div>
              <p className="mt-1.5 text-muted-foreground text-sm leading-relaxed">
                {isTempQuickUpdate
                  ? `Update prefilled ${config.singularName.toLowerCase()} details from temp #${tempId}.`
                  : isEdit
                    ? `${seedRow?.name ?? config.singularName} · ${recordId ?? refId ?? ""}`
                    : `Capture trade, asset, pricing, and bank details for this ${config.singularName.toLowerCase()}.`}
              </p>
            </div>
          </div>
          <Button variant="outline" size="sm" className="shrink-0 gap-1.5" asChild>
            <Link href={listPath}>
              <ArrowLeft className="size-3.5" />
              Back to list
            </Link>
          </Button>
        </header>

        {isLoadingRecord ? (
          <p className="text-muted-foreground text-sm">
            {shouldPrefillFromTemp ? "Loading temp data…" : "Loading record…"}
          </p>
        ) : loadError ? (
          <p className="text-destructive text-sm">{loadError}</p>
        ) : config.moduleId === "stock" || config.moduleId === "stock-funds" ? (
          <StockTransactionForm
            key={formKey}
            formId={config.formId}
            variant={config.moduleId === "stock-funds" ? "stock-funds" : "stock"}
            initialValues={initialValues as ModuleTransactionFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={
              config.moduleId === "stock-funds" ? loadStockFundFormOptionsClient : undefined
            }
          />
        ) : config.moduleId === "commodity" ? (
          <StockTransactionForm
            key={recordId ?? parentId ?? refId ?? "new"}
            formId={config.formId}
            variant="commodity"
            initialValues={initialValues as ModuleTransactionFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadCommodityFormOptionsClient}
          />
        ) : config.moduleId === "mixed-funds" ? (
          <StockTransactionForm
            key={formKey}
            formId={config.formId}
            variant="mixed-funds"
            initialValues={initialValues as ModuleTransactionFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadMixedFundFormOptionsClient}
          />
        ) : config.moduleId === "crypto" ? (
          <StockTransactionForm
            key={formKey}
            formId={config.formId}
            variant="crypto"
            initialValues={initialValues as CryptoFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadCryptoFormOptionsClient}
          />
        ) : config.moduleId === "other-assets" ? (
          <StockTransactionForm
            key={formKey}
            formId={config.formId}
            variant="other-assets"
            initialValues={initialValues as OtherAssetsFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadOtherAssetFormOptionsClient}
          />
        ) : config.moduleId === "structure" ? (
          <StructureTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as StructureFormValues | undefined}
            isSale={isStructureSale}
            onSubmit={handleSubmit}
          />
        ) : config.moduleId === "bond" ? (
          <BondTransactionForm
            key={formKey}
            formId={config.formId}
            variant="bond"
            initialValues={initialValues as BondFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadBondFormOptionsClient}
          />
        ) : config.moduleId === "bond-funds" ? (
          <BondTransactionForm
            key={formKey}
            formId={config.formId}
            variant="bond-funds"
            initialValues={initialValues as BondFundsFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadBondFundFormOptionsClient}
          />
        ) : config.moduleId === "fixed-deposit" ? (
          <DepositTransactionForm
            key={formKey}
            formId={config.formId}
            variant="fixed-deposit"
            initialValues={initialValues as DepositFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadFixedDepositFormOptionsClient}
          />
        ) : config.moduleId === "leverage" ? (
          <DepositTransactionForm
            key={formKey}
            formId={config.formId}
            variant="leverage"
            initialValues={initialValues as DepositFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadLeverageFormOptionsClient}
          />
        ) : config.moduleId === "call-deposit" ? (
          <CallDepositTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as CallDepositFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadCallDepositFormOptionsClient}
          />
        ) : config.moduleId === "fx-accumulator" ? (
          <FxAccumulatorTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as FxAccumulatorFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadFxAccumulatorFormOptionsClient}
          />
        ) : config.moduleId === "swaps" ? (
          <SwapsTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as SwapsFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadSwapsFormOptionsClient}
          />
        ) : config.moduleId === "currency-conversion" ? (
          <CurrencyConversionTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as CurrencyConversionFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadCurrencyConversionFormOptionsClient}
          />
        ) : config.moduleId === "cash-withdrawal" ? (
          <CashWithdrawalTransactionForm
            key={formKey}
            formId={config.formId}
            initialValues={initialValues as CashWithdrawalFormValues | undefined}
            onSubmit={handleSubmit}
            loadFormOptions={loadCashWithdrawalFormOptionsClient}
          />
        ) : (
          <ModuleTransactionForm
            key={formKey}
            config={config}
            initialValues={initialValues as ModuleTransactionFormValues | undefined}
            onSubmit={handleSubmit}
          />
        )}
      </div>

      <div className="sticky bottom-0 z-20 border-t border-border/60 bg-background/90 shadow-[0_-4px_24px_-8px_rgba(0,0,0,0.08)] backdrop-blur-md dark:shadow-[0_-4px_24px_-8px_rgba(0,0,0,0.35)]">
        <div className="flex w-full flex-wrap items-center justify-between gap-3 px-4 py-3.5 lg:px-6">
          <p className="text-muted-foreground text-xs sm:text-sm">
            {showUpdateChrome
              ? "Changes apply on save"
              : "All required fields must be valid before saving"}
          </p>
          <div className="flex flex-wrap items-center gap-2">
            <Button variant="ghost" size="sm" className="text-muted-foreground" asChild>
              <Link href={listPath}>Cancel</Link>
            </Button>
            <Button
              type="submit"
              form={config.formId}
              size="sm"
              className="min-w-[7.5rem] px-6 shadow-sm"
              disabled={isLoadingRecord || Boolean(loadError)}
            >
              {showUpdateChrome ? "Save changes" : "Create transaction"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
