import Dialog from '@arcblock/ux/lib/Dialog';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput } from '@blocklet/payment-react';
import type { TPaymentLink } from '@blocklet/payment-types';
import { Button, CircularProgress, Stack } from '@mui/material';
import type { EventHandler } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

export default function RenamePaymentLink({
  data,
  loading,
  onSave,
  onCancel,
}: {
  data: TPaymentLink;
  loading: boolean;
  onSave: EventHandler<any>;
  onCancel: EventHandler<any>;
}) {
  const { t } = useLocaleContext();
  const methods = useForm<TPaymentLink>({
    defaultValues: {
      name: data.name,
    },
  });

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

  return (
    <Dialog
      open
      disableEscapeKeyDown
      fullWidth
      maxWidth="sm"
      className="base-dialog"
      onClose={() => onCancel(null)}
      showCloseButton={false}
      title={t('admin.paymentLink.rename')}
      actions={
        <Stack direction="row">
          <Button size="small" sx={{ mr: 2 }} onClick={onCancel}>
            {t('common.cancel')}
          </Button>
          <Button variant="contained" color="primary" size="small" disabled={loading} onClick={onSubmit}>
            {loading && <CircularProgress size="small" />} {t('common.save')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <FormInput
          name="name"
          rules={{ required: true }}
          label={t('admin.paymentLink.name.label')}
          placeholder={t('admin.paymentLink.name.placeholder')}
          autoFocus
        />
      </FormProvider>
    </Dialog>
  );
}
