/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput } from '@blocklet/payment-react';
import { Stack, Typography } from '@mui/material';
import { useFormContext, useWatch } from 'react-hook-form';

import Uploader from '../uploader';

type TPaymentCurrencyFormProps = {
  disableKeys?: string[];
};

export default function PaymentCurrencyForm({ disableKeys = [] }: TPaymentCurrencyFormProps) {
  const { t } = useLocaleContext();
  const { control, setValue } = useFormContext();
  const logo = useWatch({ control, name: 'logo' });

  const onUploaded = (result: any) => {
    if (!result.url) {
      setValue('logo', '');
      return;
    }
    const tmp = new URL(result.url);
    setValue('logo', tmp.pathname);
  };

  return (
    <Stack
      direction="column"
      spacing={2}
      sx={{
        alignItems: 'flex-start',
      }}>
      <FormInput
        key="name"
        name="name"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.name.label')}
        placeholder={t('admin.paymentMethod.name.tip')}
        disabled={disableKeys.includes('name')}
        inputProps={{ maxLength: 32 }}
      />
      <FormInput
        key="description"
        name="description"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.description.label')}
        placeholder={t('admin.paymentMethod.description.tip')}
        disabled={disableKeys.includes('description')}
        inputProps={{ maxLength: 255 }}
      />
      <FormInput
        key="contract"
        name="contract"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentCurrency.contract.label')}
        placeholder={t('admin.paymentCurrency.contract.tip')}
        disabled={disableKeys.includes('contract')}
      />
      <Stack direction="column">
        <Typography
          sx={{
            mb: 1,
          }}>
          {t('admin.paymentCurrency.logo.label')}
        </Typography>
        <Uploader onUploaded={onUploaded} preview={logo} />
      </Stack>
    </Stack>
  );
}
