import { useEffect, useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';

import { compact } from 'lodash-es';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';

import SurveyResultsLayout from '@material-hu/components/composed-components/peopleExperience/surveyResults/SurveyResultsLayout';
import { SegmentationGroupType } from '@material-hu/components/composed-components/peopleExperience/types';
import SidebarContentLayout from '@material-hu/components/composed-components/SidebarContentLayout';
import TaskFocusLayout from '@material-hu/components/composed-components/TaskFocusLayout';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useLocalStorage from 'src/hooks/useLocalStorage';
import useSurveyId from '../../hooks/useSurveyId';
import { type SegmentationFilterParams } from '../../types';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getStorageKey } from 'src/utils/storage';

import useManagerSurveyDetail from '../../hooks/useSurveyDetail';
import { pxLinks, pxRoutes } from '../../routes';

import useFilterDrawer from './hooks/useFilterDrawer';
import { type SerializedFilterState } from './hooks/useFilterState/types';
import { getInitialFilters } from './hooks/useFilterState/utils';
import { getPillTypeFromStatus } from './utils';

const ManagerResults = () => {
  const HuGoThemeProvider = useHuGoTheme();
  const { t } = useLokaliseTranslation('people_experience');
  const surveyId = useSurveyId();
  const navigate = useNavigate();
  const location = useLocation();

  const { data: survey, isLoading: isLoadingSurvey } = useManagerSurveyDetail({
    surveyId,
    t,
  });

  const initialFilters = getInitialFilters();

  const [appliedFilters, setAppliedFilters] =
    useLocalStorage<SerializedFilterState>(
      getStorageKey('@px', 'surveyFilters', { surveyId }),
      initialFilters,
      { storage: 'sessionStorage' },
    );

  const { drawer: filterDrawer, filters } = useFilterDrawer({
    surveyId: surveyId!,
    appliedFilters,
    onApply: () => setAppliedFilters(filters.utils.serialize()),
    onClear: () => {
      filters.handlers.resetAll();
      setAppliedFilters(initialFilters);
    },
  });

  const sidebarOptions = {
    participation: {
      label: t('participation.title'),
      to: pxLinks.managerResultsParticipation(surveyId!),
    },
    nps: survey?.hasNPSQuestion
      ? {
          label: t('e_nps.title'),
          to: pxLinks.managerResultsNps(surveyId!),
        }
      : null,
    list: {
      label: t('dimensions_and_questions'),
      to: pxLinks.managerResultsList(surveyId!),
    },
    heatmap: {
      label: t('heat_map'),
      to: pxLinks.managerResultsHeatmap(surveyId!),
    },
  };

  const resolvePathExtras = () => {
    const currentOption = Object.values(sidebarOptions).find(
      option => option?.to === location.pathname,
    );
    return {
      title: currentOption?.label ?? '',
      disableFilters: location.pathname === sidebarOptions.participation.to,
    };
  };

  const { title: resultTitle, disableFilters } = resolvePathExtras();

  const segmentationFilters: SegmentationFilterParams = useMemo(() => {
    const { isGroupOfType } = filters.derived;

    const segmentationItem: string[] = [];
    const ageId: string[] = [];
    const seniorityId: string[] = [];

    Object.entries(appliedFilters.selectedItems).forEach(
      ([groupId, itemIds]) => {
        const numGroupId = Number(groupId);
        itemIds.forEach(itemId => {
          if (isGroupOfType(numGroupId, SegmentationGroupType.AGE)) {
            ageId.push(String(itemId));
          } else if (
            isGroupOfType(numGroupId, SegmentationGroupType.SENIORITY)
          ) {
            seniorityId.push(String(itemId));
          } else {
            segmentationItem.push(String(itemId));
          }
        });
      },
    );

    const excludeSegmentationItem: string[] = [];
    const excludeAgeId: string[] = [];
    const excludeSeniorityId: string[] = [];

    Object.entries(appliedFilters.deselectedItems).forEach(
      ([groupId, itemIds]) => {
        const numGroupId = Number(groupId);
        itemIds.forEach(itemId => {
          if (isGroupOfType(numGroupId, SegmentationGroupType.AGE)) {
            excludeAgeId.push(String(itemId));
          } else if (
            isGroupOfType(numGroupId, SegmentationGroupType.SENIORITY)
          ) {
            excludeSeniorityId.push(String(itemId));
          } else {
            excludeSegmentationItem.push(String(itemId));
          }
        });
      },
    );

    return {
      segmentationGroup: appliedFilters.selectAllGroups.map(String),
      segmentationItem,
      excludeSegmentationItem,
      ageId,
      excludeAgeId,
      seniorityId,
      excludeSeniorityId,
    };
  }, [appliedFilters, filters.derived]);

  const handleClose = () => {
    navigate(pxRoutes.managerSurveysBase());
  };

  useEffect(() => {
    return () => {
      filters.handlers.resetAll();
      setAppliedFilters(initialFilters);
    };
  }, []);

  return (
    <HuGoThemeProvider>
      <Helmet>
        <title>{formatTitle(t('MANAGER_RESULTS'))}</title>
      </Helmet>
      <TaskFocusLayout
        slotProps={{
          root: {
            sx: {
              height: '100vh',
            },
          },
          header: {
            title: survey?.name ?? '',
            onBack: handleClose,
            onClose: handleClose,
            pillLabel: survey?.status.label,
            slotProps: {
              pill: {
                type: survey
                  ? getPillTypeFromStatus(survey.status.value)
                  : undefined,
              },
              root: {
                sx: {
                  borderBottom: theme =>
                    `1px solid ${theme.palette.new.border.neutral.default}`,
                },
              },
            },
          },
        }}
      >
        <SidebarContentLayout
          slotProps={{
            root: {
              sx: {
                flexShrink: 1,
                minHeight: 0,
              },
            },
            sidebar: {
              buttonLabel: t('collapse'),
              options: compact(Object.values(sidebarOptions)),
            },
          }}
        >
          <SurveyResultsLayout
            title={resultTitle}
            filtersLabel={t('filters')}
            filtersCount={filters.derived.selectedGroupsCount}
            onClickFilters={() => {
              filterDrawer.showDrawer({});
            }}
            clearFiltersLabel={t('clear_filters')}
            onClearFilters={() => {
              filters.handlers.resetAll();
              setAppliedFilters(initialFilters);
            }}
            loading={isLoadingSurvey}
            disableFilters={disableFilters}
          >
            {isLoadingSurvey && !survey && (
              <Stack sx={{ gap: 3, p: 3, height: '100%' }}>
                <Stack sx={{ flexDirection: 'row', gap: 3 }}>
                  <Skeleton
                    width={322}
                    height={165}
                    variant="rounded"
                  />
                  <Skeleton
                    width={322}
                    height={165}
                    variant="rounded"
                  />
                </Stack>
                <Skeleton
                  width="100%"
                  height="100%"
                  variant="rounded"
                  sx={{ flex: '1 0 0' }}
                />
              </Stack>
            )}
            {survey && (
              <Outlet context={{ filters: segmentationFilters, survey }} />
            )}
            {filterDrawer.drawer}
          </SurveyResultsLayout>
        </SidebarContentLayout>
      </TaskFocusLayout>
    </HuGoThemeProvider>
  );
};

export default ManagerResults;
