// component/global/notificationTabViewComponent.tsx
//the size of the TabView will follow its parent-container's size.

import * as React from 'react';
import { View, Text, useWindowDimensions, StyleSheet, ScrollView, ActivityIndicator, Pressable } from 'react-native';
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';

import { formatToChineseDateTime } from '../../util/lib';
import { useCallback, useMemo, useEffect, useState } from 'react';
import { notificationStorage } from '../notificationStorage';
import { router, useFocusEffect } from 'expo-router';
import { useTranslation } from '../../util/hooks/useTranslation';

export interface TabItem {
    title: string;
    description: string;
    date: string;
}

interface TabViewComponentProps {
    titles: string[];
    reservationAfter2025: any;
    passingThisPromotionToBell: any;
}

const NotificationRow = ({
    promotionObj,
    index,
    viewedNotifications
}: {
    promotionObj: any;
    index: number;
    viewedNotifications: any;
}) => {
    const isViewed = viewedNotifications.some(
        (notification: any) => notification.id === promotionObj.id && notification.type === 'promotion'
    );

    const handlePress = async () => {
        // Mark promotion as viewed
        await notificationStorage.markAsViewed(promotionObj.id, 'promotion');
        router.push({
            pathname: '/notificationDetailPage',
            params: { promotion: JSON.stringify(promotionObj) }
        });
    };

    return (
        <Pressable
            onPress={handlePress}
            style={{ opacity: isViewed ? 0.5 : 1 }}
            className={`flex flex-col w-full bg-white space-y-2 p-2 ${index % 2 === 0 ? 'bg-[#e7f2f8]' : 'bg-white'}`}
        >
            <View className="flex flex-row justify-between">
                <Text className="font-[500] text-base">{promotionObj.title}</Text>
                <Text>{formatToChineseDateTime(promotionObj.createdAt)}</Text>
            </View>
            <View>
                <Text numberOfLines={2} ellipsizeMode="tail" className="text-sm">
                    {promotionObj.text}
                </Text>
            </View>
        </Pressable>
    );
};

const ReservationRow = ({
    reservationObj,
    index,
    viewedNotifications
}: {
    reservationObj: any;
    index: number;
    viewedNotifications: any;
}) => {
    const { t } = useTranslation();
    const isViewed = viewedNotifications.some(
        (notification: any) => notification?.id === reservationObj?.id && notification.type === 'reservation'
    );
    const handlePress = async () => {
        await notificationStorage.markAsViewed(reservationObj.id, 'reservation');
        if (reservationObj.status.id === '7') {
            router.push({ pathname: '/chargingPage' });
        } else {
            router.push({ pathname: '/chargingDetailPage', params: { promotion: JSON.stringify(reservationObj) } });
        }
    };

    const title =
        reservationObj.status.id === '8' || reservationObj.status.id === '13'
            ? t('notifications.chargingIn.charging_completed')
            : reservationObj.status.id === '7'
            ? t('notifications.chargingIn.charging_in_progress')
            : '';

    const text =
        reservationObj.status.id === '8' || reservationObj.status.id === '13'
            ? t('notifications.chargingIn.charging_completed_message')
            : reservationObj.status.id === '7'
            ? t('notifications.chargingIn.charging_in_progress_message', { soc: reservationObj.Soc })
            : '';

    return (
        <Pressable
            onPress={handlePress}
            style={{ opacity: isViewed ? 0.5 : 1 }}
            className={`flex flex-col w-full bg-white space-y-2 p-2 ${index % 2 === 0 ? 'bg-[#e7f2f8]' : 'bg-white'}`}
        >
            <View className="flex flex-row justify-between">
                <Text className={`font-[400] text-base ${reservationObj.status.id === '7' ? 'font-[700]' : ''}`}>
                    {title}
                </Text>
                <Text>{formatToChineseDateTime(reservationObj.createdAt)}</Text>
            </View>
            <View>
                <Text numberOfLines={2} ellipsizeMode="tail" className="text-sm">
                    {text}
                </Text>
            </View>
        </Pressable>
    );
};

const FirstRoute = ({ loading, reservationAfter2025 }: { loading: boolean; reservationAfter2025: any }) => {
    const { t } = useTranslation();
    const [viewedNotifications, setViewedNotifications] = useState([]);
    useFocusEffect(
        useCallback(() => {
            const getViewedNotifications = async () => {
                const notifications = await notificationStorage.getViewedNotifications();
                setViewedNotifications(notifications as any);
            };
            getViewedNotifications();
        }, [])
    );
    return (
        <ScrollView
            style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}
            contentContainerStyle={{ paddingBottom: 150 }}
        >
            <View className="flex-1 flex-col">
                {loading ? (
                    <View className="items-center justify-center">
                        <ActivityIndicator />
                    </View>
                ) : (
                    <View>
                        <View>
                            {reservationAfter2025.length === 0 ? (
                                <Text className="pl-4">{t('notifications.chargingIn.no_charging_info')}</Text>
                            ) : (
                                reservationAfter2025
                                    .sort(
                                        (a: any, b: any) =>
                                            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
                                    )
                                    .filter(
                                        (reservationObj: any) =>
                                            reservationObj.status.id === '7' ||
                                            reservationObj.status.id === '8' ||
                                            reservationObj.status.id === '13'
                                    )
                                    .slice(0, 30)
                                    .map((reservationObj: any, index: any) => (
                                        <ReservationRow
                                            reservationObj={reservationObj}
                                            index={index}
                                            key={reservationObj.id}
                                            viewedNotifications={viewedNotifications}
                                        />
                                    ))
                            )}
                        </View>
                    </View>
                )}
            </View>
        </ScrollView>
    );
};

const SecondRoute = ({ promotions, loading }: { promotions: TabItem[]; loading: boolean }) => {
    const { t } = useTranslation();
    const [viewedNotifications, setViewedNotifications] = useState([]);
    useFocusEffect(
        useCallback(() => {
            const getViewedNotifications = async () => {
                const notifications = await notificationStorage.getViewedNotifications();
                setViewedNotifications(notifications as any);
            };
            getViewedNotifications();
        }, [])
    );

    return (
        <ScrollView
            style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}
            contentContainerStyle={{ paddingBottom: 120 }}
        >
            <View className="flex-1 flex-col">
                {loading ? (
                    <View className="items-center justify-center">
                        <ActivityIndicator />
                    </View>
                ) : (
                    <View>
                        <View>
                            {promotions.length === 0 ? (
                                <Text className="pl-4">{t('notifications.no_promotions')}</Text>
                            ) : (
                                promotions
                                    .sort(
                                        (a: any, b: any) =>
                                            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
                                    )
                                    .slice(0, 30)
                                    .map((promotionObj: any, index: any) => (
                                        <NotificationRow
                                            promotionObj={promotionObj}
                                            index={index}
                                            key={promotionObj.id}
                                            viewedNotifications={viewedNotifications}
                                        />
                                    ))
                            )}
                        </View>
                    </View>
                )}
            </View>
        </ScrollView>
    );
};

const NotificationTabView: React.FC<TabViewComponentProps> = ({
    titles,
    reservationAfter2025,
    passingThisPromotionToBell
}) => {
    const layout = useWindowDimensions();
    const [loading, setLoading] = useState(true);
    const renderScene = useCallback(
        ({ route }: { route: any }) => {
            switch (route.key) {
                case 'firstRoute':
                    return <FirstRoute loading={loading} reservationAfter2025={reservationAfter2025} />;
                case 'secondRoute':
                    return <SecondRoute promotions={passingThisPromotionToBell} loading={loading} />;
                default:
                    return null;
            }
        },
        [reservationAfter2025, passingThisPromotionToBell]
    );
    useEffect(() => {
        setLoading(false)
    }, [reservationAfter2025, passingThisPromotionToBell]);
    const [routes] = React.useState([
        { key: 'firstRoute', title: titles[0] },
        { key: 'secondRoute', title: titles[1] }
    ]);
    const [index, setIndex] = React.useState(0);

    const renderTabBar = (props: any) => (
        <TabBar
            {...props}
            indicatorStyle={{
                backgroundColor: '#025c72'
            }}
            style={{
                backgroundColor: 'white',
                borderColor: '#DBE4E8',
                elevation: 0,
                marginHorizontal: 15,
                borderBottomWidth: 0.5
            }}
        />
    );
    return (
        <TabView
            navigationState={{ index, routes }}
            renderTabBar={renderTabBar}
            renderScene={renderScene}
            onIndexChange={setIndex}
            initialLayout={{ width: layout.width }}
            commonOptions={{
                label: ({ route, focused }) => (
                    <Text
                        style={{
                            color: focused ? '#025c72' : '#888888',
                            fontWeight: focused ? '900' : 'thin',
                            fontSize: 20
                        }}
                    >
                        {route.title}
                    </Text>
                )
            }}
            lazy
        />
    );
};
export default NotificationTabView;

const styles = StyleSheet.create({
    container: { flexDirection: 'row' },
    image: { width: 100, height: 100, margin: 15, borderRadius: 10 },
    textContainer: { flexDirection: 'column', gap: 8, marginTop: 20 },
    floatingButton: {
        elevation: 5,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 3.84
    }
});