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

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

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

export default function AddPrice({ loading, onSave, onCancel, productType = '' }: AddPriceProps) {
  const { t } = useLocaleContext();
  const { settings } = usePaymentContext();
  const methods = useForm<Price>({
    mode: 'onChange',
    defaultValues: {
      ...DEFAULT_PRICE,
      currency_id: settings.baseCurrency.id,
    },
  });

  const {
    handleSubmit,
    reset,
    formState: { errors },
  } = methods;
  const onSubmit = () => {
    if (Object.keys(errors).length > 0) {
      return;
    }
    handleSubmit(async (formData: any) => {
      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.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={loading} onClick={onSubmit}>
            {loading && <CircularProgress size="small" />} {t('common.save')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <ProductsProvider>
          <PriceForm productType={productType} />
        </ProductsProvider>
      </FormProvider>
    </Dialog>
  );
}
