import { type FC, useMemo } from 'react';
import {
  FormProvider,
  useForm,
  useFormContext,
  useWatch,
} from 'react-hook-form';
import { List, type RowComponentProps } from 'react-window';

import Stack from '@material-hu/mui/Stack';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuFormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import HuFormSearch from '@material-hu/components/design-system/Inputs/Search/form';
import HuTitle from '@material-hu/components/design-system/Title';

import { type Segmentation } from 'src/types/segmentation';
import { type SegmentationItem } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import VacationsFilterAccordion from './GeneralFilterAccordion';

const ROW_HEIGHT = 40;

const ItemRow = ({
  filteredItems,
  index,
  style,
}: RowComponentProps<{
  filteredItems: SegmentationItem[];
}>) => {
  return (
    <Stack style={style}>
      <HuFormCheckbox
        name={`segmentation.selected_${filteredItems[index].id}`}
        checkBoxProps={{
          label: filteredItems[index].name,
        }}
      />
    </Stack>
  );
};

type GeneralFilterAccordionProps = {
  group: Segmentation;
};
// groups can have lots of items so we need to optimize
const SegmentationFilterAccordion: FC<GeneralFilterAccordionProps> = ({
  group,
}) => {
  const { t } = useLokaliseTranslation('time_off');
  const formContext = useFormContext();
  const form = useForm({
    defaultValues: {
      search: '',
    },
  });

  const search = useWatch({
    control: form.control,
    name: 'search',
  });

  const filteredItems = useMemo(
    () =>
      search
        ? group.items.filter(item =>
            item.name.toLowerCase().includes(search.toLowerCase()),
          )
        : group.items,
    [group, search],
  );

  const hasSomeSelected = useMemo(
    () =>
      Object.entries(formContext.getValues('segmentation')).some(
        ([key, value]) =>
          value && group.items.some(i => key === `selected_${i.id}`),
      ),
    [],
  );

  return (
    <FormProvider {...form}>
      <VacationsFilterAccordion
        label={group.name}
        accordionProps={{
          defaultExpanded: hasSomeSelected,
        }}
      >
        <Stack sx={{ gap: 1 }}>
          {group.items.length > 7 && <HuFormSearch name="search" />}
          <FormProvider {...formContext}>
            <HuCardContainer sx={{ width: '100%' }}>
              {filteredItems.length === 0 && (
                <HuTitle
                  variant="S"
                  title={t('no_results')}
                  fontWeight="fontWeightRegular"
                />
              )}
              <List
                rowComponent={ItemRow}
                rowProps={{
                  filteredItems,
                }}
                rowHeight={ROW_HEIGHT}
                rowCount={filteredItems.length}
                overscanCount={5}
                style={{
                  height: Math.min(400, ROW_HEIGHT * filteredItems.length),
                }}
              />
            </HuCardContainer>
          </FormProvider>
        </Stack>
      </VacationsFilterAccordion>
    </FormProvider>
  );
};

export default SegmentationFilterAccordion;
