import { useQuery } from 'react-query';

import PxSegmentDropdown from '@material-hu/components/composed-components/peopleExperience/SegmentDropdown';
import type * as PxTypes from '@material-hu/components/composed-components/peopleExperience/types';

import useSurveyId from '../../../../hooks/useSurveyId';
import { pxKeys } from '../../../../queries';
import type { SegmentationGroup as ApiSegmentationGroup } from '../../../../types';
import {
  getManagerSurveyDetail,
  getSegmentDropdownItems,
} from '../../../../services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getNewBaseSegments } from '../constants';

export type SegmentDropdownProps = {
  value: PxTypes.SegmentationGroup;
  onChange: (value: PxTypes.SegmentationGroup) => void;
};

const SegmentDropdown = ({ value, onChange }: SegmentDropdownProps) => {
  const surveyId = useSurveyId();
  const { t } = useLokaliseTranslation('people_experience');

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

  const newBaseSegments = getNewBaseSegments(t);

  const baseSegments: PxTypes.SegmentationGroup[] = [
    {
      ...newBaseSegments.bosses,
      description: t(
        survey?.addBossInBossesFilter
          ? 'SCORE_INCLUDES_BOSS_WITH_TEAM_FILTER'
          : 'SCORE_EXCLUDES_BOSS_WITH_TEAM_FILTER',
      ),
    },
    {
      ...newBaseSegments.directBoss,
      description: t(
        survey?.addBossInDirectBossFilter
          ? 'SCORE_INCLUDES_BOSS_WITH_BOSS_FILTER'
          : 'SCORE_EXCLUDES_BOSS_WITH_BOSS_FILTER',
      ),
    },
  ];

  const { data = [], isLoading } = useQuery<
    ApiSegmentationGroup[],
    unknown,
    PxTypes.SegmentationGroup[]
  >(
    pxKeys.segmentDropdownItems({ surveyId }),
    () => getSegmentDropdownItems({ surveyId, page: 1, limit: 100 }),
    {
      select: resData =>
        [...baseSegments, ...resData] as PxTypes.SegmentationGroup[],
      placeholderData: baseSegments as ApiSegmentationGroup[],
    },
  );

  return (
    <PxSegmentDropdown
      options={data}
      value={value}
      onChange={onChange}
      loading={isLoading}
      instanceId={surveyId}
      surveyId={surveyId}
    />
  );
};

export default SegmentDropdown;
