import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import classNames from 'clsx';

import types from '../filterSuggester/component/types';

import getFilterComponent from '../helpers/filterComponentMapper';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

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

import styles from './additionalFilters.module.scss';

function AdditionalFiltersComponent({
  keys = [],
  config = {},
  filterConfig = {},
  contentOwners = [],
  handleClick = () => {},
  handleReset = () => {},
  handleApply = () => {},
  ...props
}) {
  const containerRef = useRef(null);
  const [isAnimated, setAnimationState] = useState(false);
  const [heightOfFilter, setHeightOfFilter] = useState(0);
  const [heightOfOverlay, setHeightOfOverlay] = useState(0);
  const setContainerSize = () => {
    const absolutePositionYOfFilter = containerRef.current.getBoundingClientRect().y;
    const heightOfRootContainer = window.innerHeight;

    setHeightOfFilter(Math.floor(window.innerHeight - absolutePositionYOfFilter));
    setHeightOfOverlay(heightOfRootContainer - absolutePositionYOfFilter);
  };

  const userPermissions = useSelector(getUserPermissionsSelector);

  useEffect(() => {
    window.addEventListener('resize', setContainerSize, false);
    setContainerSize();
    return () => {
      window.removeEventListener('resize', setContainerSize);
    };
  });

  useEffect(() => {
    if (props.isOpened) {
      setAnimationState(true);
    }
  }, [props.isOpened]);

  return (
    <>
      <div
        role="button"
        tabIndex={-1}
        onKeyUp={null}
        aria-label="overlay"
        className={classNames(styles.Overlay, {
          [styles.Overlay___active]: props.isOpened && !!heightOfOverlay,
        })}
        onClick={() => props.setOpen(false)}
        style={{
          height: heightOfOverlay,
        }}
      />
      <Stack
        spacing={2}
        style={{ height: heightOfFilter }}
        className={classNames(styles.Filters, {
          [styles.Filters___animated]: isAnimated,
          [styles.Filters___active]: props.isOpened && !!heightOfFilter,
        })}
        ref={containerRef}
      >
        <Stack spacing={4} className={styles.List}>
          {keys
            .filter((key) => {
              const filter = filterConfig[key].filters[0];
              const { permission } = filter;

              return !permission || hasPermission(permission, userPermissions);
            })
            .map((key) => {
              const filter = filterConfig[key].filters[0];
              const Component = getFilterComponent(filter.component);
              const selectedFilter = config[key].filters[0];

              return (
                <Stack spacing={2} key={filter.label} data-id={key}>
                  <Typography variant="subtitle2" color="text.primary" fontWeight={400}>
                    {filter.label}
                  </Typography>
                  <Component
                    size="small"
                    config={filter}
                    selected={selectedFilter.value}
                    selectAction={handleClick(key, false, props.isTrending && props.isOpened)}
                    contentOwners={contentOwners}
                    isCategorized={[types.labels, types.source].some((keySource) => keySource === types[key])}
                    isFilterDirty={props.isFilterDirty}
                  />
                </Stack>
              );
            })}
        </Stack>
        <Stack
          spacing={2}
          direction="row"
          fullWidth
          alignItems="center"
          justifyContent="flex-end"
          className={styles.Footer}
        >
          <Button
            variant="text"
            color="neutral"
            size="small"
            className={styles.FooterButton}
            onClick={() => props.setOpen(!props.isOpened)}
          >
            Cancel
          </Button>
          <Button
            variant="text"
            size="small"
            data-id="resetFilter"
            className={styles.FooterButton}
            onClick={handleReset}
          >
            Reset Filters
          </Button>
          <Button
            data-id="applyFilter"
            size="small"
            className={styles.FooterButton}
            onClick={() => {
              handleApply();
              props.setOpen(false);
            }}
          >
            Apply Filters
          </Button>
        </Stack>
      </Stack>
    </>
  );
}

AdditionalFiltersComponent.propTypes = {
  keys: PropTypes.arrayOf(PropTypes.string),
  config: PropTypes.shape({}),
  filterConfig: PropTypes.shape({}),
  contentOwners: PropTypes.arrayOf(PropTypes.string),
  handleClick: PropTypes.func,
  handleReset: PropTypes.func,
  handleApply: PropTypes.func,
  isOpened: PropTypes.bool.isRequired,
  setOpen: PropTypes.func.isRequired,
  isTrending: PropTypes.bool.isRequired,
  isFilterDirty: PropTypes.bool.isRequired,
};

export default AdditionalFiltersComponent;
