import React, { useEffect, useMemo, useState } from 'react';
import { FlatList, Image, StyleSheet, TouchableOpacity, View } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { Fonts } from '../../assets/fonts';
import AppLoader from '../../components/AppLoader';
import AppText from '../../components/AppText';
import MainContainer from '../../components/MainContainer';
import { AppHeight, AppMargin, AppPadding } from '../../constants/commonStyle';
import { NavigationKeys } from '../../constants/navigationKeys';
import { t } from '../../i18n';
import { GET_RECENT } from '../../services/API/endpoints';
import { APIMethods } from '../../services/API/methods';
import { AppDispatch } from '../../store';
import { setData } from '../../store/reducers/homeScreen.slice';
import { Theme } from '../../theme/AppColors';
import { useTheme } from '../../theme/ThemeProvider';

declare function alert(message: string): void;

interface HomeScreenProps {
	navigation: any
}

const HomeScreen = (props: HomeScreenProps) => {

	const { Colors, isDarkMode } = useTheme();
	const styles = useMemo(() => createStyles(Colors), [Colors]);

	const dispatch: AppDispatch = useDispatch();

	const listData = useSelector((state: any) => state.homeScreen);
	const [isLoading, setIsLoading] = useState<boolean>(true);
	const [currentPage, setCurrentPage] = useState<number>(1);

	useEffect(() => {
		_getLatestProducts()
		const unsubscribe = props.navigation.addListener('focus', () => {
		});

		return () => {
			unsubscribe()
		};
	}, [dispatch, props.navigation]);

	const _getLatestProducts = async () => {
		try {
			setIsLoading(true);
			// endpoint: any, params: any = '', customHeaders = []
			let params = { page: currentPage }
			const response: any = await APIMethods.get(GET_RECENT, params, []);
			const data = response?.data;
			if (currentPage == 1) {
				setCurrentPage(previousState => previousState + 1);
				dispatch(setData(data));
			} else {
				const updatedData = [...listData.items, ...data];
				dispatch(setData(updatedData));
			}
		} catch (err) {
			console.error(err);
		} finally {
			setIsLoading(false);	// Hide loading indicator regardless of success or error!
		}
	};

	const _goToDetails = (item: any) => {
		props.navigation.navigate(NavigationKeys.DetailScreen, { animeItem: item })
	};

	const _renderItem = ({ item, index }: any) => {
		const title = item.title_english || item.title;
		return (
			<TouchableOpacity key={index} onPress={() => _goToDetails(item)}
				style={styles.renderContainer}>
				<AppText fontFamily={Fonts.MEDIUM} label={title} />
				<Image
					style={{ marginTop: AppMargin._30, height: AppHeight._350, resizeMode: 'cover' }}
					source={{ uri: item?.images?.jpg?.large_image_url }}
				/>
			</TouchableOpacity>
		)
	}

	const loadMoreData = async () => {
		setCurrentPage(previousState => previousState + 1);
		await _getLatestProducts()
	}

	return (
		<MainContainer>
			{isLoading && <AppLoader isLoading={isLoading} />}
			<View style={{ marginHorizontal: 20, flex: 1 }}>
				<AppText textColor={Colors.primary} fontFamily={Fonts.BOLD} title={`${t('title')} ${listData.userName}`} />

				<View style={{ flex: 1 }}>
					{listData.items &&
						listData.items.length > 0 &&
						<FlatList
							style={{ flex: 1 }}
							data={listData?.items}
							showsVerticalScrollIndicator={false}
							contentContainerStyle={styles.flatListContainer}
							keyExtractor={(item, index) => index.toString()}
							ItemSeparatorComponent={() => <View style={{ marginVertical: AppMargin._10 }} />}
							renderItem={_renderItem}
							initialNumToRender={10}
							onEndReached={loadMoreData}
							onEndReachedThreshold={0.5}
						/>}
				</View>

			</View>
		</MainContainer>
	);
};

const createStyles = (Colors: Theme) => {
	return StyleSheet.create({
		renderContainer: {
			padding: 20,
			borderWidth: 1,
			borderColor: Colors.primaryTransparent
		},
		flatListContainer: {
			paddingBottom: AppMargin._75,
			paddingTop: AppPadding._20,
		},
	});
};

export default HomeScreen;