/* 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';

export default function ArcBlockMethodForm({ checkDisabled }: { checkDisabled: (key: string) => boolean }) {
  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 (
    <>
      <FormInput
        key="name"
        name="name"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.name.label')}
        placeholder={t('admin.paymentMethod.name.tip')}
        disabled={checkDisabled('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={checkDisabled('description')}
        inputProps={{ maxLength: 255 }}
      />
      <FormInput
        key="secret_key"
        name="settings.arcblock.chain_id"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.arcblock.chain_id.label')}
        placeholder={t('admin.paymentMethod.arcblock.chain_id.tip')}
        disabled={checkDisabled('settings.arcblock.chain_id')}
      />
      <FormInput
        key="api_host"
        name="settings.arcblock.api_host"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.arcblock.api_host.label')}
        placeholder={t('admin.paymentMethod.arcblock.api_host.tip')}
        disabled={checkDisabled('settings.arcblock.api_host')}
      />
      <FormInput
        key="explorer_host"
        name="settings.arcblock.explorer_host"
        type="text"
        rules={{ required: true }}
        label={t('admin.paymentMethod.arcblock.explorer_host.label')}
        placeholder={t('admin.paymentMethod.arcblock.explorer_host.tip')}
        disabled={checkDisabled('settings.arcblock.explorer_host')}
      />
      <Stack direction="column">
        <Typography
          sx={{
            mb: 1,
          }}>
          {t('admin.paymentCurrency.logo.label')}
        </Typography>
        <Uploader onUploaded={onUploaded} preview={logo} disabled={checkDisabled('logo')} />
      </Stack>
    </>
  );
}
