import Dialog from '@arcblock/ux/lib/Dialog';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, usePaymentContext } from '@blocklet/payment-react';
import { Button, CircularProgress, Stack } from '@mui/material';
import { useSetState } from 'ahooks';
import type { EventHandler } from 'react';
import { FormProvider, useFieldArray, useForm } from 'react-hook-form';

import PriceForm, { DEFAULT_PRICE } from '../price/form';
import ProductForm, { Product } from './form';
import { ProductsProvider } from '../../contexts/products';

export default function CreateProduct({
  simple = true,
  onSave,
  onCancel,
}: {
  simple?: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
}) {
  const { t } = useLocaleContext();
  const { settings } = usePaymentContext();
  const [state, setState] = useSetState({ loading: false });
  const methods = useForm<Product>({
    mode: 'onChange',
    defaultValues: {
      type: 'service',
      name: '',
      description: '',
      images: [],
      statement_descriptor: '',
      unit_label: '',
      features: [],
      prices: [{ ...DEFAULT_PRICE, currency_id: settings.baseCurrency.id }],
      metadata: [],
    },
  });

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = methods;
  const prices = useFieldArray({ control, name: 'prices' });

  const onCreate = (data: Product) => {
    setState({ loading: true });
    return api
      .post('/api/products', data)
      .then(() => {
        Toast.success(t('admin.product.saved'));
      })
      .catch((err: any) => {
        console.error(err);
        Toast.error(formatError(err));
      })
      .finally(() => {
        setState({ loading: false });
      });
  };

  const onSubmit = () => {
    if (Object.keys(errors).length > 0) {
      return;
    }
    handleSubmit(async (formData: any) => {
      await onCreate(formData);
      await reset();
      await onSave(null);
    })();
  };

  return (
    <Dialog
      open
      disableEscapeKeyDown
      fullWidth
      maxWidth="md"
      onClose={() => onCancel(null)}
      showCloseButton={false}
      title={t('admin.product.add')}
      actions={
        <Stack direction="row">
          <Button size="small" sx={{ mr: 2 }} onClick={onCancel}>
            {t('common.cancel')}
          </Button>
          <Button variant="contained" color="primary" size="small" disabled={state.loading} onClick={onSubmit}>
            {state.loading && <CircularProgress size="small" />} {t('common.save')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <ProductsProvider>
          <ProductForm simple={simple} />
          {prices.fields.map((price, index) => (
            <PriceForm key={price.id} prefix={`prices.${index}`} simple={simple} />
          ))}
        </ProductsProvider>
      </FormProvider>
    </Dialog>
  );
}
