import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import { useOutletContext } from 'react-router-dom';

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

import PxHeatmap from '@material-hu/components/composed-components/peopleExperience/Heatmap';
import * as PxTypes from '@material-hu/components/composed-components/peopleExperience/types';

import { logEvent } from 'src/config/amplitude';
import { pxKeys } from '../../../../queries';
import { getHeatmapScores, getHeatmapTotals } from '../../../../services';
import { EventName } from 'src/types/amplitude';
import {
  type HeatmapReqParams,
  type HeatmapScoresReqParams,
  SegmentType,
} from '../../../../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { SegmentDropdown } from '../../../../SurveyResults/components/Heatmap/components';
import { getInitialHeatmapFilters } from '../../../../SurveyResults/components/Heatmap/constants';
import { type ManagerResultsOutletContext } from '../../types';

const isBossSegment = (segment: PxTypes.SegmentationGroup) =>
  typeof segment.id !== 'number';

const HeatmapResults = () => {
  const { t } = useLokaliseTranslation('people_experience');
  const { filters, survey } = useOutletContext<ManagerResultsOutletContext>();

  const surveyId = survey.id;
  const logEventOnce = useMemo(() => once(logEvent), []);

  const [heatmapFilters, setHeatmapFilters] = useState<PxTypes.HeatmapFilters>(
    getInitialHeatmapFilters(t),
  );

  const { dataSource, segment, parentId } = heatmapFilters;

  const getDimensionParam = () => {
    if (isBossSegment(segment)) {
      return segment.id;
    }

    if (segment.type === PxTypes.SegmentationGroupType.AGE) {
      return SegmentType.AGE;
    }

    if (segment.type === PxTypes.SegmentationGroupType.SENIORITY) {
      return SegmentType.SENIORITY;
    }

    return SegmentType.SEGMENTATION_GROUPS;
  };

  const getParentId = () => {
    if (isBossSegment(segment)) {
      return parentId;
    }

    if (
      segment?.type &&
      [
        PxTypes.SegmentationGroupType.AGE,
        PxTypes.SegmentationGroupType.SENIORITY,
      ].includes(segment.type)
    ) {
      return null;
    }

    return segment.id;
  };

  const parentIdParam = getParentId();

  const baseReqParams: HeatmapReqParams = {
    surveyId,
    parentId: parentIdParam ?? undefined,
    dimension: getDimensionParam(),
    ...filters,
  };

  const { data: totalsData, isLoading: isTotalLoading } = useQuery({
    queryKey: pxKeys.heatmapTotals(baseReqParams),
    queryFn: () => getHeatmapTotals(baseReqParams),
    select: resData => resData.data,
  });

  const scoreReqParams: HeatmapScoresReqParams = {
    ...baseReqParams,
    dataSource,
  };

  const { data: scoresData, isLoading: isScoreLoading } = useQuery({
    queryKey: pxKeys.heatmapScores(scoreReqParams),
    queryFn: () => getHeatmapScores(scoreReqParams),
    select: resData => resData.data,
  });

  const isDataLoading = isTotalLoading || isScoreLoading;

  useEffect(() => {
    if (surveyId) {
      logEventOnce(EventName.HEATMAP_VIEWED, { surveyID: surveyId });
    }
  }, [logEventOnce, surveyId]);

  return (
    <Stack
      sx={{
        flex: 1,
        minHeight: 0,
        overflow: 'hidden',
        p: 3,
      }}
    >
      <PxHeatmap
        totalsData={totalsData}
        scoresData={scoresData}
        loading={isDataLoading}
        onFiltersChange={nextFilters => setHeatmapFilters(nextFilters)}
        SegmentSelect={SegmentDropdown}
        defaultFilters={heatmapFilters}
      />
    </Stack>
  );
};

export default HeatmapResults;
