/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, usePaymentContext } from '@blocklet/payment-react';
import type { TPaymentMethod } from '@blocklet/payment-types';
import { AddOutlined } from '@mui/icons-material';
import { Button, Typography } from '@mui/material';
import { FormProvider, useForm } from 'react-hook-form';
import { dispatch } from 'use-bus';

import DrawerForm from '../../../../components/drawer-form';
import PaymentMethodForm from '../../../../components/payment-method/form';

export default function PaymentMethodCreate() {
  const { t } = useLocaleContext();
  const settings = usePaymentContext();

  const methods = useForm<TPaymentMethod & any>({
    defaultValues: {
      type: 'arcblock',
      name: '',
      description: '',
      settings: {
        arcblock: {
          chain_id: '',
          api_host: '',
          explorer_host: '',
          logo: '',
        },
        stripe: {
          dashboard: settings.livemode ? 'https://dashboard.stripe.com' : 'https://dashboard.stripe.com/test',
          publishable_key: '',
          secret_key: '',
        },
        ethereum: {
          api_host: '',
          explorer_host: '',
          native_symbol: 'ETH',
          confirmation: 1,
          logo: '',
        },
        base: {
          api_host: '',
          explorer_host: '',
          native_symbol: 'ETH',
          confirmation: 1,
          logo: '',
        },
        bitcoin: {
          chain_id: 0,
          api_host: '',
          explorer_host: '',
          logo: '',
        },
        google_play: {
          package_name: '',
          service_account_json: '',
          pubsub_topic_name: '',
        },
        app_store: {
          bundle_id: '',
          environment: 'sandbox',
          issuer_id: '',
          key_id: '',
          private_key_pem: '',
        },
      },
    },
  });
  const { handleSubmit } = methods;

  const onSubmit = (data: TPaymentMethod) => {
    api
      .post('/api/payment-methods', data)
      .then(() => {
        Toast.success(t('admin.paymentMethod.saved'));
        methods.reset();
        dispatch('drawer.submitted');
        dispatch('paymentMethod.created');
      })
      .catch((err: any) => {
        console.error(err);
        Toast.error(formatError(err));
      });
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={t('admin.paymentMethod.add')}
      width={640}
      footer={
        <Button variant="contained" size="large" onClick={handleSubmit(onSubmit)} sx={{ width: '100%' }}>
          {t('common.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <Typography variant="h6" sx={{ mb: 3, fontWeight: 600 }}>
          {t('admin.paymentMethod.type')}
        </Typography>
        <PaymentMethodForm />
      </FormProvider>
    </DrawerForm>
  );
}
