/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput } from '@blocklet/payment-react';
import { Box, Typography, CircularProgress } from '@mui/material';
import { useWatch, useFormContext } from 'react-hook-form';
import { CheckCircleOutline, ErrorOutline } from '@mui/icons-material';
import { useRpcStatus } from '../../hooks/rpc-status';

interface Props {
  name: string; // 表单字段名
  label: string;
  placeholder: string;
  disabled?: boolean;
}

export default function EvmRpcInput({ name, label, placeholder, disabled = false }: Props) {
  const { t } = useLocaleContext();
  const { control } = useFormContext();
  const apiHost = useWatch({
    control,
    name,
  });

  const { status } = useRpcStatus(apiHost, { debounce: 500, pollInterval: 2000 });

  return (
    <FormInput
      key="api_host"
      name={name}
      type="text"
      rules={{ required: true }}
      disabled={disabled}
      label={
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          {label}
          {apiHost && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              {status.loading ? (
                <>
                  <CircularProgress size={14} />
                  <Typography
                    variant="caption"
                    sx={{
                      color: 'text.secondary',
                    }}>
                    {t('admin.paymentMethod.evm.checking')}
                  </Typography>
                </>
              ) : status.connected ? (
                <>
                  <CheckCircleOutline sx={{ fontSize: 14 }} color="success" />
                  <Typography
                    variant="caption"
                    sx={{
                      color: 'text.secondary',
                    }}>
                    {t('admin.paymentMethod.evm.connected')} | {t('admin.paymentMethod.evm.blockHeight')}:{' '}
                    {status.blockNumber?.toLocaleString()}
                  </Typography>
                </>
              ) : status.error ? (
                <>
                  <ErrorOutline sx={{ fontSize: 14 }} color="error" />
                  <Typography variant="caption" color="error">
                    {t('admin.paymentMethod.evm.connectionError')}
                  </Typography>
                </>
              ) : null}
            </Box>
          )}
        </Box>
      }
      placeholder={placeholder}
    />
  );
}
