import { View, Text, ScrollView, FlatList, Pressable, ActivityIndicator, Image, Modal, Alert } from 'react-native';
import NormalButton from '../global/normal_button';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { useColorScheme } from 'nativewind';
import RecentlyBookedScrollView from '../global/recentlyBookedScrollView';
import {
    BellIconSvg,
    HomeIconSvg,
    MyBookingIconSvg,
    MyVehicleIconSvg,
    QrCodeIconSvg,
    VipCodeIconSvg
} from '../global/SVG';
import { AuthContext } from '../../context/AuthProvider';
import { useContext, useEffect, useState } from 'react';
import { authenticationService } from '../../service/authService';
import { chargeStationService } from '../../service/chargeStationService';
import { walletService } from '../../service/walletService';
import useUserInfoStore from '../../providers/userinfo_store';
interface HomePageProps {}

const HomePage: React.FC<HomePageProps> = () => {
    const now = new Date();
    const { user } = useContext(AuthContext);
    const { userID, currentPrice, setUserID, setCurrentPrice } = useUserInfoStore();
    const { colorScheme, toggleColorScheme } = useColorScheme();
    useEffect(() => {
        // Set to light mode on component mount
        if (colorScheme === 'dark') {
            toggleColorScheme();
        }
    }, []);
    // Effect for fetching user ID
    useEffect(() => {
        const fetchID = async () => {
            try {
                const response = await authenticationService.getUserInfo();
                if (response) {
                    setUserID(response.data.id);
                } else {
                    console.log('fail to set user ID');
                }
            } catch (error) {
                console.log(error);
            }
        };
        fetchID();
    }, []);

    useEffect(() => {
        const fetchCurrentPrice = async () => {
            try {
                const response = await chargeStationService.getCurrentPrice();
                if (response) {
                    // console.log('main page fetch current price', response);
                    setCurrentPrice(response);
                }
            } catch (error) {
                console.log('main page fetch current price error', error);
            }
        };
        fetchCurrentPrice();
    }, []);

    // Add new state for modal visibility
    const [showOnboarding, setShowOnboarding] = useState(true);
    const [mainPromotion, setMainPromotion] = useState([]);
    const [mainPromotionImage, setMainPromotionImage] = useState('');

    useEffect(() => {
        const fetchMainPromotion = async () => {
            try {
                const response = await chargeStationService.getAdvertise();
                if (response) {
                    const mainPromo = response.filter((item: any) => item.is_main)[0];
                    setMainPromotion(mainPromo);

                    if (mainPromo) {
                        const mainPromoImage = await chargeStationService.getProcessedImageUrl(mainPromo.image_url);
                        if (mainPromoImage) {
                            setMainPromotionImage(mainPromoImage);
                        }
                    }
                }
            } catch (error) {
                console.log('Error fetching promotion:', error);
            }
        };
        fetchMainPromotion();
    }, []);

    return (
        <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
            {/* Add Modal component */}
            {mainPromotionImage && (
                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={showOnboarding}
                    onRequestClose={() => setShowOnboarding(false)}
                >
                    <Pressable
                        className="flex-1 bg-black/50 items-center justify-center"
                        onPress={() => setShowOnboarding(false)}
                    >
                        <View className="w-[120%] rounded-2xl ">
                            <Image
                                source={{ uri: mainPromotionImage }}
                                className="w-full aspect-square "
                                resizeMode="contain"
                            />
                            <Text className="text-center mt-4 mb-2 text-gray-200">點擊任意位置關閉</Text>
                        </View>
                    </Pressable>
                </Modal>
            )}

            <ScrollView showsVerticalScrollIndicator={false} className="flex-1 mx-[5%] ">
                <View className=" flex-1 pt-8 ">
                    <View className="flex-row items-center pb-4">
                        <HomeIconSvg />
                        <View className="pl-2 flex-1 flex-column ">
                            <View className="flex-row justify-between mr-[10%]">
                                <Text className="text-lg text-left pb-1">你好！</Text>
                                <View className="relative">
                                    {/* <Pressable onPress={() => router.push('notificationPage')}>
                                        <View className="w-6 h-6">
                                            <BellIconSvg />
                                        </View>
                                        <View className="absolute -top-2 -right-2 bg-red-500 rounded-full w-5 h-5 items-center justify-center">
                                            <Text className="text-white text-xs font-bold">3</Text>
                                        </View>
                                    </Pressable> */}
                                </View>
                            </View>
                            <Text className="text-4xl font-light ">{user?.nickname}</Text>
                        </View>
                    </View>
                    <View className=" flex-1 justify-center ">
                        <Pressable onPress={() => router.push('searchPage')}>
                            <View
                                style={{
                                    borderWidth: 1,
                                    padding: 24,
                                    borderRadius: 12,
                                    borderColor: '#bbbbbb',
                                    maxWidth: '100%'
                                }}
                            >
                                <Text style={{ color: '#888888', fontSize: 16 }}>搜尋充電站或地區..</Text>
                            </View>
                        </Pressable>
                    </View>
                </View>
                {/* <View className="flex-1">
                    <RecentlyBookedScrollView />
                </View> */}
                <View className="flex-1">
                    <View className=" my-4">
                        <NormalButton
                            // onPress={() => console.log('掃瞄及充電')}
                            onPress={() => router.push('scanQrPage')}
                            title={
                                <View className="flex flex-row space-x-2 items-center">
                                    <QrCodeIconSvg />
                                    <Text className="text-white font-bold text-lg">掃描及充電</Text>
                                </View>
                            }
                            extendedStyle={{
                                alignItems: 'flex-start',
                                padding: 24
                            }}
                        />
                    </View>
                    <View className="flex-1 flex-row justify-between gap-6">
                        <View className="flex-1">
                            <NormalButton
                                // onPress={() => router.push('bookingMenuPage')}
                                onPress={() => Alert.alert('即將推出', '此功能即將推出，敬請期待！')}
                                title={
                                    <View className="flex flex-row space-x-2 items-center ">
                                        <MyBookingIconSvg />
                                        <Text className="text-white font-bold text-lg">我的預約</Text>
                                    </View>
                                }
                                extendedStyle={{
                                    alignItems: 'flex-start',
                                    padding: 24
                                }}
                            />
                        </View>
                        <View className="flex-1">
                            {/* <NormalButton
                                onPress={() => router.push('myVehiclePage')}
                                title={
                                    <View className="flex flex-row space-x-2 items-center">
                                        <MyVehicleIconSvg />
                                        <Text className="text-white font-bold text-lg">我的車輛</Text>
                                    </View>
                                }
                                extendedStyle={{
                                    alignItems: 'flex-start',
                                    padding: 24
                                }}
                            /> */}

                            <NormalButton
                                onPress={() => router.push('accountMainPage')}
                                title={
                                    <View className="flex flex-row space-x-2 items-center">
                                        <MyVehicleIconSvg />
                                        <Text className="text-white font-bold text-lg">我的帳戶</Text>
                                    </View>
                                }
                                extendedStyle={{
                                    alignItems: 'flex-start',
                                    padding: 24
                                }}
                            />
                        </View>
                    </View>
                    <View className="mt-4">
                        <NormalButton
                            // onPress={() => console.log('掃瞄及充電')}
                            onPress={() => router.push('vipQrPage')}
                            title={
                                <View className="flex flex-row items-center space-x-2">
                                    <VipCodeIconSvg />
                                    <Text className="text-white font-bold text-lg">專屬會員二維碼</Text>
                                </View>
                            }
                            extendedStyle={{
                                alignItems: 'flex-start',
                                padding: 24
                            }}
                        />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};
export default HomePage;
