/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import type { TPaymentMethod } from '@blocklet/payment-types';
import { AddOutlined } from '@mui/icons-material';
import { Button, CircularProgress } from '@mui/material';
import { useSetState } from 'ahooks';
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 PaymentMethodEdit({ onClose, value }: { onClose: () => void; value: TPaymentMethod | null }) {
  const { t } = useLocaleContext();
  const [state, setState] = useSetState({ loading: false });

  const methods = useForm<TPaymentMethod>({
    defaultValues: {
      type: value?.type,
      name: value?.name,
      description: value?.description,
      logo: value?.logo,
      settings: value?.settings,
    },
  });
  const { handleSubmit } = methods;

  const onSubmit = (data: TPaymentMethod) => {
    setState({ loading: true });
    api
      .put(`/api/payment-methods/${value?.id}`, data)
      .then(() => {
        setState({ loading: false });
        Toast.success(t('admin.paymentMethod.saved'));
        methods.reset();
        dispatch('drawer.submitted');
        dispatch('paymentMethod.updated');
      })
      .catch((err: any) => {
        setState({ loading: false });
        console.error(err);
        Toast.error(formatError(err));
      });
  };

  return (
    <DrawerForm
      open
      icon={<AddOutlined />}
      onClose={onClose}
      text={t('admin.paymentMethod.edit')}
      width={640}
      footer={
        <Button
          variant="contained"
          size="large"
          onClick={handleSubmit(onSubmit)}
          disabled={state.loading}
          sx={{ width: '100%' }}>
          {state.loading && <CircularProgress size={20} />} {t('common.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <PaymentMethodForm
          action="edit"
          editableKeys={[
            'name',
            'description',
            'logo',
            'settings.base.api_host',
            'settings.base.explorer_host',
            'settings.ethereum.api_host',
            'settings.ethereum.explorer_host',
            'settings.stripe.publishable_key',
            'settings.stripe.secret_key',
            'settings.stripe.dashboard',
          ]}
        />
      </FormProvider>
    </DrawerForm>
  );
}
