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

import type { Product } from './form';
import ProductForm from './form';

export default function EditProduct({
  product,
  loading,
  onSave,
  onCancel,
}: {
  product: TProduct;
  loading: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
}) {
  const { t } = useLocaleContext();
  const methods = useForm<Product>({
    defaultValues: {
      ...product,
      metadata: isEmpty(product.metadata)
        ? []
        : // @ts-ignore
          Object.keys(product.metadata).map((x) => ({ key: x, value: product.metadata[x] })),
      prices: [],
      // 处理 vendor_config 数据回显
      vendor_config: product.vendor_config
        ? product.vendor_config.map((vendor: any) => ({
            vendor_id: vendor.vendor_id, // 直接使用 vendor_id
            commission_rate: vendor.commission_rate?.toString() || '0',
            commission_type:
              vendor.commission_type === 'fixed_amount' ? 'fixed' : vendor.commission_type || 'percentage',
          }))
        : [],
    },
  });

  const { handleSubmit, reset } = methods;
  const onSubmit = () => {
    handleSubmit(async (formData: any) => {
      await onSave(formData);
      reset();
      onCancel(null);
    })();
  };

  return (
    <Dialog
      open
      disableEscapeKeyDown
      fullWidth
      maxWidth="sm"
      onClose={() => onCancel(null)}
      showCloseButton={false}
      className="base-dialog"
      title={t('admin.product.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}>
        <ProductForm />
      </FormProvider>
    </Dialog>
  );
}
