/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { isValidCountry } from '@blocklet/payment-react';
import { AddOutlined } from '@mui/icons-material';
import { FormProvider, useForm } from 'react-hook-form';
import { Button, CircularProgress } from '@mui/material';
import type { EventHandler } from 'react';
import type { TCustomer } from '@blocklet/payment-types';

import DrawerForm from '../drawer-form';

import CustomerForm from './form';

export default function EditCustomer({
  data,
  loading,
  onSave,
  onCancel,
}: {
  data: TCustomer;
  loading: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
}) {
  const { t } = useLocaleContext();

  const methods = useForm<TCustomer>({
    defaultValues: {
      name: data.name || '',
      email: data.email || '',
      phone: data.phone || '',
      address: Object.assign(
        {
          country: '',
          state: '',
          city: '',
          line1: '',
          line2: '',
          postal_code: '',
        },
        data.address || {},
        { country: isValidCountry(data.address?.country || '') ? data.address?.country : 'us' }
      ),
    },
  });

  const onSubmit = () => {
    methods.handleSubmit(async (formData: any) => {
      await onSave(formData);
      methods.reset();
      onCancel(null);
    })();
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={t('payment.customer.update')}
      width={520}
      addons={null}
      open
      hideLiveMode
      onClose={onCancel}
      footer={
        <Button variant="contained" color="primary" disabled={loading} onClick={onSubmit} sx={{ width: '100%' }}>
          {loading && <CircularProgress size="small" />} {t('common.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <CustomerForm />
      </FormProvider>
    </DrawerForm>
  );
}
