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

import type { TMeter } from '@blocklet/payment-types';
import MeterForm, { type TokenConfig } from '../../../../components/meter/form';
import DrawerForm from '../../../../components/drawer-form';

type TMeterForm = TMeter & {
  mode?: 'OffChain' | 'OnChain';
  tokenFactoryAddress?: string;
};

export default function MeterCreate() {
  const { t } = useLocaleContext();
  const { refresh } = usePaymentContext();
  const [tokenConfig, setTokenConfig] = useLocalStorageState<TokenConfig>('payment_kit_token_config', {
    defaultValue: { name: '', symbol: '', tokenFactoryAddress: '' },
  });
  const methods = useForm<TMeterForm>({
    defaultValues: {
      name: '',
      event_name: '',
      aggregation_method: 'sum',
      unit: '',
      description: '',
      metadata: {},
      mode: 'OffChain',
    },
  });

  const onSubmit = async (data: TMeterForm) => {
    try {
      const submitData: any = { ...data };
      delete submitData.mode;

      if (data.mode === 'OnChain') {
        let tokenFactoryAddress = tokenConfig?.tokenFactoryAddress;
        // Create new token if no existing token selected
        if (!tokenFactoryAddress && tokenConfig?.symbol) {
          const { data: factory } = await api.post('/api/credit-tokens', {
            name: tokenConfig.name,
            symbol: tokenConfig.symbol,
          });
          tokenFactoryAddress = factory.address;
        }
        if (tokenFactoryAddress) {
          submitData.token = { tokenFactoryAddress };
        }
      }

      await api.post('/api/meters', submitData);
      Toast.success(t('admin.meter.saved'));
      setTokenConfig({ name: '', symbol: '', tokenFactoryAddress: '' });
      methods.reset();
      dispatch('meter.created');
      dispatch('drawer.submitted');
      refresh(true);
    } catch (err: any) {
      Toast.error(formatError(err));
    }
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={t('admin.meter.add')}
      onClose={methods.clearErrors}
      width={640}
      addons={
        <Button
          variant="contained"
          size="small"
          disabled={methods.formState.isSubmitting}
          onClick={methods.handleSubmit(onSubmit as any)}>
          {t('admin.meter.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <MeterForm tokenConfig={tokenConfig!} onTokenConfigChange={setTokenConfig} />
      </FormProvider>
    </DrawerForm>
  );
}
