"use client";

import * as React from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { Building2, CircleDollarSign, ClipboardList, Layers3, StickyNote } from "lucide-react";
import { FormProvider, useForm, useWatch } from "react-hook-form";

import type { FilterOption } from "@/app/customer/_lib/customer-asset-filter-options";
import { withServerValidationErrors } from "@/app/customer/_lib/apply-yii-validation-errors";
import type { StockChildFieldMeta } from "@/app/customer/[tenant]/stock/_lib/stock-child-types";
import {
  EMPTY_STOCK_FORM_OPTIONS,
  mapStockFormOptions,
  type StockFormOptions,
} from "@/app/customer/[tenant]/stock/_lib/stock-form-options";
import { stockFieldLabels, transactionFieldLabels } from "@/components/form/common/field-labels";
import { formGridClass, formSpanFull } from "@/components/form/common/form-layout";
import { DateField } from "@/components/form/fields/date-field";
import { NumberField } from "@/components/form/fields/number-field";
import { SelectField } from "@/components/form/fields/select-field";
import { TextAreaField } from "@/components/form/fields/text-area-field";
import { TextField } from "@/components/form/fields/text-field";
import {
  defaultStockSaleChildFormValues,
  stockSaleChildFormSchema,
  type StockSaleChildFormValues,
} from "@/components/form/schemas/stock-sale-schema";
import { YII_TRANSACTION } from "@/config/yii-transaction";
import { formatQuantityFixed } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

import { TransactionFormSection } from "./form-section";

const MATURITY_EXECUTION_TYPE = "1477";

type StockSaleChildFormProps = {
  formId: string;
  initialValues?: StockSaleChildFormValues;
  formOptionsRaw?: Record<string, Record<string, string>>;
  fieldMeta?: StockChildFieldMeta;
  onSubmit?: (values: StockSaleChildFormValues) => void | Promise<void>;
};

function toSelectOptions(options: FilterOption[]) {
  return options.map((option) => ({ value: option.value, label: option.label }));
}

function LockedSection({ locked, children }: { locked: boolean; children: React.ReactNode }) {
  return (
    <div className={cn("relative w-full min-w-0")}>
      {locked ? (
        <div className="pointer-events-none absolute inset-0 z-10 rounded-lg bg-background/40" aria-hidden />
      ) : null}
      {children}
    </div>
  );
}

export function StockSaleChildForm({
  formId,
  initialValues,
  formOptionsRaw,
  fieldMeta,
  onSubmit,
}: StockSaleChildFormProps) {
  const [formOptions, setFormOptions] = React.useState<StockFormOptions>(EMPTY_STOCK_FORM_OPTIONS);

  const form = useForm<StockSaleChildFormValues>({
    resolver: zodResolver(stockSaleChildFormSchema),
    defaultValues: { ...defaultStockSaleChildFormValues, ...initialValues },
    mode: "onBlur",
  });

  React.useEffect(() => {
    form.reset({ ...defaultStockSaleChildFormValues, ...initialValues });
  }, [form, initialValues]);

  React.useEffect(() => {
    if (formOptionsRaw) {
      setFormOptions(mapStockFormOptions(formOptionsRaw));
    }
  }, [formOptionsRaw]);

  const quantity = useWatch({ control: form.control, name: "quantity" });
  const price = useWatch({ control: form.control, name: "price" });
  const commission = useWatch({ control: form.control, name: "commission" });
  const b1 = useWatch({ control: form.control, name: "b_1" });
  const b2 = useWatch({ control: form.control, name: "b_2" });
  const executionType = useWatch({ control: form.control, name: "execution_type" });

  React.useEffect(() => {
    const amount = Number(quantity || 0) * Number(price || 0);
    form.setValue("amount", Number.isFinite(amount) ? Number(amount.toFixed(8)) : 0, { shouldDirty: true });
    form.setValue("transaction", YII_TRANSACTION.sale, { shouldDirty: false });
  }, [form, quantity, price]);

  const gross = useWatch({ control: form.control, name: "amount" });
  const net =
    Number(gross || 0) -
    (Number(commission || 0) + Number(b1 || 0) + Number(b2 || 0));

  const lockParent = fieldMeta?.lockParentSection ?? false;
  const showMaturityDate = executionType === MATURITY_EXECUTION_TYPE;
  const amountLabel =
    executionType === MATURITY_EXECUTION_TYPE ? "Max Exposure" : transactionFieldLabels.amount;

  return (
    <FormProvider {...form}>
      <form id={formId} noValidate onSubmit={form.handleSubmit(withServerValidationErrors(form.setError, onSubmit))}>
        <div className="flex flex-col gap-5">
          <LockedSection locked={lockParent}>
            <TransactionFormSection title="Parent stock" icon={<Layers3 className="size-4" />} contentClassName={formGridClass}>
              <TextField control={form.control} name="uid" label="Ref. ID" />
            </TransactionFormSection>
          </LockedSection>

          <TransactionFormSection
            title="Transaction"
            icon={<ClipboardList className="size-4" />}
            contentClassName={formGridClass}
          >
            <DateField control={form.control} name="t_date" label={transactionFieldLabels.t_date} />
            <SelectField
              control={form.control}
              name="execution_type"
              label={stockFieldLabels.execution_type}
              options={toSelectOptions(formOptions.executionTypes)}
              searchable
            />
            <TextField control={form.control} name="r_no" label={transactionFieldLabels.r_no} />
            <NumberField control={form.control} name="quantity" label={transactionFieldLabels.quantity} step="0.0001" />
          </TransactionFormSection>

          <TransactionFormSection title="Security & pricing" icon={<Layers3 className="size-4" />} contentClassName={formGridClass}>
            <TextField control={form.control} name="ticker" label={transactionFieldLabels.ticker} />
            <TextField control={form.control} name="isin" label={transactionFieldLabels.isin} />
            <TextAreaField control={form.control} name="b_notes" label={transactionFieldLabels.b_notes} className={formSpanFull} />
            <NumberField control={form.control} name="price" label={transactionFieldLabels.price} step="0.0001" />
            <DateField control={form.control} name="p_date" label={transactionFieldLabels.p_date} />
            {showMaturityDate ? (
              <DateField control={form.control} name="m_date" label={transactionFieldLabels.m_date} />
            ) : null}
            <NumberField control={form.control} name="amount" label={amountLabel} />
            <NumberField control={form.control} name="t_price" label={transactionFieldLabels.t_price} step="0.0001" />
          </TransactionFormSection>

          <TransactionFormSection title="Fees & currency" icon={<CircleDollarSign className="size-4" />} contentClassName={formGridClass}>
            <NumberField control={form.control} name="commission" label={transactionFieldLabels.commission} />
            <TextField control={form.control} name="b_1" label={transactionFieldLabels.b_1} />
            <TextField control={form.control} name="b_2" label={transactionFieldLabels.b_2} />
            <SelectField
              control={form.control}
              name="p_currency"
              label={transactionFieldLabels.p_currency}
              options={toSelectOptions(formOptions.currencies)}
              searchable
            />
          </TransactionFormSection>

          <TransactionFormSection title="Classification & bank" icon={<Building2 className="size-4" />} contentClassName={formGridClass}>
            <div className="hidden">
              <TextField control={form.control} name="a_class" label={transactionFieldLabels.a_class} />
            </div>
            <SelectField
              control={form.control}
              name="a_type"
              label={transactionFieldLabels.a_type}
              options={toSelectOptions(formOptions.assetTypes)}
              searchable
            />
            <SelectField
              control={form.control}
              name="bank"
              label={transactionFieldLabels.bank}
              options={toSelectOptions(formOptions.banks)}
              searchable
            />
          </TransactionFormSection>

          <TransactionFormSection title="Notes" icon={<StickyNote className="size-4" />} contentClassName={formGridClass}>
            <TextAreaField control={form.control} name="remarks" label={transactionFieldLabels.remarks} className={formSpanFull} />
            <TextAreaField control={form.control} name="purpose" label={transactionFieldLabels.purpose} className={formSpanFull} />
            <TextField control={form.control} name="r_m" label={transactionFieldLabels.r_m} />
            <TextField control={form.control} name="r_link" label={transactionFieldLabels.r_link} />
          </TransactionFormSection>

          <div className="rounded-lg border bg-muted/20 px-4 py-3 text-sm">
            <div className="flex justify-between">
              <span>Net amount</span>
              <span className="font-medium tabular-nums">
                {formatQuantityFixed(net, 2)}
              </span>
            </div>
          </div>
        </div>
      </form>
    </FormProvider>
  );
}
