/* eslint-disable @typescript-eslint/indent */
import Dialog from '@arcblock/ux/lib/Dialog';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Button, CircularProgress, Stack } from '@mui/material';
import { fromUnitToToken } from '@ocap/util';
import { cloneDeep, isEmpty } from 'lodash';
import type { EventHandler } from 'react';
import Toast from '@arcblock/ux/lib/Toast';
import { FormProvider, useForm } from 'react-hook-form';

import { getPricingModel } from '../../libs/util';
import PriceForm, { DEFAULT_PRICE, Price } from '../price/form';
import { ProductsProvider } from '../../contexts/products';

interface EditPriceProps {
  price: Price;
  loading: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
  productType?: string;
}

export default function EditPrice({ price, loading, onSave, onCancel, productType = '' }: EditPriceProps) {
  const { t } = useLocaleContext();

  // 处理 metadata 的回填逻辑
  const processMetadata = (metadata: any) => {
    if (isEmpty(metadata)) {
      return {};
    }

    return metadata;
  };

  const methods = useForm<Price>({
    mode: 'onChange',
    defaultValues: {
      ...price,
      unit_amount: fromUnitToToken(price.unit_amount, price.currency?.decimal),
      // @ts-ignore
      model: getPricingModel(price as any),
      // @ts-ignore
      metadata: processMetadata(price.metadata),
      recurring: price.recurring
        ? {
            ...price.recurring,
          }
        : DEFAULT_PRICE.recurring,
      currency_options: cloneDeep(price.currency_options).map((x: any) => {
        x.unit_amount = fromUnitToToken(x.unit_amount, x.currency?.decimal);
        return x;
      }),
    },
  });

  const {
    handleSubmit,
    reset,
    formState: { errors },
  } = methods;
  const onSubmit = () => {
    if (Object.keys(errors).length > 0) {
      return;
    }
    handleSubmit(async (formData: any) => {
      // Workaround: handleSubmit may not include metadata when Controller returns empty element
      // Use getValues('metadata') as fallback
      if (formData.metadata === undefined) {
        formData.metadata = methods.getValues('metadata');
      }

      if (
        Number(formData.quantity_available) > 0 &&
        Number(formData.quantity_available) < Number(formData.quantity_sold)
      ) {
        Toast.warning(t('admin.price.quantityAvailable.valid'));
        return;
      }
      await onSave(formData);
      reset();
      onCancel(null);
    })();
  };

  return (
    <Dialog
      open
      disableEscapeKeyDown
      fullWidth
      maxWidth="sm"
      className="base-dialog"
      onClose={() => onCancel(null)}
      showCloseButton={false}
      title={t('admin.price.edit')}
      actions={
        <Stack direction="row">
          <Button size="small" sx={{ mr: 2 }} onClick={onCancel}>
            {t('common.cancel')}
          </Button>
          <Button variant="contained" color="primary" size="small" disabled={loading} onClick={onSubmit}>
            {loading && <CircularProgress size="small" />} {t('common.save')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <ProductsProvider>
          <PriceForm productType={productType || price.product?.type} />
        </ProductsProvider>
      </FormProvider>
    </Dialog>
  );
}
