import { View, Text, StyleSheet, ScrollView, Dimensions, ActivityIndicator, RefreshControl, Alert } from 'react-native';
import TabViewComponent, { TabItem } from '../global/tabView';
import NormalButton from '../global/normal_button';
import { SafeAreaView } from 'react-native-safe-area-context';
import RecentlyBookedScrollView from '../global/recentlyBookedScrollView';
import { router } from 'expo-router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';
import { calculateDistance } from '../global/distanceCalculator';
import React from 'react';
import BookingTabViewComponent from '../global/bookingTabViewComponent';

interface BookingMenuPageProps {}
const BookingMenuPageComponent: React.FC<BookingMenuPageProps> = () => {
    //check for unpaid penalties
    useEffect(() => {
        const checkUnpaidPenalties = async () => {
            try {
                const reservationHistories = await chargeStationService.fetchReservationHistories();
                const unpaidPenalties = reservationHistories.filter(
                    (reservation) => reservation.penalty_fee > 0 && reservation.penalty_paid_status === false
                );

                if (unpaidPenalties.length > 0) {
                    const mostRecentUnpaidReservation = unpaidPenalties.reduce((mostRecent, current) => {
                        return new Date(mostRecent.created_at) > new Date(current.created_at) ? mostRecent : current;
                    }, unpaidPenalties[0]);

                    Alert.alert(
                        '未付罰款',
                        '您有未支付的罰款。請先支付罰款後再開始充電。',
                        [
                            {
                                text: '查看詳情',
                                onPress: () => {
                                    // Navigate to a page showing penalty details
                                    router.push({
                                        pathname: '(auth)/(tabs)/(home)/penaltyPaymentPage',
                                        params: {
                                            book_time: mostRecentUnpaidReservation.book_time,
                                            end_time: mostRecentUnpaidReservation.end_time,
                                            actual_end_time: mostRecentUnpaidReservation.actual_end_time,
                                            penalty_fee: mostRecentUnpaidReservation.penalty_fee,
                                            format_order_id: mostRecentUnpaidReservation.format_order_id,
                                            id: mostRecentUnpaidReservation.id,
                                            stationName:
                                                mostRecentUnpaidReservation.connector.EquipmentID.StationID.snapshot
                                                    .StationName,
                                            address:
                                                mostRecentUnpaidReservation.connector.EquipmentID.StationID.snapshot
                                                    .Address
                                        }
                                    });
                                }
                            },
                            {
                                text: '返回',
                                onPress: () => {
                                    if (router.canGoBack()) {
                                        router.back();
                                    } else {
                                        router.push('/mainPage');
                                    }
                                }
                            }
                        ],
                        { cancelable: false }
                    );
                }
            } catch (error) {
                console.error('Error checking unpaid penalties:', error);
                // Handle the error appropriately (e.g., show an error message to the user)
            }
        };

        checkUnpaidPenalties();
    }, []);

    // console.log('BookingMenuPageComponent rendering');
    const [refreshing, setRefreshing] = useState(false);
    const [refetchTrigger, setRefetchTrigger] = useState(0);

    const calculateResponsivePadding = useCallback(() => {
        const screenHeight = Dimensions.get('window').height;
        return screenHeight * 0.03;
    }, []);

    const calculateTabViewHeight = useCallback(() => {
        const screenHeight = Dimensions.get('window').height;
        if (screenHeight > 800) return 500;
        else if (screenHeight > 550) return 300;
        else return 150;
    }, []);

    const onRefresh = useCallback(() => {
        setRefreshing(true);
        setRefetchTrigger((prev) => prev + 1);
        // Simulate a delay to show the refresh indicator
        setTimeout(() => {
            setRefreshing(false);
        }, 1000);
    }, []);

    return (
        <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
            <ScrollView
                className="flex-1 mt-8"
                nestedScrollEnabled={true}
                showsVerticalScrollIndicator={false}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        onRefresh={onRefresh}
                        colors={['#34657b']} // Android
                        tintColor="#34657b" // iOS
                    />
                }
            >
                <View className="mx-[5%]">
                    <View>
                        <Text className="text-5xl pt-1 pb-6">預約</Text>
                        <NormalButton
                            title={<Text style={{ color: 'white', fontSize: 16, fontWeight: '800' }}>+ 新增預約</Text>}
                            // onPress={() => router.push('reservationLocationPage')}
                            onPress={() => Alert.alert('即將推出', '此功能即將推出，敬請期待！')}
                            extendedStyle={{ padding: calculateResponsivePadding() }}
                        />
                    </View>
                    <RecentlyBookedScrollView />
                </View>
                <View className="flex-1" style={{ height: calculateTabViewHeight() }}>
                    <BookingTabViewComponent titles={['已預約', '已完成']} refetchTrigger={refetchTrigger} />
                    {/* <TabViewComponent
                        titles={['已預約', '已完成']}
                        tabItems={tabItems}
                        isLoading={isLoading}
                        completedReservationTabItems={completedReservationTabItems}
                    /> */}
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default React.memo(BookingMenuPageComponent);
