/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, getPrefix, CachedRequest } from '@blocklet/payment-react';
import type { TPaymentCurrency, TPaymentMethod } from '@blocklet/payment-types';
import { AddOutlined } from '@mui/icons-material';
import { Button, CircularProgress } from '@mui/material';
import { useSetState } from 'ahooks';
import { FormProvider, useForm } from 'react-hook-form';
import { dispatch } from 'use-bus';
import { useEffect } from 'react';
import { joinURL } from 'ufo';

import DrawerForm from '../drawer-form';
import PaymentCurrencyForm from './form';

const loadTokenList = () =>
  import(
    /* webpackChunkName: "payment-token-list" */
    './tokenList.json'
  );

interface TokenInfo {
  address: string;
  chainId: number;
  decimals: number;
  name: string;
  symbol: string;
  logoURI?: string;
  localLogoURI?: string;
}

export default function PaymentCurrencyEdit({
  method,
  onClose,
  value,
}: {
  method: TPaymentMethod;
  onClose: () => void;
  value: TPaymentCurrency;
}) {
  const { t } = useLocaleContext();
  const [state, setState] = useSetState({
    loading: false,
    tokenListLoading: false,
    contractToTokenMap: new Map<string, TokenInfo>(),
  });

  const methods = useForm<TPaymentCurrency>({
    defaultValues: {
      payment_method_id: method.id,
      name: value?.name,
      description: value?.description,
      logo: value?.logo,
      contract: value?.contract,
    },
  });
  const { handleSubmit, setValue } = methods;

  const showTokenSelect = ['ethereum', 'base'].includes(method.type);
  // @ts-ignore
  const chainId = method?.settings?.[method.type]?.chain_id || '';

  const getLogoURI = (token: TokenInfo) => {
    if (token.localLogoURI) {
      return joinURL(getPrefix(), token.localLogoURI);
    }
    return token.logoURI || '';
  };

  useEffect(() => {
    if (showTokenSelect && chainId) {
      setState({ tokenListLoading: true });

      // 使用 CachedRequest 直接缓存 contract 映射
      const cachedTokenMapRequest = new CachedRequest(
        `tokenMap_${chainId}`,
        async () => {
          const module = await loadTokenList();
          // @ts-ignore
          const tokenList = (module.default?.[chainId] as TokenInfo[]) || [];

          // 创建 contract 地址到 token 的映射对象
          const contractToTokenObj: Record<string, TokenInfo> = {};
          tokenList.forEach((token: TokenInfo) => {
            if (token.address) {
              contractToTokenObj[token.address.toLowerCase()] = token;
            }
          });

          return { data: contractToTokenObj };
        },
        {
          strategy: 'session',
          ttl: 30 * 60 * 1000,
        }
      );

      cachedTokenMapRequest
        .fetch()
        .then((contractToTokenObj: Record<string, TokenInfo>) => {
          const contractToTokenMap = new Map<string, TokenInfo>(Object.entries(contractToTokenObj));
          setState({
            contractToTokenMap,
            tokenListLoading: false,
          });

          // 检查当前币种是否需要替换 logo（根据 contract 地址匹配）
          if (value?.contract) {
            const matchedToken = contractToTokenMap.get(value.contract.toLowerCase());
            if (matchedToken && matchedToken.localLogoURI) {
              const newLogoURI = getLogoURI(matchedToken);
              setValue('logo', newLogoURI);
            }
          }
        })
        .catch((error) => {
          console.error('Failed to load token map:', error);
          setState({ tokenListLoading: false });
        });
    }
  }, [showTokenSelect, chainId, value?.contract]);

  const onSubmit = (data: TPaymentCurrency) => {
    setState({ loading: true });
    api
      .put(`/api/payment-currencies/${value.id}`, data)
      .then(() => {
        setState({ loading: false });
        Toast.success(t('admin.paymentCurrency.saved'));
        methods.reset();
        dispatch('drawer.submitted');
        dispatch('paymentCurrency.updated');
      })
      .catch((err: any) => {
        setState({ loading: false });
        console.error(err);
        Toast.error(formatError(err));
      });
  };

  return (
    <DrawerForm
      open
      icon={<AddOutlined />}
      onClose={onClose}
      text={t('admin.paymentCurrency.edit')}
      width={640}
      footer={
        <Button
          variant="contained"
          size="large"
          onClick={handleSubmit(onSubmit)}
          disabled={state.loading}
          sx={{ width: '100%' }}>
          {state.loading && <CircularProgress size={20} />} {t('common.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <PaymentCurrencyForm disableKeys={['contract']} />
      </FormProvider>
    </DrawerForm>
  );
}
