import { theme } from 'data/dataMx';
import React, {useState, useEffect} from 'react';
import { AtomButtonDefault } from 'react/atoms/Buttons/Default';
import { AtomButtonGhost } from 'react/atoms/Buttons/Ghost';
import { AtomButtonIcon } from 'react/atoms/Buttons/Icon';
import { AtomCardContainer } from 'react/atoms/CardContainer';
import { AtomCheckbox } from 'react/atoms/Checkbox';
import { AtomLink } from 'react/atoms/Link';
import { AtomBody } from 'react/atoms/Typography/Body';
import { AtomSubtitle } from 'react/atoms/Typography/Subtitle';
import { MoleculeButtonGroup } from 'react/molecules/ButtonGroup';
import { IAccordionElementsProps, IButtonGroupToggleProps, IItemProps } from './index.interfaces';
import {
  FilterAccordionContent,
  ButtonContainer,
  FilterRow,
  CollapsiblePanel,
  SortingRow,
  DismissContainer,
  TitleContainer,
  Bar,
  FilterAccordionSortButton,
} from './styles';

export interface IFilterAccordionProps {
  accordionElements: IAccordionElementsProps[];
  clearButtonLabel?: string;
  handleClear: () => void;
  showResultsLabel?: string;
  handleShow: () => void;
  handleClose?: () => void;
  handleChange?: (element: Array<any>) => void;
}

let filterObject: any = {};
let sortButtons: IButtonGroupToggleProps[] = [];

export const OrganismFilterAccordion = ({
  accordionElements,
  clearButtonLabel = 'Clear all',
  handleClear,
  showResultsLabel = 'Show Rewards',
  handleShow,
  handleClose,
  handleChange,
}: IFilterAccordionProps) => {
  accordionElements.forEach(element => {
    if (typeof filterObject[element.value] === 'undefined') {
      if (element.value != '') {
        filterObject[element.value] = []
      }
    }
  })
  const [collapsed, setCollapsed] = useState(true);
  const [sortButtonsModified, setSortButtons] = useState(sortButtons);
  const [filterSelection, setFileterSelection] = useState<Array<any>>([]);

  useEffect(() => {
    handleChange && handleChange(filterSelection);
  }, [filterSelection]);

  useEffect(() => {
    let [sortButtonsArray] = accordionElements.filter(
      (element) => element.sortButtons.length > 0
    );
    sortButtons = [];
    sortButtonsArray.sortButtons.forEach(element => {
      let buttons: IItemProps[] = [];
      element.buttons.forEach((button, index) => {
        const newElement: IItemProps = {
          ...button,
          id: index,
          disabled: false,
          color: 'primary',
          type: 'outline',
        };
        buttons.push(newElement);
      });
      sortButtons.push({ title: element.title, buttons });
    });
    setSortButtons(sortButtons);
  }, [accordionElements]);

  const handleClick = (elementId: number) => {
    let [selectedElement] = accordionElements.filter(element => element.id === elementId);
    selectedElement.open = !selectedElement.open;
    setCollapsed(!collapsed);
  }

  const getCheckValue = (selection: any, checked: boolean) => {
    checked ? setFileterSelection([...filterSelection, selection]) : filterSelection.filter((item) => item.value !== selection.value);
  };

  return(
    <>
      <AtomCardContainer
        flexDirection='column'
        justifyContent='space-between'
        alignContent='center'
        alignItems='center'
        bgColor={'neutral100'}
        height='auto'
        shadowSize='small'
        width='100%'
      >
        <FilterAccordionContent>
          <TitleContainer>
            <AtomSubtitle
              align="left"
              color={'neutral700'}
              size="small"
              text="Filters"
              weight="semibold"
              styles={{margin: '24px'}}
            />
            <DismissContainer className={'container change'} onClick={handleClose} data-testid="id" key={'dismiss-container'}>
              <Bar className={'bar1 change'} />
              <Bar className={'bar2 change'} />
              <Bar className={'bar3 change'} />
            </DismissContainer>
          </TitleContainer>
          {
            accordionElements.map((element, index) => {
              return (
              <>
                <AtomButtonIcon
                  color="custom"
                  customColor="neutral"
                  icon={element.open? 'arrow_drop_up' : 'arrow_drop_down'}
                  iconAlign="right"
                  onClick={() => handleClick(element.id)}
                  shape="default"
                  size="medium"
                  styles={{
                    color: `${theme.neutral700} !important`,
                    justifyContent: 'space-between !important',
                    borderBottom: '1px solid #E7EFF2',
                    transition: 'all ease .3s',
                    borderRadius: '0',
                  }}
                  text={element.accordionTitle}
                  type="button"
                  typeButtonIcon="ghost"
                  width="100%"
                  disabled={false}
                  data-testid={'button-' + index}
                />
                <CollapsiblePanel data-testid={'collapsible-' + index} style={{display: !element.open? 'none': 'block'}}>
                  {
                    element.filters.map(filter => {
                      return (
                        <FilterRow
                          data-testid={'checkbox-' + filter.value}
                          link={filter.link ? true : false}
                          active={filter.active}
                          check={filter.type === 'check'}
                        >
                          {
                            filter.type === 'link' && (
                              <AtomLink
                                url={filter.link ? filter.link : ''}
                                typeIcon={'noIcon'}
                                text={filter.text}
                                color={'custom'}
                                customColor={'neutral'}
                                target={'_self'}
                              />
                            )
                          }
                          {
                            filter.type === 'check' && (
                              <>
                                <AtomCheckbox
                                  onChange={(checked: boolean) => getCheckValue(
                                    { text: filter.text, value: filter.value },
                                    checked)
                                  }
                                  checked={false}
                                  value={filter.value} />
                                <AtomBody
                                  align="left"
                                  color={'neutral600'}
                                  size="medium"
                                  styles={{marginLeft: '19px'}}
                                  text={filter.text}
                                  weight="semibold"
                                />
                              </>
                            )
                          }
                        </FilterRow>
                      )
                    })
                  }
                  {
                    (element.sortButtons.length > 0) && sortButtonsModified.map(buttons => {
                      return <SortingRow>
                        <AtomBody
                          align="left"
                          color={'neutral700'}
                          size="medium"
                          styles={{margin: 0}}
                          text={buttons.title}
                          weight="regular"
                        />
                        <FilterAccordionSortButton>
                          <MoleculeButtonGroup
                            data={buttons.buttons}
                            direction="row"
                            groupStyle='toggle'
                          />
                        </FilterAccordionSortButton>
                      </SortingRow>
                    })
                  }
                </CollapsiblePanel>
              </>)
            })
          }
        </FilterAccordionContent>
        <ButtonContainer>
          <AtomButtonGhost
            color="primary"
            customColor="tertiary"
            onClick={handleClear}
            size="medium"
            text={clearButtonLabel}
            type="reset"
            width=""
            disabled={false}
          />
          <AtomButtonDefault
            color="primary"
            customColor="tertiary"
            onClick={handleShow}
            size="medium"
            text={showResultsLabel}
            type="submit"
            width=""
            disabled={false}
          />
        </ButtonContainer>
      </AtomCardContainer>
    </>
  )
};