import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import { AddOutlined } from '@mui/icons-material';
import { Button, CircularProgress, Stack } from '@mui/material';
import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { dispatch } from 'use-bus';

import DrawerForm from '../../../components/drawer-form';
import TaxRateForm, { TaxRateFormValues, generateTaxRateDisplayName } from '../../../components/tax/tax-rate-form';

type FormData = TaxRateFormValues;

const DEFAULT_VALUES: FormData = {
  display_name: '',
  description: '',
  country: '',
  state: '',
  postal_code: '',
  tax_code: '',
  percentage: 0,
};

export default function TaxRateCreate() {
  const { t, locale } = useLocaleContext();
  const [loading, setLoading] = useState(false);

  const methods = useForm<FormData>({
    mode: 'onChange',
    defaultValues: DEFAULT_VALUES,
  });

  const { handleSubmit, reset, formState } = methods;

  const handleClose = () => {
    reset(DEFAULT_VALUES);
    dispatch('drawer.submitted');
  };

  const onSubmit = async (values: FormData) => {
    try {
      setLoading(true);
      const { metadata, ...rest } = values;

      const displayName =
        rest.display_name ||
        generateTaxRateDisplayName(
          rest.country,
          rest.state,
          rest.postal_code,
          Number(rest.percentage),
          rest.tax_code,
          locale
        );

      await api.post('/api/tax-rates', {
        ...rest,
        display_name: displayName,
        active: true,
        percentage: Number(rest.percentage),
        metadata,
      });

      Toast.success(t('admin.taxRate.created'));
      dispatch('tax-rate.created');
      dispatch('drawer.submitted');
      handleClose();
    } catch (error) {
      console.error(error);
      Toast.error(formatError(error));
    } finally {
      setLoading(false);
    }
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={t('admin.taxRate.create')}
      onClose={handleClose}
      hideLiveMode
      width={720}
      addons={
        <Stack direction="row" spacing={1}>
          <Button variant="text" color="inherit" onClick={handleClose}>
            {t('common.cancel')}
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={handleSubmit(onSubmit)}
            disabled={loading || !formState.isValid}>
            {loading && <CircularProgress size={16} sx={{ mr: 1 }} />}
            {t('admin.taxRate.createAction')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <TaxRateForm />
      </FormProvider>
    </DrawerForm>
  );
}
