/* eslint-disable react/prop-types */
import pick from 'lodash/pick';
import { Confirm } from '@arcblock/ux/lib/Dialog';
import { Box } from '@mui/material';
import Toast from '@arcblock/ux/lib/Toast';
import CardSelector from '@arcblock/ux/lib/CardSelector';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useCreation, useMemoizedFn } from 'ahooks';
import { createPassportSvg } from '@arcblock/ux/lib/Util/passport';

// eslint-disable-next-line import/no-unresolved
import { ReactGA } from '@arcblock/ux/lib/withTracker';
// eslint-disable-next-line import/no-unresolved
import Guest from '../OAuth/guest.svg?react';

export const parseResponse = (data) => {
  if (!data) {
    return {};
  }

  // for backward compatibility
  if (typeof data === 'string') {
    return { sessionToken: data };
  }

  return pick(data, ['sessionToken', 'refreshToken', 'visitorId', 'destroySessionId', 'csrfToken']);
};

const translations = {
  zh: {
    switchPassport: '切换通行证',
    switchPassportFailed: '切换通行证失败',
    switchPassportSucceed: '切换通行证成功',
    selectedPassport: '请选择一个通行证',
    switch: '切换',
    cancel: '取消',
    currentRole: '当前角色：',
    passport: '通行证',
    getPassportFailed: '获取通行证失败',
  },
  en: {
    switchPassport: 'Switch passport',
    switchPassportFailed: 'Switch passport failed',
    switchPassportSucceed: 'Switch passport succeed',
    selectedPassport: 'Select a passport to switch',
    switch: 'Switch',
    cancel: 'Cancel',
    currentRole: 'Current role: ',
    passport: 'Passport',
    getPassportFailed: 'Get passports failed',
  },
};

export function PassportSwitcher({ api, locale, switchState, onSwitchPassport, session }) {
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const visiblePassports = useCreation(() => {
    return switchState.passports.filter((x) => x.role !== switchState.currentUser?.role);
  }, [switchState.passports, switchState.currentUser?.role]);

  const onSwitch = async () => {
    const passportId = switchState.selectedPassport;
    const fromRole = session?.user?.role;
    const toRole = session?.user?.passports?.find((x) => x.id === passportId)?.role ?? 'guest';
    const change = `${fromRole} -> ${toRole}`;
    try {
      const { data } = await api.post('/switch', { passportId });
      const { sessionToken, refreshToken, csrfToken } = parseResponse(data);
      onSwitchPassport({ sessionToken, refreshToken, csrfToken });
      Toast.success(t('switchPassportSucceed'));

      /**
       * @type {import('@arcblock/ux/lib/withTracker/action/switch-passport').SwitchPassportSuccessEvent}
       */
      const switchPassportSuccessEvent = {
        action: 'switchPassportSuccess',
        change,
        success: true,
      };
      ReactGA.event(switchPassportSuccessEvent.action, switchPassportSuccessEvent);
    } catch (err) {
      const errorMessage = err.message || t('switchPassportFailed');
      /**
       * @type {import('@arcblock/ux/lib/withTracker/action/switch-passport').SwitchPassportFailedEvent}
       */
      const switchPassportFailedEvent = {
        action: 'switchPassportFailed',
        success: false,
        change,
        errorMessage,
      };
      ReactGA.event(switchPassportFailedEvent.action, switchPassportFailedEvent);
      Toast.error(errorMessage);
    }
  };

  return (
    <Confirm
      open={switchState.open}
      title={t('switchPassport')}
      onConfirm={onSwitch}
      onCancel={switchState.reset}
      confirmButton={{
        text: t('switch'),
        props: {
          variant: 'contained',
          color: 'primary',
        },
      }}
      cancelButton={{
        text: t('cancel'),
        props: {
          color: 'inherit',
        },
      }}
      PaperProps={{ style: { width: 600 } }}>
      <Box
        sx={{
          mb: 2,
        }}>
        {t('currentRole')}
        {switchState.currentUser?.role}
      </Box>
      <CardSelector
        width={160}
        height={240}
        cardSpace={24}
        list={[
          // eslint-disable-next-line react/no-unstable-nested-components
          () => <Guest />,
          ...visiblePassports.map((x) => {
            if (x.display) {
              return {
                src: x.display,
                name: x.title,
              };
            }

            // eslint-disable-next-line react/no-unstable-nested-components, react/function-component-definition
            return () => (
              <Box
                key={x.id}
                sx={{ width: '100%' }}
                dangerouslySetInnerHTML={{
                  __html: createPassportSvg(x),
                }}
              />
            );
          }),
        ]}
        onSelect={(index) => {
          switchState.selectedPassport = index > 0 ? visiblePassports[index - 1].id : undefined;
        }}
        defaultIndex={0}
      />
    </Confirm>
  );
}
