/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, ConfirmDialog, formatBNStr, Link, parseMarkedText, Table, useMobile } from '@blocklet/payment-react';
import { Alert, Avatar, Box, Button, CircularProgress, Stack, Tooltip, Typography, useTheme } from '@mui/material';
import { useRequest, useSetState } from 'ahooks';
import Empty from '@arcblock/ux/lib/Empty';
import { HelpOutline } from '@mui/icons-material';
import type { TPaymentCurrencyExpanded } from '@blocklet/payment-types';
import Toast from '@arcblock/ux/lib/Toast';
import { styled } from '@mui/system';
import { useSessionContext } from '../../../../contexts/session';

import EditForm from './edit-form';

export const getVaultConfigs = async () => {
  const res = await api.get('/api/payment-currencies/vault-config');
  return res.data;
};

export const checkDepositVault = async (currencyId: string) => {
  const res = await api.get(`/api/payment-currencies/${currencyId}/deposit-vault`);
  return res.data;
};

export const depositToVault = async (currencyId: string) => {
  const res = await api.put(`/api/payment-currencies/${currencyId}/deposit-vault`);
  return res.data;
};

export default function VaultConfig() {
  const { t } = useLocaleContext();
  const { session } = useSessionContext();
  const { isMobile } = useMobile();
  const theme = useTheme();
  const isOwner = session?.user?.role === 'owner';

  const [state, setState] = useSetState({
    item: null as TPaymentCurrencyExpanded | null,
    edit: false,
    confirm: false,
  });

  const {
    data = {
      list: [],
      balances: {},
    },
    loading,
    error,
    refresh,
  } = useRequest(getVaultConfigs, {
    onSuccess: (res) => {
      if (res.error) {
        Toast.error(res.error);
      }
    },
  });

  const { runAsync: runCheckDepositVault } = useRequest(checkDepositVault, {
    manual: true,
    onSuccess: (result) => {
      if (result.depositAmount && result.depositAmount !== '0') {
        setState({
          confirm: true,
        });
      }
    },
  });
  const handleEditClick = (item: TPaymentCurrencyExpanded) => {
    setState({
      item,
      edit: true,
    });
  };

  const handleFormClose = () => {
    setState({
      edit: false,
    });
  };

  // 确认转入冷钱包
  const handleDepositConfirm = async () => {
    if (!state.item) return;
    try {
      setState({ confirm: false });
      await depositToVault(state.item.id);
      Toast.success(t('admin.vaultConfig.depositQueued'));
    } catch (err) {
      Toast.error(t('admin.vaultConfig.depositFailed'));
    }
  };

  const handleFormSuccess = () => {
    if (state.item) {
      runCheckDepositVault(state.item.id);
    }
    refresh();
    handleFormClose();
  };

  const columns = [
    {
      label: t('common.currency'),
      name: 'symbol',
      options: {
        customBodyRenderLite: (dataIndex: number) => {
          const item = data.list?.[dataIndex];
          if (!item) {
            return '-';
          }
          return (
            <Stack
              direction="row"
              spacing={1}
              sx={{
                alignItems: 'center',
              }}>
              <Avatar src={item.logo} alt={item.symbol} style={{ width: 24, height: 24 }} />
              <Box>
                <Typography variant="body2">{item.symbol}</Typography>
                {!isMobile && (
                  <Typography
                    variant="caption"
                    sx={{
                      color: 'text.secondary',
                    }}>
                    {item.payment_method?.name}
                  </Typography>
                )}
              </Box>
            </Stack>
          );
        },
      },
    },
    {
      label: t('admin.vaultConfig.appBalance'),
      name: 'id',
      options: {
        customBodyRenderLite: (dataIndex: number) => {
          const item = data.list?.[dataIndex];
          if (!item) {
            return '-';
          }
          return (
            <Typography variant="body1">
              {formatBNStr(data.balances?.[item.id] || '0', item.decimal)} {item.symbol}
            </Typography>
          );
        },
      },
    },
    {
      label: t('admin.vaultConfig.enabled'),
      name: 'vault_enabled',
      options: {
        customBodyRenderLite: (dataIndex: number) => {
          const item = data.list?.[dataIndex];
          if (!item) {
            return '-';
          }
          const enabled = item.vault_config?.enabled;
          return (
            <Stack
              direction="row"
              spacing={1}
              sx={{
                alignItems: 'center',
              }}>
              <Box
                sx={{
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  bgcolor: enabled ? 'success.main' : 'text.lighter',
                }}
              />
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {enabled ? t('admin.vaultConfig.enabledYes') : t('admin.vaultConfig.enabledNo')}
              </Typography>
            </Stack>
          );
        },
      },
    },
    {
      label: t('admin.vaultConfig.depositThreshold'),
      name: 'deposit_threshold',
      options: {
        customBodyRenderLite: (dataIndex: number) => {
          const item = data.list?.[dataIndex];
          if (!item) {
            return '-';
          }
          if (!item?.vault_config) {
            return (
              <Typography
                variant="body2"
                sx={{
                  color: 'text.secondary',
                }}>
                {t('admin.vaultConfig.notConfig')}
              </Typography>
            );
          }
          return (
            <Typography variant="body1">
              {formatBNStr(item.vault_config?.deposit_threshold || '0', item.decimal)} {item.symbol}
            </Typography>
          );
        },
        customHeadLabelRender: () => {
          return (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1,
              }}>
              {t('admin.vaultConfig.depositThreshold')}
              <Tooltip title={t('admin.vaultConfig.depositThresholdHelp')}>
                <HelpOutline fontSize="small" sx={{ color: 'text.lighter' }} />
              </Tooltip>
            </Box>
          );
        },
      },
    },
    {
      label: t('admin.vaultConfig.bufferThreshold'),
      name: 'buffer_threshold',
      options: {
        customBodyRenderLite: (dataIndex: number) => {
          const item = data.list?.[dataIndex];
          if (!item) {
            return '-';
          }
          if (!item?.vault_config) {
            return (
              <Typography
                variant="body2"
                sx={{
                  color: 'text.secondary',
                }}>
                {t('admin.vaultConfig.notConfig')}
              </Typography>
            );
          }
          return (
            <Typography variant="body1">
              {formatBNStr(item.vault_config?.buffer_threshold || '0', item.decimal)} {item.symbol}
            </Typography>
          );
        },
        customHeadLabelRender: () => {
          return (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1,
              }}>
              {t('admin.vaultConfig.bufferThreshold')}
              <Tooltip title={t('admin.vaultConfig.bufferThresholdHelp')}>
                <HelpOutline fontSize="small" sx={{ color: 'text.lighter' }} />
              </Tooltip>
            </Box>
          );
        },
      },
    },
    // {
    //   label: t('admin.vaultConfig.withdrawThreshold'),
    //   name: 'withdraw_threshold',
    //   options: {
    //     customBodyRenderLite: (dataIndex: number) => {
    //       const item = data.list[dataIndex];
    //       if (!item.vault_config) {
    //         return (
    //           <Typography variant="body2" color="text.secondary">
    //             {t('admin.vaultConfig.notConfig')}
    //           </Typography>
    //         );
    //       }
    //       return (
    //         <Typography variant="body1">
    //           {item.vault_config?.withdraw_threshold === '0'
    //             ? t('admin.vaultConfig.noLimit')
    //             : `${formatBNStr(item.vault_config?.withdraw_threshold || '0', item.decimal)} ${item.symbol}`}
    //         </Typography>
    //       );
    //     },
    //     customHeadLabelRender: () => {
    //       return (
    //         <Box display="flex" alignItems="center" gap={1}>
    //           {t('admin.vaultConfig.withdrawThreshold')}
    //           <Tooltip title={t('admin.vaultConfig.withdrawThresholdHelp')}>
    //             <HelpOutline fontSize="small" sx={{ color: 'text.lighter' }} />
    //           </Tooltip>
    //         </Box>
    //       );
    //     },
    //   },
    // },
    ...(isOwner
      ? [
          {
            label: t('common.actions'),
            name: 'actions',
            options: {
              customBodyRenderLite: (dataIndex: number) => {
                const item = data.list?.[dataIndex];
                if (!item) {
                  return null;
                }
                const enabled = item.vault_config?.enabled;
                return (
                  <Button
                    size="small"
                    variant="text"
                    onClick={() => handleEditClick(item)}
                    sx={{
                      color: 'text.link',
                      minWidth: 'fit-content',
                    }}>
                    {enabled ? t('common.edit') : t('admin.vaultConfig.enable')}
                  </Button>
                );
              },
            },
          },
        ]
      : []),
  ];

  if (loading) {
    return <CircularProgress />;
  }

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  const renderEmpty = () => {
    const configFirst = t('admin.vaultConfig.configureFirst');
    const parsedParts = parseMarkedText(configFirst);

    return (
      <Empty>
        <Typography variant="body1">{t('admin.vaultConfig.notConfigured')}</Typography>
        <Typography
          variant="body2"
          sx={{
            mt: 1,
            display: 'flex',
            alignItems: 'center',
            gap: 0.5,
          }}>
          {parsedParts.map((part: { type: 'text' | 'marked'; content: string }) =>
            part.type === 'text' ? (
              part.content
            ) : (
              <Link
                key={part.content}
                to={`${window.location.origin}/.well-known/service/admin/operations/advanced`}
                style={{ color: theme.palette.text.link }}>
                {part.content}
              </Link>
            )
          )}
        </Typography>
      </Empty>
    );
  };

  return (
    <Root>
      <Box
        sx={{
          mb: 2,
        }}>
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
            mt: 1,
          }}>
          {t('admin.vaultConfig.description')}
          <Box
            component="a"
            href="https://www.arcblock.io/docs/arcblock-payment-kit/en/vault-config"
            target="_blank"
            rel="noopener noreferrer"
            sx={{ color: 'text.link', textDecoration: 'none', ml: 0.5 }}>
            {t('admin.vaultConfig.learnMore')}
          </Box>
        </Typography>

        {!isOwner && (
          <Alert severity="warning" sx={{ mt: 2 }}>
            {t('admin.vaultConfig.ownerOnly')}
          </Alert>
        )}
      </Box>
      <Table
        data={Array.isArray(data.list) ? data.list : []}
        columns={columns}
        options={{
          pagination: false,
          selectableRows: 'none',
        }}
        mobileTDFlexDirection="row"
        toolbar={false}
        footer={false}
        emptyNode={renderEmpty()}
      />
      {state.edit && state.item && (
        <EditForm item={state.item} onClose={handleFormClose} onSuccess={handleFormSuccess} isOwner={isOwner} />
      )}
      {state.confirm && state.item && (
        <ConfirmDialog
          title={t('admin.vaultConfig.depositConfirmTitle')}
          message={t('admin.vaultConfig.depositConfirmMessage', {
            currency: state.item.symbol,
          })}
          onCancel={() => setState({ confirm: false })}
          onConfirm={handleDepositConfirm}
          color="primary"
        />
      )}
    </Root>
  );
}

const Root = styled(Box)`
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    .MuiTable-root > .MuiTableBody-root > .MuiTableRow-root > td.MuiTableCell-root {
      > div {
        width: fit-content;
        flex: inherit;
        font-size: 14px;
      }
    }
    .invoice-summary {
      padding-right: 20px;
    }
  }
`;
