import { useMemo } from 'react';
import { Box, Button, styled } from '@mui/material';
import { useMemoizedFn } from 'ahooks';
import { joinURL } from 'ufo';
import noop from 'lodash/noop';
import { Icon } from '@iconify/react';

import useFollow from '../use-follow';
import { User, UserCardProps } from '../types';
import { useLocaleContext } from '../../Locale/context';
import { translate } from '../../Locale/util';
import { isSupportFollow } from '../../Util';

type SocialActionsProps = Pick<UserCardProps, 'showSocialActions' | 'session' | 'onFollowClick'> & {
  user: User; // 当前卡片显示的用户，要与 session.user 区分开
};

const translations = {
  zh: {
    chat: '聊天',
    follow: '关注',
    unfollow: '取消关注',
    follow_success: '关注成功',
    unfollow_success: '取消关注成功',
  },
  en: {
    chat: 'Chat',
    follow: 'Follow',
    unfollow: 'Unfollow',
    follow_success: 'Follow success',
    unfollow_success: 'Unfollow success',
  },
};

const getDiscussKitMountPoint = () => {
  const { componentMountPoints = [] } = window.blocklet || {};
  const component = componentMountPoints.find((c: any) => c.name === 'did-comments');
  return component?.mountPoint;
};

// chat: 1. showSocialActions.chat 为 true，2. 必须安装了 discuss kit
function Chat({
  user,
  showSocialActions,
  session,
}: {
  user: SocialActionsProps['user'];
  showSocialActions: SocialActionsProps['showSocialActions'];
  session: SocialActionsProps['session'];
}) {
  const { locale } = useLocaleContext() || { locale: 'en' };
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const isLogin = useMemo(() => {
    return !!session?.user?.did;
  }, [session?.user?.did]);

  // 获取 discuss kit 的挂载点
  const discussKitMountPoint = useMemo(() => getDiscussKitMountPoint(), []);

  const onNavigateToChat = useMemoizedFn(() => {
    if (!isLogin) {
      session?.login(noop, {
        openMode: 'redirect',
        redirect: window.location.href,
      });
      return;
    }
    window.open(joinURL(discussKitMountPoint, `/chat/dm/${user?.did}`), '_blank');
  });

  const showChat = useMemo(() => {
    // boolean：直接使用原值；对象：取对应属性值
    const chatEnabled = typeof showSocialActions === 'boolean' ? !!showSocialActions : showSocialActions?.chat;

    return chatEnabled && !!discussKitMountPoint;
  }, [showSocialActions, discussKitMountPoint]);

  if (!showChat) {
    return null;
  }
  return (
    <ButtonWrapper
      className="user-card__social-actions-chat"
      variant="outlined"
      color="primary"
      size="small"
      onClick={onNavigateToChat}>
      <Icon icon="tabler:message-dots" style={{ marginRight: 4 }} />
      {t('chat')}
    </ButtonWrapper>
  );
}

// follow: 1. showSocialActions.follow 为 true
function Follow({
  user,
  showSocialActions,
  session,
  onFollowClick,
}: {
  user: SocialActionsProps['user'];
  showSocialActions: SocialActionsProps['showSocialActions'];
  session: SocialActionsProps['session'];
  onFollowClick: SocialActionsProps['onFollowClick'];
}) {
  const { locale } = useLocaleContext() || { locale: 'en' };
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const isLogin = useMemo(() => {
    return !!session?.user?.did;
  }, [session?.user?.did]);

  const showFollow = useMemo(() => {
    // boolean：直接使用原值；对象：取对应属性值
    return typeof showSocialActions === 'boolean' ? !!showSocialActions : showSocialActions?.follow;
  }, [showSocialActions]);

  const { followed, followUser, unfollowUser } = useFollow({
    user,
    t,
    isMySelf: false,
    visible: !!showFollow,
  });
  const handleFollowAction = useMemoizedFn(async (e) => {
    if (!isLogin) {
      session?.login(noop, {
        openMode: 'redirect',
        redirect: window.location.href,
      });
      return;
    }
    if (followed) {
      await unfollowUser(user.did);
    } else {
      await followUser(user.did);
    }
    if (onFollowClick && typeof onFollowClick === 'function') {
      onFollowClick(user, e);
    }
  });

  if (!showFollow) {
    return null;
  }

  return (
    <ButtonWrapper
      className="user-card__social-actions-follow"
      variant="outlined"
      color="primary"
      size="small"
      onClick={handleFollowAction}>
      {followed ? t('unfollow') : t('follow')}
    </ButtonWrapper>
  );
}

// 社交操作组件
// 按钮的显示逻辑
// 通用逻辑： 1. user 和 session.user 不能是同一个用户, 2. 相关依赖支持，3. showSocialActions 为 true 或 为 object
// 其他逻辑： 1. 如果 session 中没有用户信息，点击后需要重定向到登录页面
function SocialActions({ showSocialActions, session, user, onFollowClick = undefined }: SocialActionsProps) {
  const isSameUser = useMemo(() => {
    return session?.user?.did === user?.did;
  }, [session?.user?.did, user?.did]);

  const isSupportSocialActions = useMemo(() => {
    return isSupportFollow();
  }, []);

  // 如果 session 中没有用户信息，或者 user 和 session.user 是同一个用户，则不显示社交操作
  if (isSameUser || !isSupportSocialActions || !showSocialActions) {
    return null;
  }

  return (
    <Box className="user-card__social-actions" sx={{ display: 'flex', gap: 1 }}>
      <Chat session={session} user={user} showSocialActions={showSocialActions} />
      <Follow onFollowClick={onFollowClick} session={session} user={user} showSocialActions={showSocialActions} />
    </Box>
  );
}

export default SocialActions;

export const ButtonWrapper = styled(Button)`
  color: ${({ theme }) => theme.palette.text.primary};
  font-weight: 500;
  border-color: ${({ theme }) => theme.palette.grey[300]};
  line-height: 1.5;
`;
