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

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

import { DEFAULT_FILTER_NAMES } from '../filterConfig';
import FilterTimePicker from '../filterTimePicker';
import { Button, ButtonGroup, Menu, MenuItem, Typography } from '@/mui/components';
import { CustomSortAscendOutlined, CustomSortDescendOutlined } from '@/mui/components/CustomIcon';

function FilterItemComponent({
  onSortIconClick = () => null,
  handleClick = () => {},
  filters = [],
  selected = [],
  type = '',
  isReversed = false,
  disabled = false,
}) {
  const buttonRef = useRef(null);
  const { label, value, isSortable: isSortable$ } = selected[0];
  const [isReversedInner, setReverse] = useState(isReversed);
  const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);

  const handleClick$ = (event) => setAnchorEl(event.currentTarget);

  const handleClose = () => setAnchorEl(null);

  useEffect(() => setReverse(isReversed), [isReversed]);

  const isActive = open || filters[0].value !== value;

  return (
    <>
      <ButtonGroup size="small" variant={isActive ? 'contained' : 'outlined'} color={isActive ? 'primary' : 'neutral'}>
        <Button ref={buttonRef} onClick={(event) => (open ? handleClose() : handleClick$(event))} disabled={disabled}>
          {type === DEFAULT_FILTER_NAMES.order ? `Sort: ${label}` : label}
        </Button>
        {isSortable$ && (
          <Button
            disabled={disabled}
            onClick={(event) => {
              onSortIconClick(event);
              setReverse(!isReversedInner);
            }}
            square
            startIcon={isReversedInner ? <CustomSortAscendOutlined /> : <CustomSortDescendOutlined />}
          />
        )}
      </ButtonGroup>
      {open && (
        <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
          {filters.map((filter) => {
            const selectedFilter = selected[0];

            return (
              <MenuItem
                selected={selectedFilter && filter.label === selectedFilter.label}
                key={filter.label}
                data-id={filter.label}
                disableTouchRipple={filter.component === FILTER_COMPONENTS_NAMES.FilterTimePicker}
                disableRipple={filter.component === FILTER_COMPONENTS_NAMES.FilterTimePicker}
                onClick={() => {
                  if (filter.component !== FILTER_COMPONENTS_NAMES.FilterTimePicker) {
                    handleClick(filter);
                    handleClose();
                  }
                }}
              >
                {filter.component === FILTER_COMPONENTS_NAMES.FilterTimePicker ? (
                  <FilterTimePicker
                    config={filter}
                    size="small"
                    selected={selectedFilter.value}
                    selectAction={handleClick}
                    onClose={handleClose}
                  />
                ) : (
                  <Typography variant="body2">{filter.label}</Typography>
                )}
              </MenuItem>
            );
          })}
        </Menu>
      )}
    </>
  );
}

FilterItemComponent.propTypes = {
  isReversed: PropTypes.bool,
  onSortIconClick: PropTypes.func,
  handleClick: PropTypes.func,
  filters: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.shape({})]),
    }),
  ),
  selected: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string.isRequired,
      value: PropTypes.string.isRequired,
      isSortable: PropTypes.bool,
    }),
  ),
  type: PropTypes.string,
  disabled: PropTypes.bool,
};

export default FilterItemComponent;
