//the size of the TabView will follow its parent-container's size.

import * as React from 'react';
import * as Location from 'expo-location';
import {
    View,
    Text,
    useWindowDimensions,
    StyleSheet,
    Image,
    ImageSourcePropType,
    ActivityIndicator,
    Pressable
} from 'react-native';
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import { FlashList } from '@shopify/flash-list';
import { useEffect, useState } from 'react';
import { calculateDistance } from './distanceCalculator';
import { router } from 'expo-router';

export interface TabItem {
    imgURL: ImageSourcePropType;
    date: string;
    time: string;
    chargeStationName: string;
    chargeStationAddress: string;
    stationLat: string | number;
    stationLng: string | number;
    distance: string;
    format_order_id: string;
}

interface TabViewComponentProps {
    titles: string[];
    tabItems: TabItem[];
    completedReservationTabItems: TabItem[];
    isLoading?: boolean;
}

const TabViewComponent: React.FC<TabViewComponentProps> = ({
    titles,
    isLoading,
    tabItems,
    completedReservationTabItems
}) => {
    const layout = useWindowDimensions();
    const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);

    useEffect(() => {
        const getCurrentLocation = async () => {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                console.error('Permission to access location was denied');
                return;
            }
            let location = await Location.getLastKnownPositionAsync({});
            setCurrentLocation(location);
        };

        getCurrentLocation();
    }, []);

    // Memoize the route components
    // const FirstRoute = React.useMemo(
    //     () =>
    //         React.memo(() => (
    //             <View style={{ flex: 1, backgroundColor: 'white' }}>
    //                 {isLoading ? (
    //                     <View className="items-center justify-center flex-1">
    //                         <ActivityIndicator color="#34657b" />
    //                     </View>
    //                 ) : (
    //                     <FlashList
    //                         nestedScrollEnabled={true}
    //                         data={tabItems}
    //                         renderItem={({ item }) => <TabItem item={item} currentLocation={currentLocation} />}
    //                         estimatedItemSize={10}
    //                     />
    //                 )}
    //             </View>
    //         )),
    //     [isLoading, tabItems]
    // );
    //i unmemoed it
    const FirstRoute = () => (
        <View style={{ flex: 1, backgroundColor: 'white' }}>
            {isLoading ? (
                <View className="items-center justify-center flex-1">
                    <ActivityIndicator color="#34657b" />
                </View>
            ) : (
                <FlashList
                    nestedScrollEnabled={true}
                    data={tabItems}
                    renderItem={({ item }) => <TabItem item={item} currentLocation={currentLocation} />}
                    estimatedItemSize={10}
                />
            )}
        </View>
    );

    const SecondRoute = React.useMemo(
        () =>
            React.memo(() => (
                <View style={{ flex: 1, backgroundColor: 'white' }}>
                    <FlashList
                        nestedScrollEnabled={true}
                        data={completedReservationTabItems}
                        renderItem={({ item }) => <TabItem item={item} currentLocation={currentLocation} />}
                        estimatedItemSize={10}
                    />
                </View>
            )),
        [completedReservationTabItems]
    );

    // Use useCallback for renderScene
    // const renderScene = React.useCallback(
    //     SceneMap({
    //         firstRoute: FirstRoute,
    //         secondRoute: SecondRoute
    //     }),
    //     [FirstRoute, SecondRoute]
    // );

    //uncallbacked it
    const renderScene = SceneMap({
        firstRoute: FirstRoute,
        secondRoute: SecondRoute
    });

    // const routes = React.useMemo(
    //     () => [
    //         { key: 'firstRoute', title: titles[0] },
    //         { key: 'secondRoute', title: titles[1] }
    //     ],
    //     [titles]
    // );

    const routes = [
        { key: 'firstRoute', title: titles[0] },
        { key: 'secondRoute', title: titles[1] }
    ];

    const [index, setIndex] = React.useState(0);

    // const renderTabBar = React.useCallback(
    //     (props: any) => (
    //         <TabBar
    //             {...props}
    //             renderLabel={({ route, focused }) => (
    //                 <Text
    //                     style={{
    //                         color: focused ? '#025c72' : '#888888',
    //                         fontWeight: focused ? '900' : 'thin',
    //                         fontSize: 20
    //                     }}
    //                 >
    //                     {route.title}
    //                 </Text>
    //             )}
    //             indicatorStyle={{
    //                 backgroundColor: '#025c72'
    //             }}
    //             style={{
    //                 backgroundColor: 'white',
    //                 borderColor: '#DBE4E8',
    //                 elevation: 0,
    //                 marginHorizontal: 15,
    //                 borderBottomWidth: 0.5
    //             }}
    //         />
    //     ),
    //     []
    // );

    const renderTabBar = (props: any) => (
        <TabBar
            {...props}
            renderLabel={({ route, focused }) => (
                <Text
                    style={{
                        color: focused ? '#025c72' : '#888888',
                        fontWeight: focused ? '900' : 'thin',
                        fontSize: 20
                    }}
                >
                    {route.title}
                </Text>
            )}
            indicatorStyle={{
                backgroundColor: '#025c72'
            }}
            style={{
                backgroundColor: 'white',
                borderColor: '#DBE4E8',
                elevation: 0,
                marginHorizontal: 15,
                borderBottomWidth: 0.5
            }}
        />
    );

    return (
        <TabView
            navigationState={{ index, routes }}
            renderScene={renderScene}
            onIndexChange={setIndex}
            initialLayout={{ width: layout.width }}
            renderTabBar={renderTabBar}
            lazy
        />
    );
};

// Separate memoedTabItem component
// const TabItem = React.memo(
//     ({ item, currentLocation }: { item: TabItem; currentLocation: Location.LocationObject | null }) => {
//         const [distance, setDistance] = useState<number | null>(null);
//         useEffect(() => {
//             const getDistance = async () => {
//                 if (currentLocation) {
//                     const result = await calculateDistance(
//                         Number(item.stationLat),
//                         Number(item.stationLng),
//                         currentLocation
//                     );
//                     setDistance(result);
//                 }
//             };

//             getDistance();
//         }, [currentLocation, item.stationLat, item.stationLng]);

//         const formatDistance = (distanceInMeters: number): string => {
//             if (distanceInMeters < 1000) {
//                 return `${Math.round(distanceInMeters)}米`;
//             } else {
//                 const distanceInKm = distanceInMeters / 1000;
//                 return `${distanceInKm.toFixed(1)}公里`;
//             }
//         };
//         return (
//             <View style={styles.container}>
//                 <Image style={styles.image} source={item.imgURL} />
//                 <View style={styles.textContainer}>
//                     <Text
//                         style={{
//                             fontWeight: '700',
//                             color: '#02677D',
//                             fontSize: 20
//                         }}
//                     >
//                         {`${item.date} - ${item.time}`}
//                     </Text>
//                     <Text
//                         style={{
//                             fontWeight: '400',
//                             fontSize: 16,
//                             color: '#222222'
//                         }}
//                     >
//                         {item.chargeStationName}
//                     </Text>
//                     <Text
//                         style={{
//                             fontWeight: '400',
//                             fontSize: 16,
//                             color: '#888888'
//                         }}
//                     >
//                         {item.chargeStationAddress}
//                     </Text>
//                 </View>
//                 <Text
//                     style={{
//                         fontWeight: '400',
//                         fontSize: 16,
//                         color: '#888888',
//                         marginTop: 20,
//                         marginLeft: 16
//                     }}
//                 >
//                     {distance !== null ? formatDistance(distance) : ''}
//                 </Text>
//             </View>
//         );
//     }
// );

const TabItem = ({ item, currentLocation }: { item: TabItem; currentLocation: Location.LocationObject | null }) => {
    const [distance, setDistance] = useState<number | null>(null);

    useEffect(() => {
        const getDistance = async () => {
            if (currentLocation) {
                const result = await calculateDistance(
                    Number(item.stationLat),
                    Number(item.stationLng),
                    currentLocation
                );
                setDistance(result);
            }
        };

        getDistance();
    }, [currentLocation, item.stationLat, item.stationLng]);

    const formatDistance = (distanceInMeters: number): string => {
        if (distanceInMeters < 1000) {
            return `${Math.round(distanceInMeters)}米`;
        } else {
            const distanceInKm = distanceInMeters / 1000;
            return `${distanceInKm.toFixed(1)}公里`;
        }
    };

    return (
        <Pressable
            onPress={() => {
                console.log(item.format_order_id);
            }}
        >
            <View style={styles.container}>
                <Image style={styles.image} source={item.imgURL} />
                <View style={styles.textContainer}>
                    <Text
                        style={{
                            fontWeight: '700',
                            color: '#02677D',
                            fontSize: 20
                        }}
                    >
                        {`${item.date} - ${item.time}`}
                    </Text>
                    <Text
                        style={{
                            fontWeight: '400',
                            fontSize: 16,
                            color: '#222222'
                        }}
                    >
                        {item.chargeStationName}
                    </Text>
                    <Text
                        style={{
                            fontWeight: '400',
                            fontSize: 16,
                            color: '#888888'
                        }}
                    >
                        {item.chargeStationAddress}
                    </Text>
                </View>
                <Text
                    style={{
                        fontWeight: '400',
                        fontSize: 16,
                        color: '#888888',
                        marginTop: 20,
                        marginLeft: 16
                    }}
                >
                    {distance !== null ? formatDistance(distance) : ''}
                </Text>
            </View>
        </Pressable>
    );
};

export default TabViewComponent;

const styles = StyleSheet.create({
    container: { flexDirection: 'row' },
    image: { width: 100, height: 100, margin: 15, borderRadius: 10 },
    textContainer: { flexDirection: 'column', gap: 8, marginTop: 20 }
});
