import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { Stack, Typography } from '@mui/material';

import { SEGMENTS_BLACKLIST } from './constants';
import { PxDropdownList, type PxTypes } from '.';

export type SegmentDropdownProps = {
  value: PxTypes.SegmentationGroup;
  onChange: (value: PxTypes.SegmentationGroup) => void;
  instanceId: number;
  surveyId: number;
  options: PxTypes.SegmentationGroup[];
  loading?: boolean;
};

const SegmentDropdown = ({
  value,
  onChange,
  instanceId,
  surveyId,
  options,
  loading = false,
}: SegmentDropdownProps) => {
  const { t } = useTranslation('material_hu_only');

  const blackedSegmentGroup = useMemo(
    () =>
      SEGMENTS_BLACKLIST.find(
        segment =>
          segment.instanceId === instanceId &&
          (segment.surveyId ? segment.surveyId === surveyId : true),
      ),
    [instanceId, surveyId],
  );

  const isSegmentBlackListed = (segment: PxTypes.SegmentationGroup) => {
    return blackedSegmentGroup
      ? blackedSegmentGroup.segments.includes(segment.id)
      : true;
  };

  return (
    <Stack
      sx={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 1,
        flexWrap: 'wrap',
      }}
    >
      <Typography fontWeight="fontWeightMedium">
        {t('people_experience.segment')}
      </Typography>
      <PxDropdownList
        options={options.filter(isSegmentBlackListed)}
        value={value}
        onChange={onChange}
        loading={loading}
      />
    </Stack>
  );
};

export default SegmentDropdown;
