"use client";

import { useSearchParams } from "next/navigation";

import { mapStockChildModelToFormValues } from "@/app/customer/[tenant]/stock/_lib/map-stock-child-model";
import {
  createMixedFundsChildClient,
  loadMixedFundsChildFormContextClient,
  loadMixedFundsChildUpdateFormContextClient,
  updateMixedFundsChildClient,
} from "@/app/customer/[tenant]/mixed-funds/_lib/mixed-funds-child-api";
import {
  MIXED_FUNDS_CHILD_LABELS,
  supportsStandaloneMixedFundsChildCreate,
  type MixedFundsChildFormContext,
  type MixedFundsChildKind,
} from "@/app/customer/[tenant]/mixed-funds/_lib/mixed-funds-child-types";

import { createChildFormRoutePage, childFormComponent } from "./create-child-form-route-page";
import { useCustomerModuleListPath } from "./list-table-form-actions";
import { mixedFundsFormConfig } 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 MIXED_FUNDS_CHILD_FORM_ID = "mixed-funds-child-form";

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

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

function shouldUseMixedFundsChildFormPage(
  child: string | null | undefined,
  pid: string | null | undefined,
  id: string | null | undefined,
): boolean {
  if (!child || !isMixedFundsChildKind(child)) {
    return false;
  }

  const trimmedPid = pid?.trim() ?? "";
  const trimmedId = id?.trim() ?? "";
  if (trimmedPid || trimmedId) {
    return true;
  }

  return supportsStandaloneMixedFundsChildCreate(child);
}

const { ChildFormPage: MixedFundsChildFormPage } = createChildFormRoutePage<
  MixedFundsChildKind,
  MixedFundsChildKind,
  MixedFundsChildFormContext
>({
  formId: MIXED_FUNDS_CHILD_FORM_ID,
  childLabels: MIXED_FUNDS_CHILD_LABELS,
  defaultTitle: "Mixed fund action",
  parentEntityLabel: "mixed fund",
  isChildKind: isMixedFundsChildKind,
  isEditableChildKind: isEditableMixedFundsChildKind,
  supportsStandaloneCreate: supportsStandaloneMixedFundsChildCreate,
  childFormIsReady: (child, { pid, id }) => {
    if (!child) {
      return false;
    }
    if (id) {
      return true;
    }
    if (pid) {
      return true;
    }
    return supportsStandaloneMixedFundsChildCreate(child);
  },
  useExplicitLoadingState: true,
  rethrowSubmitError: true,
  isUpdateMode: ({ child, id }) => Boolean(child && id),
  loadCreate: loadMixedFundsChildFormContextClient,
  loadUpdate: loadMixedFundsChildUpdateFormContextClient,
  create: createMixedFundsChildClient,
  update: (child, id, pid, values, formName, context) =>
    updateMixedFundsChildClient(child, id, pid || context.pid, values, formName),
  mapModel: (child, context, pid) =>
    mapStockChildModelToFormValues(child, context.model, context.fieldMeta, context.pid || pid),
  getBadgeLabel: (isUpdateMode) => (isUpdateMode ? "Edit" : "Draft"),
  getParentPid: ({ pid, context }) => pid || context?.pid || null,
  getMissingChildMessage: ({ child, loadError }) =>
    loadError ??
    (child === "sale"
      ? "Sale requires a parent mixed fund id."
      : "Missing child action or parent mixed fund id."),
  formComponents: {
    sale: childFormComponent(StockSaleChildForm),
    option: childFormComponent(StockOptionTransactionForm),
    accumulator: childFormComponent(StockAccumulatorTransactionForm),
  },
});

export { MixedFundsChildFormPage };

export function MixedFundsFormRoutePage() {
  const searchParams = useSearchParams();
  const childParam = searchParams.get("child")?.trim() ?? "";
  const pid = searchParams.get("pid")?.trim() ?? "";
  const id = searchParams.get("id")?.trim() ?? "";
  const listPath = useCustomerModuleListPath(mixedFundsFormConfig.listPath);

  if (shouldUseMixedFundsChildFormPage(childParam, pid, id)) {
    return <MixedFundsChildFormPage listPath={listPath} />;
  }

  return <TransactionModuleFormPage config={mixedFundsFormConfig} />;
}
