import React, { FunctionComponent, useEffect, useState } from 'react';
import { AtomBody } from 'native/atoms/Typography/Body';
import { AtomIcon } from 'native/atoms/Icon';
import { StyledAccordion, StyledContainer, StyledHeader, StyledHeaderText, StyledIcon, StyledPanel } from './styles';
import { AtomSubtitle } from 'native/atoms/Typography/Subtitle';
import { CSSObject } from 'styled-components';
import { ScrollView } from 'react-native';

export interface IAccordionProps {
  data: IItemProps[];
  stylesAccordion?: CSSObject;
  stylesPanel?: CSSObject;
  stylesContainer?: CSSObject;
}

interface IItemProps {
  header: string; //Value to write as header
  detail: string; //Value to write as detail
  _id: any; //Value to use as key
}

export const MoleculeAccordion: FunctionComponent<IAccordionProps> = ({ data,stylesAccordion,stylesPanel,stylesContainer }) => {
  const [array, setArray] = useState(data.map((item) => {
    return {
      ...item,
      open: false
    }
  }));

  const handlerPress = (row: any) => {
    let newArray = array.map((item) => {
      return {
        ...item,
        open: item._id === row._id ? !item.open : item.open
      }
    });
    setArray(newArray);
  }

  useEffect(() => {
    setArray(data.map((item) => {
      return {
        ...item,
        open: false
      }
    }))
  }, [data]);

  return (
    <StyledAccordion styles={stylesAccordion}>
      {
        array.map((item: any) => {
          return (
            <StyledPanel key={item._id} testID={`accordion`} styles={stylesPanel}>
              <StyledHeader onPress={() => handlerPress(item)} testID={`item_${item._id}`}>
                <StyledHeaderText>
                  <AtomSubtitle size='xsmall' text={item.header} weight='medium' align='left' />
                </StyledHeaderText>
                <StyledIcon>
                  <AtomIcon name={item.open ? 'remove' : 'add'} size={30} />
                </StyledIcon>
              </StyledHeader>
              {item.open && 
              <ScrollView>
                <StyledContainer styles={{stylesContainer}}>
                <AtomBody size='xlarge' text={item.detail} align='left' weight='regular' />
                </StyledContainer>
              </ScrollView>
              }
            </StyledPanel>
          )
        })
      }
    </StyledAccordion>
  )
};