import {
  LayoutAnimation,
  Platform,
  StyleSheet,
  Text,
  UIManager,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
} from 'react-native';
import React, { useContext, useEffect, useState } from 'react';
import { List } from 'react-native-paper';
import EntypoIcon from 'react-native-vector-icons/Entypo';
import { horizontalScale, moderateScale, verticalScale } from '../../constants/metrics';
import NewscoutLogo from '../../components/atoms/Logo/NewscoutLogo';
import fonts from '../../constants/fonts';
import CircularPrimaryBackButton from '../../components/atoms/Buttons/CircularPrimaryBackButton';
import colors from '../../constants/colors';
import NewscoutHomeHeader from '../../components/molecules/Header/NewscoutHomeHeader';
import { navigateToListViewPage, useConstructor } from '../../constants/functions';
import { getArticlesByCategory, getCategories } from '../../api/data';
import { BASE_URL } from '../../api/urls';
import CustomSwitch from '../../components/atoms/Switch/CustomSwitch';
import { ThemeContext } from '../../context/theme.context';


const SidebarPage = ({ navigation, route }) => {

  const [data, setData] = React.useState([])

  const [expandedId, setExpandedId] = React.useState('');

  const handleAccordionPress = accordionId => {
    setExpandedId(accordionId === expandedId ? '' : accordionId);
  };

  const fetchMenus = () => {
    getCategories().then(res => {
      setData(res.data.body.results)
    }).catch(err => console.error(err))
      .finally(() => console.log("Fetch Sidebar Categories Executed"))
  }

  useConstructor(() => {
    fetchMenus()
  })

  const styles = StyleSheet.create({
    sideBarContainer: {
      paddingHorizontal: horizontalScale(24),
      backgroundColor: colors().dominant,
      height: '100%'
    },
    logo: {
      width: horizontalScale(84),
      height: verticalScale(84),
    },
    logoContainer: {
      justifyContent: 'center',
      alignItems: 'center',
    },
    buttonContainer: { paddingVertical: verticalScale(8) },
    accordionContainer: {
      paddingVertical: verticalScale(16),
      gap: moderateScale(8),
      height: '100%'

    },
    accordionStyle: {
      backgroundColor: colors().dominant,
      borderRadius: moderateScale(8),
      borderWidth: moderateScale(2),
      borderColor: colors().grayShade_400,
      maxHeight: verticalScale(64),
    },
    accordionTextStyle: { fontFamily: fonts.type.medium, color: colors().recessive },
    accordionItemStyle: {
      backgroundColor: colors().dominant
    },
    accordionItemTextStyle: {
      color: colors().recessive,
      fontFamily: fonts.type.regular
    },

  });

  const theme = useContext(ThemeContext)
  const [isDarkMode, setDarkMode] = useState(theme.state.theme === "light" ? false : true)

  useEffect(() => {
    if (theme.state.theme === 'light') {
        setDarkMode(false)
    } else {
      setDarkMode(true)
    }
  },[theme.state.theme])

  return (
    <View >
      <ScrollView style={{ backgroundColor: colors().dominant, minHeight: '100%' }} showsVerticalScrollIndicator={false}>
        <NewscoutHomeHeader backButtonShown={true} onBackClick={() => navigation.toggleDrawer()} />
        <View style={styles.sideBarContainer}>

          {/* <View style={styles.buttonContainer}>
            <CircularPrimaryBackButton onPress={() => navigation.toggleDrawer()} />
          </View> */}


          <View style={styles.accordionContainer}>
            <List.AccordionGroup
              expandedId={expandedId}
              onAccordionPress={handleAccordionPress}>
              {data.map(item => {
                let acc_check = item.heading.name.toLowerCase();
                return (
                  <List.Accordion
                    key={acc_check}
                    id={acc_check}
                    theme={{colors:{background: colors().dominant}}}
                    style={[
                      styles.accordionStyle,
                      acc_check === expandedId && {
                        backgroundColor: colors().secondaryColor,
                        borderColor: colors().secondaryColor,
                      },
                    ]}
                    titleStyle={[
                      ,
                      styles.accordionTextStyle,
                      acc_check === expandedId && {
                        color: colors().white,
                        fontFamily: fonts.type.semibold,
                      },
                    ]}
                    onPress={() => {}}
                    left={() => (
                      <View style={{ paddingLeft: 16 }}>
                        <Image
                          source={{ uri: BASE_URL + "/" + item.heading.icon }}
                          style={{
                            height: 24,
                            width: 24,
                            tintColor:
                              acc_check === expandedId ?
                                colors().white :
                                colors().primaryColor
                          }}
                        />
                      </View>
                    )}
                    right={() => (
                      <EntypoIcon
                        name={
                          acc_check === expandedId ? 'chevron-up' : 'chevron-down'
                        }
                        size={moderateScale(16)}
                        color={
                          acc_check === expandedId ? colors().white : colors().recessive
                        }
                      />
                    )}
                    title={item.heading.name}>
                    {item.heading.submenu.map(subTitle => (
                      <TouchableOpacity
                        onPress={
                          () => {
                            navigation.toggleDrawer()
                            navigateToListViewPage(navigation, "category", subTitle.name)

                          }}
                      >
                        <List.Item
                          key={`${item.title}_${subTitle.name}`}
                          // key={`${item.title}_${item.subTitles.indexOf(subTitle)}`}
                          //key={`Sidebar_${item.title}_${item.subTitles.indexOf(subTitle)}`}
                          style={styles.accordionItemStyle}
                          titleStyle={styles.accordionItemTextStyle}
                          title={subTitle.name}
                        />
                      </TouchableOpacity>
                    ))}
                  </List.Accordion>
                );
              })}
            </List.AccordionGroup>
            <List.Item
              style={styles.accordionStyle}
              titleStyle={styles.accordionTextStyle}
              title="Switch Theme"
              left={props => <List.Icon {...props} icon="theme-light-dark" color={colors().primaryColor} />}
              right={props => <CustomSwitch
                onSelectSwitch={() => {
                  setDarkMode(!isDarkMode)
                  if (isDarkMode !== false){
                    theme.dispatch({ type: "LIGHTMODE" });
                    setDarkMode(false)
                  }
                  else{
                    theme.dispatch({ type: "DARKMODE" });
                    setDarkMode(true)
                  }
                   
                }}
                

            value={isDarkMode}
              />}
            />
            <List.Item
              style={styles.accordionStyle}
              titleStyle={styles.accordionTextStyle}
              title="Reader Mode"
              left={props => <List.Icon {...props} icon="book" color={colors().primaryColor} />}
              
            />

          </View>
        </View>
      </ScrollView>
    </View>
  );
};

export default SidebarPage;

