"use client";

import * as React from "react";

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

import type { FilterOption } from "@/app/customer/_lib/customer-asset-filter-options";
import {
  EMPTY_STOCK_FORM_OPTIONS,
  type StockFormOptions,
} from "@/app/customer/[tenant]/stock/_lib/stock-form-options";
import { 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 { ReferenceLinkField } from "@/components/form/fields/reference-link-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 {
  CASH_WITHDRAWAL_D_TYPES,
  defaultCashWithdrawalFormValues,
  cashWithdrawalTransactionFormSchema,
  type CashWithdrawalFormValues,
} from "@/components/form/schemas/cash-withdrawal-transaction-schema";
import {
  formatMoney,
  parseAmount,
} from "@/components/form/transaction-workspace/transaction-form-summary";

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

export type LoadCashWithdrawalFormOptionsClient = (aClass?: string) => Promise<{
  formOptions: StockFormOptions;
  defaults: Record<string, unknown> | null;
}>;

type CashWithdrawalTransactionFormProps = {
  formId: string;
  initialValues?: CashWithdrawalFormValues;
  onSubmit?: (values: CashWithdrawalFormValues) => void;
  loadFormOptions: LoadCashWithdrawalFormOptionsClient;
};

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

function CashWithdrawalSummarySidebar() {
  const dType = useWatch<CashWithdrawalFormValues, "d_type">({ name: "d_type" });
  const price = useWatch<CashWithdrawalFormValues, "price">({ name: "price" });
  const commission = useWatch<CashWithdrawalFormValues, "commission">({ name: "commission" });
  const b1 = useWatch<CashWithdrawalFormValues, "b_1">({ name: "b_1" });
  const b2 = useWatch<CashWithdrawalFormValues, "b_2">({ name: "b_2" });

  const fees = parseAmount(commission) + parseAmount(b1) + parseAmount(b2);
  const gross = parseAmount(price);
  // Yii1 calculateNetAmount: Deposit = price−fees; Withdrawal = price+fees
  const net = dType === "2" ? gross + fees : gross - fees;

  return (
    <aside className="flex h-fit flex-col gap-4 rounded-xl border border-border/60 bg-muted/20 p-4 lg:sticky lg:top-4">
      <p className="font-medium text-sm">Live summary</p>
      <div className="space-y-2 text-sm">
        <div className="flex justify-between gap-3">
          <span className="text-muted-foreground">Amount</span>
          <span className="font-mono">{formatMoney(gross)}</span>
        </div>
        <div className="flex justify-between gap-3">
          <span className="text-muted-foreground">Commission</span>
          <span className="font-mono">{formatMoney(parseAmount(commission))}</span>
        </div>
        <div className="flex justify-between gap-3">
          <span className="text-muted-foreground">Charges</span>
          <span className="font-mono">{formatMoney(parseAmount(b1))}</span>
        </div>
        <div className="flex justify-between gap-3">
          <span className="text-muted-foreground">Tax</span>
          <span className="font-mono">{formatMoney(parseAmount(b2))}</span>
        </div>
        <div className="flex justify-between gap-3 border-t border-border/50 pt-2 font-medium">
          <span>Net Amount</span>
          <span className="font-mono">{formatMoney(net)}</span>
        </div>
      </div>
    </aside>
  );
}

export function CashWithdrawalTransactionForm({
  formId,
  initialValues,
  onSubmit,
  loadFormOptions,
}: CashWithdrawalTransactionFormProps) {
  const [formOptions, setFormOptions] = React.useState<StockFormOptions>(EMPTY_STOCK_FORM_OPTIONS);
  const [optionsError, setOptionsError] = React.useState<string | null>(null);
  const [loadingOptions, setLoadingOptions] = React.useState(true);

  const form = useForm<CashWithdrawalFormValues>({
    resolver: zodResolver(cashWithdrawalTransactionFormSchema),
    defaultValues: { ...defaultCashWithdrawalFormValues, ...initialValues },
    mode: "onBlur",
  });

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

  React.useEffect(() => {
    let cancelled = false;
    setLoadingOptions(true);
    void loadFormOptions()
      .then(({ formOptions: options, defaults }) => {
        if (cancelled) return;
        setFormOptions(options);
        if (!initialValues) {
          const patch: Partial<CashWithdrawalFormValues> = {};
          if (defaults?.commission != null) patch.commission = Number(defaults.commission) || 0;
          if (defaults?.b_1 != null) patch.b_1 = String(defaults.b_1);
          if (defaults?.b_2 != null) patch.b_2 = String(defaults.b_2);
          if (Object.keys(patch).length > 0) {
            form.reset({ ...defaultCashWithdrawalFormValues, ...form.getValues(), ...patch });
          }
        }
      })
      .catch((error) => {
        if (!cancelled) {
          setOptionsError(error instanceof Error ? error.message : "Could not load form options.");
        }
      })
      .finally(() => {
        if (!cancelled) setLoadingOptions(false);
      });
    return () => {
      cancelled = true;
    };
  }, [form, initialValues, loadFormOptions]);

  const price = useWatch({ control: form.control, name: "price" });
  React.useEffect(() => {
    form.setValue("amount", Number.isFinite(Number(price)) ? Number(price) : 0, { shouldDirty: true });
  }, [form, price]);

  return (
    <FormProvider {...form}>
      <form
        id={formId}
        noValidate
        onSubmit={form.handleSubmit((values) => onSubmit?.(values))}
        className="w-full min-w-0"
      >
        {loadingOptions ? (
          <p className="mb-4 text-muted-foreground text-sm">Loading dropdown options…</p>
        ) : null}
        {optionsError ? <p className="mb-4 text-destructive text-sm">{optionsError}</p> : null}

        <div className="grid w-full min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(0,1fr)_18rem] xl:gap-8">
          <div className="flex min-w-0 flex-col gap-5 lg:gap-6">
            <TransactionFormSection
              title="Cash details"
              description="Placement date, currency, amount, and deposit/withdrawal type."
              icon={<ClipboardList className="size-4" />}
              contentClassName={formGridClass}
            >
              <DateField control={form.control} name="t_date" label="Placement Date" />
              <SelectField
                control={form.control}
                name="p_currency"
                label="Currency"
                options={toSelectOptions(formOptions.currencies)}
                searchable
                searchPlaceholder="Search currency…"
              />
              <NumberField control={form.control} name="price" label="Amount" step="0.0001" />
              <SelectField
                control={form.control}
                name="d_type"
                label="Type"
                options={[...CASH_WITHDRAWAL_D_TYPES]}
              />
              <SelectField
                control={form.control}
                name="bank"
                label="Bank"
                options={toSelectOptions(formOptions.banks)}
                searchable
                searchPlaceholder="Search bank…"
              />
              <TextField control={form.control} name="r_no" label={transactionFieldLabels.r_no} />
            </TransactionFormSection>

            <TransactionFormSection
              title="Fees"
              description="Commission, charges abroad, and federal turnover tax."
              icon={<CircleDollarSign className="size-4" />}
              contentClassName={formGridClass}
            >
              <NumberField control={form.control} name="commission" label="Commission" step="0.0001" />
              <TextField control={form.control} name="b_1" label="Charges and fees abroad" />
              <TextField control={form.control} name="b_2" label="Federal turnover tax" />
            </TransactionFormSection>

            <TransactionFormSection
              title="Bank & notes"
              description="Remarks, purpose, and PDF reference."
              icon={<Building2 className="size-4" />}
              contentClassName={formGridClass}
            >
              <div className={formSpanFull}>
                <TextAreaField control={form.control} name="remarks" label="Remarks" rows={5} />
              </div>
              <div className={formSpanFull}>
                <TextAreaField control={form.control} name="purpose" label="Purpose" rows={5} />
              </div>
              <div className={formSpanFull}>
                <ReferenceLinkField control={form.control} name="r_link" label="Reference PDF" />
              </div>
            </TransactionFormSection>

            <div className="flex items-start gap-2 text-muted-foreground text-xs">
              <StickyNote className="mt-0.5 size-3.5 shrink-0" />
              <p>
                Deposit net = amount − fees; Withdrawal net = amount + fees (Yii1 parity). Stored amount
                remains the entered amount.
              </p>
            </div>
          </div>

          <CashWithdrawalSummarySidebar />
        </div>
      </form>
    </FormProvider>
  );
}
