import { useNavigate, useLocation } from 'react-router-dom';

import { IconMessages, IconSitemap } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';

import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import usePermissions from 'src/hooks/usePermissions';
import { useOpenConversation } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { orgChartRoutes } from 'src/pages/dashboard/orgChart/routes';
import { createChat } from 'src/services/chats';
import { User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { logOrgChartView } from 'src/utils/orgChart';
import { UserPermissions } from 'src/utils/permissions';
import { canSendMessage } from 'src/utils/profile';
import { useTranslation } from 'src/components/dashboard/chat/i18n';

import { chatRoutes } from 'src/components/dashboard/chat/routes';

const { VIEW_REGULAR_CHATS, VIEW_ORGANIZATION_CHARTS, VIEW_CHATS_V2 } =
  UserPermissions;

export type UserActionsProps = {
  user: User;
};

const UserActions = (props: UserActionsProps) => {
  const { user } = props;

  const location = useLocation();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();
  const { t } = useTranslation();
  const { t: tLokalise } = useLokaliseTranslation('people');
  const { user: loggedUser, instance } = useAuth();

  const { hasAll: canViewChats } = usePermissions([VIEW_REGULAR_CHATS]);
  const { hasAll: canViewConversations } = usePermissions([VIEW_CHATS_V2]);
  const { hasAll: canViewOrgChart } = usePermissions([
    VIEW_ORGANIZATION_CHARTS,
  ]);

  const openConversation = useOpenConversation();

  const handleSendMessage = async (
    event: React.MouseEvent<HTMLButtonElement>,
  ) => {
    event.stopPropagation();
    try {
      if (canViewConversations) {
        const users = [user.id.toString()];
        openConversation.mutate({ users });
      } else {
        const { data: thread } = await createChat(user.id);
        const chatId = thread.chat.id;
        const state = thread;
        navigate(chatRoutes.thread.detail(chatId), { state });
      }
    } catch (err) {
      showGeneralError(err, t('CHAT:ERROR_CREATING_CHAT'));
    }
  };

  const handleViewOrgChart = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    logOrgChartView(location.pathname);
    navigate(orgChartRoutes.thread.detail(user.id));
  };

  const shouldViewChats = canViewChats || canViewConversations;

  const userCanSendMessage = canSendMessage(
    instance?.allowCreateChats ?? false,
    shouldViewChats,
    user,
    loggedUser!,
  );

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        justifyContent:
          userCanSendMessage && canViewOrgChart ? 'space-between' : 'center',
        width: '100%',
      }}
    >
      {userCanSendMessage && (
        <HuTooltip description={tLokalise('SEND_MESSAGE')}>
          <IconButton onClick={event => handleSendMessage(event)}>
            <IconMessages />
          </IconButton>
        </HuTooltip>
      )}
      {canViewOrgChart && (
        <HuTooltip description={tLokalise('VIEW_ORG_CHART')}>
          <IconButton onClick={event => handleViewOrgChart(event)}>
            <IconSitemap />
          </IconButton>
        </HuTooltip>
      )}
    </Stack>
  );
};

export default UserActions;
