import { useQuery } from 'react-query';

import { concat } from 'lodash-es';
import ExpandLess from '@material-hu/icons/material/ExpandLess';
import ExpandMore from '@material-hu/icons/material/ExpandMore';
import InfoOutlined from '@material-hu/icons/material/InfoOutlined';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';
import Button from '@material-hu/components/design-system/Buttons/Button';

import { useAuth } from 'src/contexts/JWTContext';
import useSurveyId from '../hooks/useSurveyId';
import { getManagerSurveyDetail, getSegmentationGroups } from '../services';
import {
  BaseSegmentId,
  type SegmentFilter,
  type SegmentId,
  SegmentType,
} from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getBaseSegments } from '../constants';
import { pxKeys } from '../queries';

type BlackedSegment = {
  instanceId: number;
  segments: SegmentId[];
  surveyId?: number;
};

const SEGMENTS_BLACKLIST: BlackedSegment[] = [
  {
    // Prisma
    instanceId: 2754,
    segments: [
      14475,
      14476,
      14474,
      10099,
      10104,
      10105,
      10109,
      10108,
      10084,
      10107,
      63154,
      BaseSegmentId.BOSS,
    ],
  },
  // Quilmes
  {
    instanceId: 9195,
    surveyId: 6106,
    segments: [57679, 57680, 56452, 60778, 27253, 69454],
  },
  // Atlas
  {
    instanceId: 994,
    surveyId: 11254,
    segments: [786, 787, 2811, 3157, 30052],
  },
  {
    instanceId: 2928,
    surveyId: 32840,
    segments: [3343, 3342, 6489, 20416, 9838, 49791, 49792],
  },
  {
    instanceId: 276,
    surveyId: 32840,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 88495, 84469, 38995, 92389, 92390, 92391, 92392, 92212,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31582,
    segments: [
      788, 1067, 823, 1069, 2137, 1070, 1068, 5277, 5222, 12205, 17536, 46400,
      79170, 79174, 79175, 79176, 79177, 79846, 84469, 38995, 92389, 92390,
      92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31583,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31584,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31585,
    segments: [
      788, 1067, 823, 1069, 2137, 1068, 5277, 5222, 12205, 17536, 46400, 79170,
      79174, 79175, 79176, 79177, 79846, 38995, 92389, 92390, 92391, 92206,
      92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31648,
    segments: [
      788, 1067, 1071, 2137, 1070, 5277, 5222, 12205, 17536, 46400, 79173,
      79174, 79175, 79177, 79846, 84088, 84090, 84470, 84469, 38995, 92389,
      92391, 92205, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31649,
    segments: [
      788, 1067, 823, 1071, 2137, 1070, 5277, 5222, 12205, 17536, 46400, 79173,
      79174, 79175, 79177, 79846, 84088, 84090, 84470, 84469, 38995, 92389,
      92391, 92205, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31650,
    segments: [
      788, 1067, 1071, 2137, 1070, 5277, 5222, 12205, 17536, 46400, 79170,
      79173, 79174, 79175, 79176, 79846, 84088, 84089, 84090, 84470, 84469,
      38995, 92389, 92391, 92205, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31651,
    segments: [
      788, 1067, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536, 46400, 79173,
      79174, 79175, 79177, 79846, 84088, 84090, 84470, 84469, 38995, 92389,
      92391, 92205, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31652,
    segments: [
      788, 1067, 1069, 2137, 5277, 5222, 17536, 46400, 79170, 79173, 79174,
      79175, 79846, 84088, 84089, 84090, 84470, 84469, 38995, 92389, 92391,
      92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 31714,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32442,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32443,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32445,
    segments: [
      788, 1067, 1069, 2137, 1068, 5277, 5222, 12205, 17536, 46400, 79170,
      79173, 79174, 79175, 79177, 79846, 84088, 84470, 84469, 38995, 92390,
      92391, 92206, 92212, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32837,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32838,
    segments: [
      788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205, 17536,
      46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84090,
      84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32902,
    segments: [
      817, 788, 1067, 823, 2137, 1070, 1068, 5277, 5222, 12205, 17536, 46400,
      79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088, 84470, 84469,
      38995, 92390, 92391, 92206, 92212, 92392, 88495,
    ],
  },
  {
    instanceId: 276,
    surveyId: 32903,
    segments: [
      817, 788, 1067, 823, 1069, 1071, 2137, 1070, 1068, 5277, 5222, 12205,
      17536, 46400, 79170, 79173, 79174, 79175, 79176, 79177, 79846, 84088,
      84090, 84470, 84469, 38995, 92389, 92390, 92391, 92206, 92212, 92392,
      88495,
    ],
  },
];

const { ActionsMenu, ActionsMenuItem } = PeopleExperience;

type SegmentSelectProps = {
  disabled?: boolean;
  onChange?: any;
  value: any | undefined;
  showLabel?: boolean;
};

const SegmentSelect = ({
  disabled,
  value,
  onChange,
  showLabel = true,
}: SegmentSelectProps) => {
  const { t } = useLokaliseTranslation('people_experience');
  const surveyId = useSurveyId();
  const { instance } = useAuth();

  const baseSegments = getBaseSegments(t);

  const { data: survey } = useQuery(
    pxKeys.surveyDetail(surveyId),
    () => getManagerSurveyDetail(surveyId),
    {
      select: response => response.data,
    },
  );

  const blackedSegment = SEGMENTS_BLACKLIST.find(
    segment =>
      segment.instanceId === instance?.id &&
      (segment.surveyId ? segment.surveyId === surveyId : true),
  );

  const { data, isLoading } = useQuery(
    pxKeys.segmentationGroups(surveyId),
    () => getSegmentationGroups({ surveyId, page: 0, limit: 100 }),
    {
      select: response => {
        if (!response.data) {
          return [];
        }

        const allSegments = concat(
          baseSegments,
          response.data.items.map(segment => ({
            id: segment.id,
            title: segment.name,
            type: SegmentType.SEGMENTATION_GROUPS,
          })),
        );

        return blackedSegment
          ? allSegments.filter(
              segment => !blackedSegment.segments.includes(segment.id),
            )
          : allSegments;
      },
      onSuccess: responseData => {
        onChange(responseData[0]);
      },
    },
  );

  const getEndIcon = (isOpen: boolean) => {
    if (isLoading) {
      return <CircularProgress size={12} />;
    }

    return isOpen ? <ExpandLess /> : <ExpandMore />;
  };

  const handleSelectOption = (option: SegmentFilter) => () => {
    onChange(option);
  };

  const getTooltipText = () => {
    if (value?.id === BaseSegmentId.BOSS) {
      return t(
        survey?.addBossInDirectBossFilter
          ? 'SCORE_INCLUDES_BOSS_WITH_BOSS_FILTER'
          : 'SCORE_EXCLUDES_BOSS_WITH_BOSS_FILTER',
      );
    }

    if (value?.id === BaseSegmentId.TEAM) {
      return t(
        survey?.addBossInBossesFilter
          ? 'SCORE_INCLUDES_BOSS_WITH_TEAM_FILTER'
          : 'SCORE_EXCLUDES_BOSS_WITH_TEAM_FILTER',
      );
    }

    return;
  };

  const tooltipText = getTooltipText();

  return (
    <Stack
      sx={{
        alignItems: 'center',
        gap: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
      }}
    >
      {showLabel && (
        <Typography
          sx={{
            textTransform: 'capitalize',
            fontWeight: 'inherit',
            fontSize: '14px',
            color: 'inherit',
          }}
        >
          {t('SEGMENT')}
        </Typography>
      )}
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
        <ActionsMenu
          renderTrigger={({ ariaProps, handleOpen, open }) => (
            <Button
              {...ariaProps}
              onClick={handleOpen}
              endIcon={getEndIcon(open)}
              variant="outlined"
              size="small"
              disabled={disabled || !data?.length}
            >
              {value?.title ?? '--'}
            </Button>
          )}
          closeOnSelect
        >
          {data?.map(option => (
            <ActionsMenuItem
              key={option.id}
              selected={value?.id === option.id}
              onClick={handleSelectOption(option)}
            >
              {option.title}
            </ActionsMenuItem>
          ))}
        </ActionsMenu>
        {tooltipText && (
          <Tooltip
            title={tooltipText}
            placement="top"
            componentsProps={{
              tooltip: { sx: { maxWidth: '218px', textAlign: 'center' } },
            }}
            arrow
          >
            <IconButton size="small">
              <InfoOutlined fontSize="small" />
            </IconButton>
          </Tooltip>
        )}
      </Stack>
    </Stack>
  );
};

export default SegmentSelect;
