"use client";

import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";

import { mapStockChildModelToFormValues } from "@/app/customer/[tenant]/stock/_lib/map-stock-child-model";
import {
  createStockFundsChildClient,
  loadStockFundsChildFormContextClient,
} from "@/app/customer/[tenant]/stock-funds/_lib/stock-funds-child-api";
import {
  STOCK_FUNDS_CHILD_LABELS,
  supportsStandaloneStockFundsChildCreate,
  type StockFundsChildFormContext,
  type StockFundsChildKind,
} from "@/app/customer/[tenant]/stock-funds/_lib/stock-funds-child-types";

import { createChildFormRoutePage, childFormComponent } from "./create-child-form-route-page";
import { useCustomerModuleListPath } from "./list-table-form-actions";
import { stockFundsFormConfig } from "./module-configs";
import { StockAccumulatorTransactionForm } from "./stock-accumulator-transaction-form";
import { StockOptionTransactionForm } from "./stock-option-transaction-form";
import { StockSaleChildForm } from "./stock-sale-child-form";
import { TransactionModuleFormPage } from "./transaction-module-form-page";

const STOCK_FUNDS_CHILD_FORM_ID = "stock-funds-child-form";

function isStockFundsChildKind(value: string | null): value is StockFundsChildKind {
  return value === "sale" || value === "option" || value === "accumulator";
}

function isEditableStockFundsChildKind(value: StockFundsChildKind | null): value is StockFundsChildKind {
  return value === "sale" || value === "option" || value === "accumulator";
}

const { ChildFormPage: StockFundsChildFormPage } = createChildFormRoutePage<
  StockFundsChildKind,
  StockFundsChildKind,
  StockFundsChildFormContext
>({
  formId: STOCK_FUNDS_CHILD_FORM_ID,
  childLabels: STOCK_FUNDS_CHILD_LABELS,
  defaultTitle: "Stock fund action",
  parentEntityLabel: "stock fund",
  isChildKind: isStockFundsChildKind,
  isEditableChildKind: isEditableStockFundsChildKind,
  supportsStandaloneCreate: supportsStandaloneStockFundsChildCreate,
  useExplicitLoadingState: true,
  rethrowSubmitError: true,
  loadCreate: loadStockFundsChildFormContextClient,
  create: createStockFundsChildClient,
  mapModel: (child, context, pid) =>
    mapStockChildModelToFormValues(child, context.model, context.fieldMeta, pid),
  getFormKeySuffix: ({ pid }) => pid || "standalone",
  getMissingChildMessage: ({ child, loadError }) =>
    loadError ??
    (child === "sale"
      ? "Sale requires a parent stock fund id."
      : "Missing child action or parent stock fund id."),
  formComponents: {
    sale: childFormComponent(StockSaleChildForm),
    option: childFormComponent(StockOptionTransactionForm),
    accumulator: childFormComponent(StockAccumulatorTransactionForm),
  },
});

export { StockFundsChildFormPage };

export function StockFundsFormRoutePage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const childParam = searchParams.get("child")?.trim() ?? "";
  const id = searchParams.get("id")?.trim();
  const refId = searchParams.get("refId")?.trim();
  const tempId = searchParams.get("temp_id")?.trim();
  const listPath = useCustomerModuleListPath(stockFundsFormConfig.listPath);

  const child = isStockFundsChildKind(childParam) ? childParam : null;
  const showParentForm = Boolean(id || refId || tempId);

  React.useEffect(() => {
    if (!child && !showParentForm) {
      router.replace(listPath);
    }
  }, [child, listPath, router, showParentForm]);

  if (child) {
    return <StockFundsChildFormPage listPath={listPath} />;
  }

  if (showParentForm) {
    return <TransactionModuleFormPage config={stockFundsFormConfig} />;
  }

  return null;
}
