import { useEffect } from 'react';
import { Box, Typography } from '@mui/material';
import type { BoxProps } from '@mui/material';
import { ROLES } from '@abtnode/constant';
import { useCreation, useMemoizedFn } from 'ahooks';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { mergeSx } from '@arcblock/ux/lib/Util/style';
import useBrowser from '@arcblock/react-hooks/lib/useBrowser';
import { translations } from '../libs/locales';
import Notification from './notification';
import Privacy from './privacy';
import { User, UserCenterTab } from '../../@types';
import { UserSessions } from '../../UserSessions';
import ThirdPartyLogin from './third-party-login';
import ConfigProfile from './config-profile';
import DangerZone from './danger-zone';
import { client } from '../../libs/client';

export default function Settings({
  user,
  settings,
  onSave,
  isMobile,
  ...rest
}: {
  user: User;
  onSave: (type: 'privacy' | 'profile') => void;
  settings: {
    userCenterTabs: UserCenterTab[];
  };
  isMobile: boolean;
  onDestroySelf?: () => void;
} & BoxProps) {
  const { locale } = useLocaleContext();
  const browser = useBrowser();
  const isArcSphere = browser.arcSphere;
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const isOwner = useCreation(() => {
    return user.passports?.some((x) => x.role === ROLES.OWNER);
  }, [user]);

  const privacyConfigList = useCreation(() => {
    const userCenterTabs = settings?.userCenterTabs || [];
    return userCenterTabs.map((item) => {
      return {
        key: item.value,
        name: item.label,
        value: item.protected,
        isPrivate: item.isPrivate,
      };
    });
  }, [settings?.userCenterTabs]);
  const tabs = useCreation(() => {
    return [
      !isArcSphere
        ? {
            label: t('commonSetting.title'),
            value: 'common',
            content: <ConfigProfile user={user} onSave={onSave} />,
          }
        : undefined,
      {
        label: t('notificationManagement'),
        value: 'notification',
        content: <Notification user={user} isMobile={isMobile} />,
      },
      {
        label: t('thirdPartyLogin.title'),
        value: 'thirdPartyLogin',
        content: <ThirdPartyLogin user={user} />,
      },
      {
        label: t('privacyManagement'),
        value: 'privacy',
        // @ts-ignore
        content: <Privacy configList={privacyConfigList} onSave={onSave} />,
      },
      {
        label: t('sessionManagement'),
        value: 'session',
        content: (
          <UserSessions
            user={user}
            showUser={false}
            getUserSessions={(params) => {
              return client.userSession.getMyLoginSessions({}, params);
            }}
          />
        ),
      },
      !isOwner && rest.onDestroySelf && typeof rest.onDestroySelf === 'function'
        ? {
            label: t('dangerZone.title'),
            value: 'dangerZone',
            content: <DangerZone onDestroySelf={rest.onDestroySelf} />,
            sx: {
              borderColor: 'error.main',
            },
          }
        : null,
    ].filter(Boolean);
  }, [user, privacyConfigList, isMobile]);

  // 支持 hash 锚点定位
  useEffect(() => {
    const id = window.location.hash.slice(1);
    if (id) {
      const element = document.getElementById(id);
      element?.scrollIntoView({ behavior: 'smooth' });
    }
  }, []);

  return (
    <Box
      {...rest}
      sx={{
        ...rest?.sx,
        display: 'flex',
        flexDirection: 'column',
        gap: 2.5,
        minWidth: {
          md: 500,
        },
        maxWidth: '100%',
      }}>
      {tabs.map((tab) => {
        if (!tab) {
          return null;
        }
        return (
          <Box
            id={tab.value}
            key={tab.value}
            sx={mergeSx(
              {
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
                p: 2,
                '&:last-child': {
                  mb: 5,
                },
              },
              tab.sx
            )}>
            <Typography
              sx={{
                color: 'text.primary',
                fontWeight: 600,
              }}>
              {tab.label}
            </Typography>
            <Box
              sx={{
                mt: 2.5,
              }}>
              {tab.content}
            </Box>
          </Box>
        );
      })}
    </Box>
  );
}
