import { useForm, Controller } from 'react-hook-form';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import Dialog from '@arcblock/ux/lib/Dialog';
import { api, formatBNStr, Switch, formatAmountPrecisionLimit, LoadingButton } from '@blocklet/payment-react';
import { Box, Button, Stack, TextField, Typography, Alert, Tooltip, InputAdornment, Divider } from '@mui/material';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { useRequest } from 'ahooks';
import type { TPaymentCurrencyExpanded } from '@blocklet/payment-types';
import Currency from '../../../../components/currency';
import { MAX_SAFE_AMOUNT } from '../../../../libs/util';

type EditFormProps = {
  item: TPaymentCurrencyExpanded | null;
  onClose: () => void;
  onSuccess: () => void;
  isOwner: boolean;
};

type VaultConfigFormData = {
  enabled: boolean;
  deposit_threshold: string;
  withdraw_threshold: string;
  buffer_threshold: string;
};

const VAULT_DEPOSIT_THRESHOLD = '100';
const VAULT_BUFFER_THRESHOLD = '10';

const updateVaultConfig = async (currencyId: string, data: VaultConfigFormData) => {
  const res = await api.put(`/api/payment-currencies/${currencyId}/vault-config`, data);
  return res.data;
};

function EditForm({ item, onClose, onSuccess, isOwner }: EditFormProps) {
  const { t, locale } = useLocaleContext();
  const {
    control,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<VaultConfigFormData>({
    defaultValues: {
      enabled: true,
      deposit_threshold:
        item?.vault_config?.deposit_threshold && item?.vault_config?.deposit_threshold !== '0'
          ? formatBNStr(item.vault_config.deposit_threshold, item?.decimal || 18)
          : VAULT_DEPOSIT_THRESHOLD,
      withdraw_threshold: item?.vault_config?.withdraw_threshold
        ? formatBNStr(item.vault_config.withdraw_threshold, item?.decimal || 18)
        : '0',
      buffer_threshold: item?.vault_config?.buffer_threshold
        ? formatBNStr(item.vault_config.buffer_threshold, item?.decimal || 18)
        : VAULT_BUFFER_THRESHOLD,
    },
    mode: 'onChange',
  });

  const enabled = watch('enabled');
  // const withdrawThreshold = watch('withdraw_threshold');

  const getDepositHelperText = (error?: { message?: string }) => {
    if (error) return error.message;
    return t('admin.vaultConfig.depositThresholdHelp');
  };

  const getBufferHelperText = (error?: { message?: string }) => {
    if (error) return error.message;
    return t('admin.vaultConfig.bufferThresholdHelp');
  };

  // const getWithdrawHelperText = (error?: { message?: string }, threshold?: string) => {
  //   if (error) return error.message;
  //   return Number(threshold) === 0
  //     ? t('admin.vaultConfig.withdrawThresholdNoLimit')
  //     : t('admin.vaultConfig.withdrawThresholdHelp');
  // };

  const { runAsync: runUpdateVaultConfig, loading } = useRequest(updateVaultConfig, {
    manual: true,
  });

  const onSubmit = (data: VaultConfigFormData) => {
    if (!item) return;

    const getSuccessMessage = () => {
      const originalEnabled = item.vault_config?.enabled;
      if (!originalEnabled && data.enabled) {
        return t('admin.vaultConfig.enableSuccess', {
          currency: item.symbol,
        });
      }
      if (originalEnabled && !data.enabled) {
        return t('admin.vaultConfig.disableSuccess', {
          currency: item.symbol,
        });
      }
      return t('admin.vaultConfig.updateSuccess', {
        currency: item.symbol,
      });
    };

    runUpdateVaultConfig(item.id, data).then(() => {
      Toast.success(getSuccessMessage());
      onSuccess();
    });
  };

  if (!item) return null;

  const renderLabelWithTooltip = (label: string, tooltip: string) => (
    <Stack
      direction="row"
      spacing={1}
      sx={{
        alignItems: 'center',
      }}>
      <Typography variant="subtitle2">{label}</Typography>
      <Tooltip title={tooltip}>
        <HelpOutlineIcon fontSize="small" sx={{ color: 'text.secondary' }} />
      </Tooltip>
    </Stack>
  );

  return (
    <Dialog
      open
      fullWidth
      onClose={onClose}
      className="base-dialog"
      title={
        item.vault_config?.enabled
          ? t('admin.vaultConfig.editTitle', { currency: item.symbol })
          : t('admin.vaultConfig.enableTitle', { currency: item.symbol })
      }
      actions={
        <Stack direction="row" spacing={2}>
          <Button variant="outlined" onClick={onClose}>
            {t('common.cancel')}
          </Button>
          <LoadingButton
            variant="contained"
            color="primary"
            disabled={loading || !isOwner}
            onClick={handleSubmit(onSubmit)}>
            {t('common.save')}
          </LoadingButton>
        </Stack>
      }>
      <Box sx={{ pb: 2 }}>
        <Alert severity="info" sx={{ mb: 3 }}>
          {t('admin.vaultConfig.enableVaultHelp')}
        </Alert>

        <Stack spacing={3}>
          {/* 启用设置 */}
          <Stack
            direction="row"
            sx={{
              alignItems: 'center',
              gap: 2,
            }}>
            <Typography variant="subtitle1">{t('admin.vaultConfig.enableVault')}</Typography>
            <Controller
              name="enabled"
              control={control}
              render={({ field }) => (
                <Switch checked={field.value} onChange={(e) => field.onChange(e.target.checked)} />
              )}
            />
          </Stack>

          {enabled && (
            <>
              <Divider sx={{ my: 1 }} />

              {/* 存入阈值设置 */}
              <Box>
                {renderLabelWithTooltip(
                  t('admin.vaultConfig.depositThreshold'),
                  t('admin.vaultConfig.depositThresholdHelp')
                )}
                <Controller
                  name="deposit_threshold"
                  control={control}
                  rules={{
                    required: true,
                    validate: (value) => {
                      if (Number(value) <= 0) {
                        return t('admin.vaultConfig.depositThresholdRequired');
                      }
                      if (Number(value) > MAX_SAFE_AMOUNT) {
                        return t('common.maxAmount', {
                          max: MAX_SAFE_AMOUNT,
                        });
                      }
                      const validPrecision = formatAmountPrecisionLimit(value.toString(), locale, item.decimal || 6);
                      return validPrecision || true;
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      type="number"
                      error={!!errors.deposit_threshold}
                      helperText={getDepositHelperText(errors.deposit_threshold)}
                      sx={{ mt: 1 }}
                      placeholder={VAULT_DEPOSIT_THRESHOLD}
                      slotProps={{
                        input: {
                          endAdornment: (
                            <InputAdornment position="end">
                              <Box sx={{ display: 'flex', alignItems: 'center', ml: 1 }}>
                                <Currency logo={item.logo} name={item.symbol} />
                              </Box>
                            </InputAdornment>
                          ),
                        },
                        htmlInput: {
                          min: 0,
                          max: MAX_SAFE_AMOUNT,
                        },
                      }}
                    />
                  )}
                />
              </Box>

              {/* 差额阈值设置 */}
              <Box>
                {renderLabelWithTooltip(
                  t('admin.vaultConfig.bufferThreshold'),
                  t('admin.vaultConfig.bufferThresholdHelp')
                )}
                <Controller
                  name="buffer_threshold"
                  control={control}
                  rules={{
                    required: true,
                    validate: (value) => {
                      if (Number(value) < 0) {
                        return t('admin.vaultConfig.bufferThresholdInvalid');
                      }
                      if (Number(value) > MAX_SAFE_AMOUNT) {
                        return t('common.maxAmount', {
                          max: MAX_SAFE_AMOUNT,
                        });
                      }
                      const validPrecision = formatAmountPrecisionLimit(value.toString(), locale, item.decimal || 6);
                      return validPrecision || true;
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      type="number"
                      error={!!errors.buffer_threshold}
                      helperText={getBufferHelperText(errors.buffer_threshold)}
                      sx={{ mt: 1 }}
                      placeholder={VAULT_BUFFER_THRESHOLD}
                      slotProps={{
                        input: {
                          endAdornment: (
                            <InputAdornment position="end">
                              <Box sx={{ display: 'flex', alignItems: 'center', ml: 1 }}>
                                <Currency logo={item.logo} name={item.symbol} />
                              </Box>
                            </InputAdornment>
                          ),
                        },
                        htmlInput: {
                          min: 0,
                          max: MAX_SAFE_AMOUNT,
                        },
                      }}
                    />
                  )}
                />
              </Box>

              {/* 提取阈值设置 */}
              {/* <Box>
                {renderLabelWithTooltip(
                  t('admin.vaultConfig.withdrawThreshold'),
                  t('admin.vaultConfig.withdrawThresholdHelp')
                )}
                <Controller
                  name="withdraw_threshold"
                  control={control}
                  rules={{
                    required: true,
                    validate: (value) => {
                      if (Number(value) < 0) {
                        return t('admin.vaultConfig.withdrawThresholdInvalid');
                      }
                      const validPrecision = formatAmountPrecisionLimit(value.toString(), locale, item.decimal || 6);
                      return validPrecision || true;
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      type="number"
                      error={!!errors.withdraw_threshold}
                      helperText={getWithdrawHelperText(errors.withdraw_threshold, withdrawThreshold)}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <Box sx={{ display: 'flex', alignItems: 'center', ml: 1 }}>
                              <Currency logo={item.logo} name={item.symbol} />
                            </Box>
                          </InputAdornment>
                        ),
                        inputProps: {
                          min: 0,
                        },
                      }}
                      sx={{ mt: 1 }}
                      placeholder="0"
                    />
                  )}
                />
              </Box> */}
            </>
          )}
        </Stack>
      </Box>
    </Dialog>
  );
}

export default EditForm;
