"use client";

import * as React from "react";
import { Plus, Trash2 } from "lucide-react";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ClipboardList,
  Layers3,
  StickyNote,
} from "lucide-react";
import { FormProvider, useFieldArray, useForm, useFormContext, useWatch } from "react-hook-form";

import { withServerValidationErrors } from "@/app/customer/_lib/apply-yii-validation-errors";
import type { FilterOption } from "@/app/customer/_lib/customer-asset-filter-options";
import { loadStructureFormOptionsClient } from "@/app/customer/[tenant]/structure/_lib/structure-api";
import {
  EMPTY_STRUCTURE_FORM_OPTIONS,
  type StructureFormOptions,
} from "@/app/customer/[tenant]/structure/_lib/structure-form-options";
import { structureFieldLabels, 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 { 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 {
  defaultStructureFormValues,
  defaultStructureUnderlyingRow,
  PURCHASE_TRANSACTION_TYPE,
  structureTransactionFormSchema,
  type StructureFormValues,
} from "@/components/form/schemas/structure-transaction-schema";
import { Button } from "@/components/ui/button";

import { TransactionFormSection } from "./form-section";
import {
  formatMoney,
  labelForOption,
  parseAmount,
  SummaryRow,
} from "./transaction-form-summary";

const MAX_UNDERLYINGS = 4;
const DURATION_UNIT_OPTIONS = [{ value: "30", label: "Months" }];

type StructureTransactionFormProps = {
  formId: string;
  initialValues?: StructureFormValues;
  isSale?: boolean;
  onSubmit?: (values: StructureFormValues) => void;
};

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

function StructureFormSummarySidebar({ formOptions }: { formOptions: StructureFormOptions }) {
  const { control, setValue } = useFormContext<StructureFormValues>();
  const watched = useWatch({ control });

  const price = parseAmount(watched.price);
  const negative = watched.t_o_t === PURCHASE_TRANSACTION_TYPE ? -1 : 1;
  const gross = price * negative;
  const commissionNum = parseAmount(watched.commission);
  const chargesNum = parseAmount(watched.b_1);
  const taxNum = parseAmount(watched.b_2);
  const net = gross - (commissionNum + chargesNum + taxNum);

  React.useEffect(() => {
    setValue("amount", String(gross), { shouldValidate: false, shouldDirty: false });
  }, [gross, setValue]);

  const structureName = watched.structure_name?.trim();
  const isin = watched.s_isin?.trim();
  const bankLabel =
    labelForOption(formOptions.banks, watched.bank_id) || watched.bank_id?.trim();
  const currencyLabel =
    labelForOption(formOptions.currencies, watched.p_currency) || watched.p_currency?.trim() || "—";
  const underlyingCount = watched.underlyings?.filter((row) => row.ticker?.trim()).length ?? 0;

  return (
    <aside className="xl:sticky xl:top-6 xl:self-start">
      <div className="overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm">
        <div className="border-b border-border/50 bg-muted/25 px-5 py-4">
          <div className="flex items-center justify-between gap-2">
            <p className="font-medium text-muted-foreground text-[11px] uppercase tracking-wider">
              Live preview
            </p>
            <span className="relative flex size-2">
              <span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-400 opacity-60" />
              <span className="relative inline-flex size-2 rounded-full bg-emerald-500" />
            </span>
          </div>
          <p className="mt-3 font-mono font-semibold text-2xl tracking-tight">
            {structureName || isin || "—"}
          </p>
          <p className="mt-1.5 text-muted-foreground text-sm leading-snug">
            {isin && structureName ? isin : "Structure details pending"}
          </p>
        </div>

        <div className="px-5 py-4">
          <SummaryRow label="Bank" value={bankLabel || "—"} />
          <SummaryRow label={structureFieldLabels.t_date} value={watched.t_date || "—"} mono />
          <SummaryRow label={structureFieldLabels.p_date} value={watched.p_date || "—"} mono />
          <SummaryRow label={structureFieldLabels.r_no} value={watched.r_no || "—"} mono />
        </div>

        <div className="border-t border-border/50 px-5 py-4">
          <SummaryRow label={structureFieldLabels.amount} value={formatMoney(gross)} mono />
          <SummaryRow label={transactionFieldLabels.commission} value={formatMoney(commissionNum)} mono />
          <SummaryRow label={transactionFieldLabels.b_1} value={formatMoney(chargesNum)} mono />
          <SummaryRow label={transactionFieldLabels.b_2} value={formatMoney(taxNum)} mono />
        </div>

        <div className="border-t border-border/50 bg-gradient-to-br from-primary/5 via-transparent to-transparent px-5 py-5">
          <p className="text-muted-foreground text-xs uppercase tracking-wider">Net Amount</p>
          <p className="mt-2 font-mono font-semibold text-3xl tracking-tight tabular-nums">
            {formatMoney(net)}
          </p>
          <p className="mt-0.5 font-medium text-muted-foreground text-sm">{currencyLabel}</p>
          <div className="mt-5 grid grid-cols-2 gap-3">
            <div className="rounded-lg border border-border/50 bg-muted/20 px-3 py-2.5">
              <p className="text-muted-foreground text-[11px] uppercase tracking-wide">
                {structureFieldLabels.s_percentage}
              </p>
              <p className="mt-1 font-mono font-medium text-sm tabular-nums">
                {watched.s_percentage?.trim() || "—"}
              </p>
            </div>
            <div className="rounded-lg border border-border/50 bg-muted/20 px-3 py-2.5">
              <p className="text-muted-foreground text-[11px] uppercase tracking-wide">Underlyings</p>
              <p className="mt-1 font-mono font-medium text-sm tabular-nums">{underlyingCount}</p>
            </div>
          </div>
        </div>
      </div>
    </aside>
  );
}

export function StructureTransactionForm({
  formId,
  initialValues,
  isSale = false,
  onSubmit,
}: StructureTransactionFormProps) {
  const [formOptions, setFormOptions] = React.useState<StructureFormOptions>(EMPTY_STRUCTURE_FORM_OPTIONS);
  const [optionsError, setOptionsError] = React.useState<string | null>(null);
  const [loadingOptions, setLoadingOptions] = React.useState(true);

  const form = useForm<StructureFormValues>({
    resolver: zodResolver(structureTransactionFormSchema),
    defaultValues: initialValues ?? defaultStructureFormValues,
    mode: "onBlur",
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "underlyings",
  });

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

  React.useEffect(() => {
    let cancelled = false;
    setLoadingOptions(true);
    setOptionsError(null);

    void loadStructureFormOptionsClient()
      .then(({ formOptions: options, defaults }) => {
        if (cancelled) return;
        setFormOptions(options);
        if (!initialValues && defaults) {
          form.reset({
            ...defaultStructureFormValues,
            ...form.getValues(),
            a_class: defaults.a_class != null ? String(defaults.a_class) : form.getValues("a_class"),
            a_type: defaults.a_type != null ? String(defaults.a_type) : form.getValues("a_type"),
            s_asset_class:
              defaults.s_asset_class != null
                ? String(defaults.s_asset_class)
                : form.getValues("s_asset_class"),
            t_o_t: defaults.t_o_t != null ? String(defaults.t_o_t) : form.getValues("t_o_t"),
            duration_other:
              defaults.duration_other != null
                ? String(defaults.duration_other)
                : form.getValues("duration_other"),
          });
        }
      })
      .catch((error) => {
        if (cancelled) return;
        setOptionsError(error instanceof Error ? error.message : "Could not load form options.");
      })
      .finally(() => {
        if (!cancelled) setLoadingOptions(false);
      });

    return () => {
      cancelled = true;
    };
  }, [form, initialValues]);

  const fieldLocked = React.useCallback(
    (name: keyof StructureFormValues | "underlyings") => isSale && name !== "t_date",
    [isSale],
  );

  return (
    <FormProvider {...form}>
      <form
        id={formId}
        noValidate
        onSubmit={form.handleSubmit(withServerValidationErrors(form.setError, onSubmit))}
        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}
        {isSale ? (
          <p className="mb-4 text-muted-foreground text-sm">
            Sale transaction: only {structureFieldLabels.t_date} can be edited (Yii1 parity).
          </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="Structure details"
              description="Placement, expiry, observation dates, coupon, and product identifiers."
              icon={<ClipboardList className="size-4" />}
              contentClassName={formGridClass}
            >
              <DateField
                control={form.control}
                name="t_date"
                label={structureFieldLabels.t_date}
                readOnly={fieldLocked("t_date")}
              />
              <TextField
                control={form.control}
                name="i_rate"
                label={structureFieldLabels.i_rate}
                readOnly={fieldLocked("i_rate")}
              />
              <DateField
                control={form.control}
                name="m_date"
                label={structureFieldLabels.m_date}
                readOnly={fieldLocked("m_date")}
              />
              <DateField
                control={form.control}
                name="o_date"
                label={structureFieldLabels.o_date}
                readOnly={fieldLocked("o_date")}
              />
              <TextField
                control={form.control}
                name="ko_barrirer"
                label={structureFieldLabels.ko_barrirer}
                readOnly={fieldLocked("ko_barrirer")}
              />
              <TextField
                control={form.control}
                name="product_type"
                label={structureFieldLabels.product_type}
                readOnly={fieldLocked("product_type")}
              />
              <TextField
                control={form.control}
                name="s_isin"
                label={structureFieldLabels.s_isin}
                readOnly={fieldLocked("s_isin")}
              />
              <TextField
                control={form.control}
                name="structure_name"
                label={structureFieldLabels.structure_name}
                readOnly={fieldLocked("structure_name")}
              />
              <TextField
                control={form.control}
                name="price"
                label={structureFieldLabels.price}
                readOnly={fieldLocked("price")}
              />
              <TextField
                control={form.control}
                name="duration"
                label={structureFieldLabels.duration}
                readOnly={fieldLocked("duration")}
              />
              <SelectField
                control={form.control}
                name="duration_other"
                label={structureFieldLabels.duration_other}
                options={DURATION_UNIT_OPTIONS}
                disabled={fieldLocked("duration_other")}
              />
              <TextField
                control={form.control}
                name="amount"
                label={structureFieldLabels.amount}
                readOnly
              />
              <SelectField
                control={form.control}
                name="p_currency"
                label={structureFieldLabels.p_currency}
                options={toSelectOptions(formOptions.currencies)}
                searchable
                searchPlaceholder="Search currency…"
                disabled={fieldLocked("p_currency")}
              />
              <TextField
                control={form.control}
                name="r_no"
                label={structureFieldLabels.r_no}
                readOnly={fieldLocked("r_no")}
              />
              <TextField
                control={form.control}
                name="s_percentage"
                label={structureFieldLabels.s_percentage}
                readOnly={fieldLocked("s_percentage")}
              />
              <SelectField
                control={form.control}
                name="bank_id"
                label={structureFieldLabels.bank_id}
                options={toSelectOptions(formOptions.banks)}
                searchable
                searchPlaceholder="Search bank…"
                disabled={fieldLocked("bank_id")}
              />
            </TransactionFormSection>

            <TransactionFormSection
              title="Underlying assets"
              description="Add up to four underlying rows (options[ticker][], options[isin][], …)."
              icon={<Layers3 className="size-4" />}
            >
              <div className="overflow-x-auto rounded-lg border border-border/70">
                <table className="min-w-full text-sm">
                  <thead className="bg-muted/40 text-left text-muted-foreground text-xs uppercase tracking-wide">
                    <tr>
                      <th className="px-3 py-2">Underlying</th>
                      <th className="px-3 py-2">{structureFieldLabels.reference_link}</th>
                      <th className="px-3 py-2">{structureFieldLabels.p_currency}</th>
                      <th className="px-3 py-2">{structureFieldLabels.spot_price}</th>
                      <th className="px-3 py-2">{structureFieldLabels.strike_price}</th>
                      <th className="px-3 py-2">Quantity</th>
                      {!fieldLocked("underlyings") ? <th className="px-3 py-2 w-20" /> : null}
                    </tr>
                  </thead>
                  <tbody>
                    {fields.map((field, index) => (
                      <tr key={field.id} className="border-t border-border/60 align-top">
                        <td className="px-2 py-2">
                          <div className="grid gap-2 sm:grid-cols-2">
                            <TextField
                              control={form.control}
                              name={`underlyings.${index}.ticker`}
                              label=""
                              placeholder={structureFieldLabels.underlying_ticker}
                              readOnly={fieldLocked("underlyings")}
                            />
                            <TextField
                              control={form.control}
                              name={`underlyings.${index}.isin`}
                              label=""
                              placeholder={structureFieldLabels.underlying_name}
                              readOnly={fieldLocked("underlyings")}
                            />
                          </div>
                        </td>
                        <td className="px-2 py-2">
                          <TextField
                            control={form.control}
                            name={`underlyings.${index}.reference_link`}
                            label=""
                            readOnly={fieldLocked("underlyings")}
                          />
                        </td>
                        <td className="px-2 py-2">
                          <SelectField
                            control={form.control}
                            name={`underlyings.${index}.currency`}
                            label=""
                            placeholder="Currency"
                            options={toSelectOptions(formOptions.currencies)}
                            searchable
                            searchPlaceholder="Search…"
                            disabled={fieldLocked("underlyings")}
                          />
                        </td>
                        <td className="px-2 py-2">
                          <TextField
                            control={form.control}
                            name={`underlyings.${index}.spot_price`}
                            label=""
                            readOnly={fieldLocked("underlyings")}
                          />
                        </td>
                        <td className="px-2 py-2">
                          <TextField
                            control={form.control}
                            name={`underlyings.${index}.strike_price`}
                            label=""
                            readOnly={fieldLocked("underlyings")}
                          />
                        </td>
                        <td className="px-2 py-2">
                          <TextField
                            control={form.control}
                            name={`underlyings.${index}.quantity`}
                            label=""
                            readOnly={fieldLocked("underlyings")}
                          />
                        </td>
                        {!fieldLocked("underlyings") ? (
                          <td className="px-2 py-2">
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon-sm"
                              disabled={fields.length <= 1}
                              onClick={() => remove(index)}
                              aria-label="Remove underlying row"
                            >
                              <Trash2 className="size-4" />
                            </Button>
                          </td>
                        ) : null}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {!fieldLocked("underlyings") ? (
                <div className="mt-3">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    disabled={fields.length >= MAX_UNDERLYINGS}
                    onClick={() => append({ ...defaultStructureUnderlyingRow })}
                  >
                    <Plus className="size-4" />
                    Add underlying
                  </Button>
                </div>
              ) : null}
            </TransactionFormSection>

            <TransactionFormSection
              title="Fees & notes"
              description="Commission, charges, start date, relationship manager, and remarks."
              icon={<StickyNote className="size-4" />}
              contentClassName={formGridClass}
            >
              <TextField
                control={form.control}
                name="commission"
                label={transactionFieldLabels.commission}
                readOnly={fieldLocked("commission")}
              />
              <TextField
                control={form.control}
                name="b_1"
                label={transactionFieldLabels.b_1}
                readOnly={fieldLocked("b_1")}
              />
              <TextField
                control={form.control}
                name="b_2"
                label={transactionFieldLabels.b_2}
                readOnly={fieldLocked("b_2")}
              />
              <DateField
                control={form.control}
                name="p_date"
                label={structureFieldLabels.p_date}
                readOnly={fieldLocked("p_date")}
              />
              <TextField
                control={form.control}
                name="r_m"
                label={transactionFieldLabels.r_m}
                readOnly={fieldLocked("r_m")}
              />
              <TextField
                control={form.control}
                name="r_link"
                label={structureFieldLabels.r_link}
                readOnly={fieldLocked("r_link")}
              />
              <TextAreaField
                control={form.control}
                name="remarks"
                label={transactionFieldLabels.remarks}
                className={formSpanFull}
                readOnly={fieldLocked("remarks")}
              />
              <TextAreaField
                control={form.control}
                name="purpose"
                label={transactionFieldLabels.purpose}
                className={formSpanFull}
                readOnly={fieldLocked("purpose")}
              />
            </TransactionFormSection>
          </div>

          <StructureFormSummarySidebar formOptions={formOptions} />
        </div>
      </form>
    </FormProvider>
  );
}
