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

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

import Button from '@material-hu/components/design-system/Buttons/Button';

import { useRequiredAuth } 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 'src/pages/dashboard/orgChart/i18n';

import { orgChartRoutes } from 'src/pages/dashboard/orgChart/routes';
import { createChat } from 'src/services/chats';
import { type UserProfile } from 'src/types/user';
import { insertIf } from 'src/utils/arrays';
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 { chatRoutes } from 'src/components/dashboard/chat/routes';

import { useEditProfileDrawer } from '../hooks/useEditProfileDrawer';

type CoverProps = {
  user: UserProfile;
};

const CoverFunctions = ({ user }: CoverProps) => {
  const { instance, user: currentUser } = useRequiredAuth();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation(['profile', 'chat', 'people']);
  const { openEditProfile } = useEditProfileDrawer(user);

  const isSameUser = user.id === currentUser.id;

  // chats
  const { hasAll: canViewChats1 } = usePermissions([
    UserPermissions.VIEW_REGULAR_CHATS,
  ]);
  const { hasAll: canViewChats2 } = usePermissions([
    UserPermissions.VIEW_CHATS_V2,
  ]);
  const openConversation = useOpenConversation();
  const userCanChat = canSendMessage(
    instance.allowCreateChats,
    canViewChats1 || canViewChats2,
    user,
    currentUser,
  );
  const handleChat = async () => {
    try {
      if (canViewChats2) {
        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'));
    }
  };

  // org chart
  const { hasAll: canViewOrgChart } = usePermissions([
    UserPermissions.VIEW_ORGANIZATION_CHARTS,
  ]);
  const handleOrgChart = async () => {
    try {
      logOrgChartView(location.pathname);
      navigate(orgChartRoutes.thread.detail(user.id));
    } catch (err) {
      showGeneralError(err, t('ORGCHART:ERROR_CREATING_ORGCHART'));
    }
  };

  const handleEmail = () => {
    window.open(`mailto:${user.email}`, '_blank');
  };

  const functions = [
    ...insertIf(canViewOrgChart, {
      icon: <IconSitemap />,
      key: 'orgchart',
      onClick: handleOrgChart,
      label: t('people:org_chart'),
    }),
    ...insertIf(userCanChat, {
      icon: <IconMessages />,
      key: 'chat',
      onClick: handleChat,
      label: '',
    }),
    ...insertIf(!!user.email && !isSameUser, {
      icon: <IconMail />,
      key: 'email',
      onClick: handleEmail,
      label: '',
    }),
    ...insertIf(isSameUser, {
      icon: <IconEdit />,
      key: 'edit',
      onClick: () => openEditProfile(),
      label: t('edit_profile'),
    }),
  ];

  return (
    <Stack
      sx={{
        gap: isSameUser ? 1.5 : 1,
        flex: 0,
        flexDirection: isSameUser ? 'column' : 'row',
        alignSelf: 'center',
        textWrap: 'nowrap',
      }}
    >
      {functions.map(func => (
        <Button
          key={func.key}
          variant="secondary"
          onClick={func.onClick}
          size="small"
          {...(isSameUser
            ? { children: func.label, startIcon: func.icon }
            : { children: func.icon, sx: { minWidth: 0 } })}
        />
      ))}
    </Stack>
  );
};

export default CoverFunctions;
