import { FC, useEffect, useMemo } from 'react';
import { Helmet } from 'react-helmet-async';

import { useQuery } from 'react-query';
import { useNavigate, useSearchParams } from 'react-router-dom';

import {
  IconArticle,
  IconList,
  IconSettings,
  IconUserStar,
  IconUserUp,
} from '@material-hu/icons/tabler';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useAuth } from 'src/contexts/JWTContext';
import { useSocket } from 'src/contexts/SocketContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getGroupDetails } from 'src/services/groups';
import { GroupsStepsType, GroupStep, STEP_DIVIDER_ID } from 'src/types/groups';
import { insertIf } from 'src/utils/arrays';
import {
  getUserGroupRoles,
  memberIsFromGroupCreatorInstance,
  userIsOnManageGroupPage,
} from 'src/utils/groups';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import GroupManagementLayout from '../components/GroupManagementLayout';
import { useGroupHasPendingPostRequests } from '../hooks/useGroupHasPendingPostRequests';
import { useGroupSteps } from '../hooks/useGroupSteps';
import { groupsKeys, invalidateGroupDetails } from '../queries';
import { groupsRoutes } from '../routes';

import { FeaturedMembers } from './components/FeaturedMembers';
import GroupPendingPostsApproval from './components/GroupPendingPostsApproval';
import InvitationManagement from './components/InvitationManagement';
import ManageConfiguration from './components/ManageConfiguration';
import ManageMembers from './components/ManageMembers';

const {
  GENERAL_ASPECTS,
  MANAGE_MEMBERS,
  INVITATION_MANAGEMENT,
  PENDING_POSTS_APPROVAL,
  FEATURED_MEMBERS,
  // GROWTH,
  // INTERACTION,
} = GroupsStepsType;

const ManageGroup: FC = () => {
  const { id: groupId } = useRequiredParams(['id']);
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const configurationType = searchParams.get('type');

  const socket = useSocket();

  const { t } = useTranslation(['post']);

  const HugoThemeProvider = useHuGoTheme();

  const showGeneralError = useGeneralError();

  const { instance } = useAuth();

  const { activeStep, setActiveStep, getActiveConfiguration } = useGroupSteps({
    initialStep: configurationType || GENERAL_ASPECTS,
  });

  const { data: groupDetails, isLoading } = useQuery(
    groupsKeys.detail(groupId),
    () => getGroupDetails(groupId),
    {
      select: res => res?.data,
      onError: err => showGeneralError(err, t('error_loading_group')),
      enabled: !!groupId,
    },
  );

  const { data: hasPendingPostRequests } =
    useGroupHasPendingPostRequests(groupId);

  useEffect(() => {
    const refetchGroupDetails = ({
      groupId: eventGroupId,
    }: {
      groupId: string;
    }) => {
      const isOnUpdatedGroup = userIsOnManageGroupPage(eventGroupId);
      if (isOnUpdatedGroup) {
        invalidateGroupDetails(eventGroupId);
      }
    };

    socket.listenEvent(
      EVENTS_SOCKETS.GROUP_HAS_PENDING_REQUESTS_UPDATED,
      refetchGroupDetails,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.GROUP_HAS_PENDING_REQUESTS_UPDATED,
        refetchGroupDetails,
      );
    };
  }, [socket]);

  const {
    title = '',
    icon,
    hasPendingRequests,
    isMultiCompany,
    members = [],
    instanceId: groupInstanceId,
  } = groupDetails || {};

  const isFromCommunityThatCreatedMultiGroup =
    !isMultiCompany ||
    memberIsFromGroupCreatorInstance(instance?.id, groupInstanceId);

  const steps: GroupStep[] = useMemo(
    () => [
      ...insertIf(isFromCommunityThatCreatedMultiGroup, {
        id: GENERAL_ASPECTS,
        label: t('group:configure'),
        icon: IconSettings,
        Component: ManageConfiguration,
      }),
      {
        id: MANAGE_MEMBERS,
        label: t('group:members'),
        icon: IconList,
        Component: ManageMembers,
      },
      {
        id: INVITATION_MANAGEMENT,
        label: t('group:invitation_management'),
        icon: IconUserUp,
        showBadge: hasPendingRequests,
        Component: InvitationManagement,
      },
      {
        id: PENDING_POSTS_APPROVAL,
        label: t('group:pending_posts_approval', { count: 2 }), // Plural
        icon: IconArticle,
        showBadge: hasPendingPostRequests,
        Component: GroupPendingPostsApproval,
      },
      {
        id: STEP_DIVIDER_ID,
        label: t('group:statistics'),
      },
      // {
      //   id: GROWTH,
      //   label: t('GROWTH'),
      //   icon: IconTrendingUp,
      //   Component: () => null,
      // },
      // {
      //   id: INTERACTION,
      //   label: t('INTERACTION'),
      //   icon: IconThumbUp,
      //   Component: () => null,
      // },
      {
        id: FEATURED_MEMBERS,
        label: t('group:featured_members'),
        icon: IconUserStar,
        Component: FeaturedMembers,
      },
    ],
    [hasPendingRequests, hasPendingPostRequests],
  );

  const activeConfiguration = getActiveConfiguration(steps);

  const { isGroupAdmin } = getUserGroupRoles(members);

  useEffect(() => {
    if (!isLoading && !isGroupAdmin) navigate(groupsRoutes.groups());
  }, [isLoading, members]);

  return (
    <HugoThemeProvider>
      <Helmet>
        <title>{formatTitle(t('group:group_configuration'))}</title>
      </Helmet>
      <GroupManagementLayout
        title={title}
        icon={icon}
        steps={steps}
        activeComponent={
          activeConfiguration ? (
            <activeConfiguration.Component group={groupDetails} />
          ) : null
        }
        onClose={() => navigate(-1)}
        activeStep={activeStep}
        onStepSelect={setActiveStep}
        isLoading={isLoading}
      />
    </HugoThemeProvider>
  );
};

export default ManageGroup;
