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

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

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

export const OrganismFilterAccordion = ({
  accordionElements,
  clearButtonLabel = 'Clear all',
  handleClear,
  itemsCounter,
  showResultsLabel = `Show ${
    itemsCounter !== undefined ? itemsCounter : ''
  } 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(() => {
    let [sortButtonsArray] = accordionElements.filter(
      (element) => element.sortButtons.length > 0
    );
    if (sortButtonsArray?.sortButtons && sortButtonsArray.sortButtons.length > 0){
      sortButtons = [];
      sortButtonsArray.sortButtons.forEach((element, index) => {
        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 handlePress = (elementId: number) => {
    let [selectedElement] = accordionElements.filter(
      (element) => element.id == elementId
    );
    selectedElement.open = !selectedElement.open;
    setCollapsed(!collapsed);
  };

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

  return (
    <ScrollContainer>
      <AtomCardContainer
        flexDirection="column"
        justifyContent="space-between"
        alignContent="center"
        alignItems="center"
        bgColor={'neutral100'}
        height="100%"
        shadowSize="small"
        managePadding="0px"
        styles={{borderRadius: '0px', minHeight: '100%'}}
        width="100%">
        <TopContainer>
          <HeaderContainer>
            <AtomSubtitle
              align="left"
              color={'neutral700'}
              size="small"
              text="Filters"
              weight="semibold"
              styles={{borderRadius: '0px'}}
              isHTML={false}
            />
            <DismissContainer
              className={'container change'}
              onPress={handleClose && handleClose}
              testID="id"
              key={'dismiss-container'}>
              <Bar style={Styles.barUpper} />
              <Bar style={Styles.hide} />
              <Bar style={Styles.barDown} />
            </DismissContainer>
          </HeaderContainer>
          <FiltersContainer>
            {accordionElements.map((element, index) => {
              return (
                <>
                  <AtomButtonIcon
                    color="custom"
                    customColor="neutral"
                    icon={element.open ? 'arrow_drop_up' : 'arrow_drop_down'}
                    iconAlign="right"
                    onPress={() => handlePress(element.id)}
                    shape="default"
                    size="medium"
                    justifyContent="space-between"
                    styles={{
                      color: theme.neutral700,
                    }}
                    text={element.accordionTitle}
                    typeButtonIcon="ghost"
                    width="100%"
                    disabled={false}
                    testID={'button-' + index}
                  />
                  <CollapsiblePanel
                    key={element.id}
                    testID={'collapsible-' + index}
                    style={{display: !element.open ? 'none' : 'flex'}}>
                    {element.filters.map(filter => {
                      return (
                        <FilterRow
                          testID={'checkbox-' + filter.value}
                          link={filter.link ? true : false}
                          active={filter.active}
                          check={filter.type === 'check'}>
                          {filter.type === 'link' && (
                            <AtomLink
                              url={''}
                              typeIcon={'noIcon'}
                              text={filter.text}
                              openLink={filter.link}
                              styles={{fontWeight: '400', fontSize: 14}}
                              color={'custom'}
                              customColor={'neutral'}
                            />
                          )}
                          {filter.type === 'check' && (
                            <>
                              <AtomCheckbox
                                onChange={(checked: boolean) => {
                                  getCheckValue(
                                    {text: filter.text, value: filter.value},
                                    checked,
                                  );
                                }}
                                checked={
                                  filter.checked ? filter.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, index) => {
                        return (
                          <SortingRow>
                            <AtomBody
                              align="left"
                              color={'neutral600'}
                              size="small"
                              text={buttons.title}
                              weight="regular"
                              styles={{margin: 0}}
                            />
                            <ButtonRowContainer>
                              <MoleculeButtonGroup
                                data={buttons.buttons}
                                directionFlex="row"
                                groupStyle="toggle"
                                width={'40%'}
                              />
                            </ButtonRowContainer>
                          </SortingRow>
                        );
                      })}
                  </CollapsiblePanel>
                </>
              );
            })}
          </FiltersContainer>
        </TopContainer>
        <BottomButtonContainer>
          <AtomButtonGhost
            color="primary"
            customColor="tertiary"
            onPress={handleClear}
            size="medium"
            text={clearButtonLabel}
            width="auto"
            disabled={false}
          />

          <AtomButtonDefault
            color="primary"
            customColor="tertiary"
            onPress={handleShow}
            size="medium"
            text={showResultsLabel}
            width="auto"
            disabled={false}
          />
        </BottomButtonContainer>
      </AtomCardContainer>
    </ScrollContainer>
  );
};
