import { Box, BoxProps, Button, CircularProgress, Link, Stack, SxProps, Typography } from '@mui/material';
import { useMemoizedFn, useReactive } from 'ahooks';
import noop from 'lodash/noop';
import type { UserPublicInfo } from '@blocklet/js-sdk';
import { useImperativeHandle, Ref } from 'react';

import DIDConnectContainer from '../did-connect-container';
import AuthAppsInfo, { type RequestAppInfo, type CurrentAppInfo } from './auth-apps-info';
import Center from '../../Center';
import LandingPage from '../landing-page';
import { translate } from '../../Locale/util';
import { useLocaleContext } from '../../Locale/context';
import UserCard from '../../UserCard';
import { CardType, InfoType } from '../../UserCard/types';
import { mergeSx } from '../../Util/style';
import SwitchRole from './switch-role';

const translations = {
  en: {
    notThis: 'Not you?',
    useAnother: 'Use another account',
    authorize: 'Authorize',
    connect: 'Connect',
    cancel: 'Cancel',
  },
  zh: {
    notThis: '不是这个？',
    useAnother: '使用其他账户',
    authorize: '授权',
    connect: 'Connect',
    cancel: '取消',
  },
};

/**
 * @example app/connect-to-did-space?appPid=zNKp8tdZUanWKnvhwZWvF2hKRutwM9ykLaY8&appDid=zNKp8tdZUanWKnvhwZWvF2hKRutwM9ykLaY8&appName=233&appDescription=456&appUrl=https://bbqaw5mgxc6fnihrwqcejcxvukkdgkk4anwxwk5msvm.did.abtnet.io/zh
 */
export default function AuthApps({
  session,
  requestAppInfo,
  currentAppInfo,
  children = null,
  userInfo = undefined,

  hideSwitchConnect = false,
  hideAuthorize = false,
  hideCancel = false,
  hideButton = false,

  notThisText = undefined,
  authorizeText = undefined,
  connectText = undefined,
  cancelText = undefined,
  useAnotherText = undefined,

  slotProps = undefined,

  onConnect = noop,
  onAuthorize = noop,
  onSwitchConnect = noop,
  onSwitchPassport = noop,
  onCancel = noop,
  ref,

  disableAuthorizeButton = false,
}: {
  session: any;
  requestAppInfo: RequestAppInfo;
  currentAppInfo: CurrentAppInfo;
  children?: React.ReactNode;
  userInfo?: UserPublicInfo;

  hideSwitchConnect?: boolean;
  hideAuthorize?: boolean;
  hideCancel?: boolean;
  hideButton?: boolean;

  notThisText?: string;
  authorizeText?: string;
  connectText?: string;
  cancelText?: string;
  useAnotherText?: string;

  slotProps?: {
    root?: BoxProps;
    didConnectContainer?: object;
    contentContainer?: BoxProps;
  };

  onConnect?: (done: () => void) => void;
  onAuthorize?: (done: () => void) => void;
  onSwitchConnect?: (done: () => void) => void;
  onSwitchPassport?: (done: () => void) => void;
  onCancel?: () => void;
  ref: Ref<{ closeLoading: () => void }>;

  disableAuthorizeButton?: boolean;
}) {
  const currentState = useReactive({
    loading: false,
  });
  const { locale = 'en' } = useLocaleContext() || {};

  const t = useMemoizedFn((key, data = {}) => translate(translations, key, locale, 'en', data));

  const handleCloseLoading = useMemoizedFn(() => {
    currentState.loading = false;
  });
  const handleConnect = useMemoizedFn(() => {
    currentState.loading = true;
    onConnect?.(handleCloseLoading);
  });
  const handleSwitchConnect = useMemoizedFn(() => {
    currentState.loading = true;
    onSwitchConnect?.(handleCloseLoading);
  });
  const handleAuthorize = useMemoizedFn(() => {
    currentState.loading = true;
    onAuthorize?.(handleCloseLoading);
  });
  const handleSwitchPassport = useMemoizedFn(() => {
    currentState.loading = true;
    onSwitchPassport?.(handleCloseLoading);
  });
  const handleCancel = useMemoizedFn(() => {
    onCancel?.();
  });

  useImperativeHandle(ref, () => ({
    closeLoading: handleCloseLoading,
  }));

  if (session.loading || !session.initialized) {
    return (
      <Center>
        <CircularProgress />
      </Center>
    );
  }

  const user = userInfo ?? session?.user;

  return (
    <LandingPage did={window.blocklet?.appPid} standalone>
      <Box
        {...slotProps?.root}
        sx={mergeSx(
          {
            width: 420,
            maxWidth: '100%',
          },
          slotProps?.root?.sx as SxProps
        )}>
        <DIDConnectContainer hideCloseButton {...slotProps?.didConnectContainer}>
          <Box
            {...slotProps?.contentContainer}
            sx={mergeSx(
              {
                display: 'flex',
                flexDirection: 'column',
                gap: 1.5,
                p: {
                  xs: 2,
                  lg: 3,
                  xl: 4,
                },
                pt: {
                  xs: 3,
                  xl: 4,
                },
                bgcolor: 'background.paper',
              },
              slotProps?.contentContainer?.sx as SxProps
            )}>
            <AuthAppsInfo requestAppInfo={requestAppInfo} currentAppInfo={currentAppInfo} />

            {user ? (
              <>
                <UserCard
                  user={user}
                  showDid
                  cardType={CardType.Detailed}
                  infoType={InfoType.Minimal}
                  renderTopRightContent={() => <SwitchRole user={user} switchPassport={handleSwitchPassport} />}
                />
                <Box />
              </>
            ) : null}

            {children}

            {hideButton ? null : (
              <>
                <Box
                  sx={{
                    border: '1px solid',
                    borderColor: 'divider',
                    borderRadius: 2,
                    overflow: 'hidden',
                    my: 1,
                  }}
                />

                <Stack direction="row" spacing={2}>
                  {!hideCancel ? (
                    <Button
                      color="inherit"
                      variant="outlined"
                      size="large"
                      fullWidth
                      onClick={handleCancel}
                      sx={{
                        color: 'grey.500',
                      }}>
                      {cancelText || t('cancel')}
                    </Button>
                  ) : null}
                  {user && !hideAuthorize ? (
                    <Button
                      variant="contained"
                      size="large"
                      fullWidth
                      onClick={handleAuthorize}
                      disabled={currentState.loading || disableAuthorizeButton}>
                      {currentState.loading ? <CircularProgress size={20} sx={{ mr: 1 }} /> : null}
                      {authorizeText || t('authorize')}
                    </Button>
                  ) : (
                    <Button
                      variant="contained"
                      size="large"
                      fullWidth
                      disabled={currentState.loading || disableAuthorizeButton}
                      onClick={handleConnect}>
                      {currentState.loading ? <CircularProgress size={20} sx={{ mr: 1 }} /> : null}
                      {connectText || t('connect')}
                    </Button>
                  )}
                </Stack>
              </>
            )}

            {hideSwitchConnect || !user ? null : (
              <Box sx={{ textAlign: 'center' }}>
                <Typography
                  variant="body2"
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 1,
                  }}>
                  {notThisText || t('notThis')} {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                  <Link
                    underline="hover"
                    onClick={handleSwitchConnect}
                    sx={{
                      cursor: 'pointer',
                    }}>
                    {useAnotherText || t('useAnother')}
                  </Link>
                </Typography>
              </Box>
            )}
          </Box>
        </DIDConnectContainer>
      </Box>
    </LandingPage>
  );
}
