import Svg, { Path, Rect } from 'react-native-svg';
import * as React from 'react';
import {
    View,
    Text,
    useWindowDimensions,
    StyleSheet,
    Image,
    ImageSourcePropType,
    Pressable,
    ActivityIndicator
} from 'react-native';
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import { FlashList } from '@shopify/flash-list';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { CheckMarkLogoSvg, CrossLogoSvg } from '../global/SVG';
import { useEffect, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';

import * as Location from 'expo-location';
import { calculateDistance } from '../global/distanceCalculator';

interface TabItem {
    imgURL: ImageSourcePropType;
    date: string;
    time: string;
    chargeStationName: string;
    chargeStationAddress: string;
    distance: string;
    stationID: string;
    lat: string;
    lng: string;
}

interface TabViewComponentProps {
    titles: string[];
    tabItems: TabItem[];
}

const ReservationLocationPage = () => {
    const [stations, setStations] = useState([]);
    const [TabItems, setTabItems] = useState<TabItem[]>([]);
    const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);

    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);
    };
    useEffect(() => {
        getCurrentLocation();
    }, []);

    const LocationTabComponent: React.FC<TabViewComponentProps> = ({ titles, tabItems }) => {
        const FirstRoute = () => (
            <View
                style={{
                    flex: 1,
                    backgroundColor: 'white'
                }}
            >
                {TabItems.length > 0 ? (
                    <FlashList
                        data={tabItems}
                        renderItem={({ item }) => {
                            return (
                                <Pressable
                                    onPress={() =>
                                        router.push({
                                            pathname: '/resultDetailPage',
                                            params: {
                                                chargeStationAddress: item.chargeStationAddress,
                                                chargeStationName: item.chargeStationName,
                                                chargeStationID: item.stationID,
                                                chargeStationLng: item.lng,
                                                chargeStationLat: item.lat
                                            }
                                        })
                                    }
                                    style={({ pressed }) => [
                                        styles.container,
                                        {
                                            backgroundColor: pressed ? '#e7f2f8' : '#ffffff'
                                        }
                                    ]}
                                >
                                    <View style={styles.container} className=" flex-1 flex-row ">
                                        <Image style={styles.image} source={item.imgURL} />
                                        <View style={styles.textContainer} className="flex-1 justify-evenly">
                                            <Text
                                                style={{
                                                    fontWeight: 400,
                                                    fontSize: 20,
                                                    color: '#222222'
                                                }}
                                            >
                                                {item.chargeStationName}
                                            </Text>
                                            <Text
                                                style={{
                                                    fontWeight: 400,
                                                    fontSize: 14,
                                                    color: '#888888'
                                                }}
                                            >
                                                {item.chargeStationAddress}
                                            </Text>
                                            <View className=" flex-row space-x-2  items-center">
                                                <CheckMarkLogoSvg />
                                                <Text
                                                    style={{
                                                        fontWeight: 400,
                                                        fontSize: 14,
                                                        color: '#222222'
                                                    }}
                                                >
                                                    Walk-in
                                                </Text>
                                            </View>
                                        </View>

                                        <Text
                                            style={{
                                                fontWeight: 400,
                                                fontSize: 16,
                                                color: '#888888',
                                                marginTop: 22,
                                                marginLeft: 'auto',
                                                marginRight: 10
                                            }}
                                        >
                                            {item.distance}
                                        </Text>
                                    </View>
                                </Pressable>
                            );
                        }}
                    />
                ) : (
                    <View className="flex-1 items-center justify-center">
                        <ActivityIndicator size="large" />
                    </View>
                )}
            </View>
        );

        //tab 2

        const SecondRoute = () => (
            <View
                style={{
                    flex: 1,
                    backgroundColor: 'white'
                }}
            >
                <FlashList
                    data={tabItems}
                    renderItem={({ item }) => {
                        return (
                            <Pressable
                                onPress={() =>
                                    router.push({
                                        pathname: '/resultDetailPage',
                                        params: {
                                            chargeStationAddress: item.chargeStationAddress,
                                            chargeStationName: item.chargeStationName,
                                            chargeStationLng: item.lng,
                                            chargeStationLat: item.lat
                                        }
                                    })
                                }
                                style={({ pressed }) => [
                                    styles.container,
                                    {
                                        backgroundColor: pressed ? '#e7f2f8' : '#ffffff'
                                    }
                                ]}
                            >
                                <View style={styles.container} className=" flex-1 flex-row ">
                                    <Image style={styles.image} source={item.imgURL} />
                                    <View style={styles.textContainer} className="flex-1 justify-evenly">
                                        <Text
                                            style={{
                                                fontWeight: 400,
                                                fontSize: 20,
                                                color: '#222222'
                                            }}
                                        >
                                            {item.chargeStationName}
                                        </Text>
                                        <Text
                                            style={{
                                                fontWeight: 400,
                                                fontSize: 14,
                                                color: '#888888'
                                            }}
                                        >
                                            {item.chargeStationAddress}
                                        </Text>

                                        <View className=" flex-row space-x-2  items-center">
                                            <CheckMarkLogoSvg />
                                            <Text
                                                style={{
                                                    fontWeight: 400,
                                                    fontSize: 14,
                                                    color: '#222222'
                                                }}
                                            >
                                                Walk-in
                                            </Text>
                                        </View>
                                    </View>

                                    <Text
                                        style={{
                                            fontWeight: 400,
                                            fontSize: 16,
                                            color: '#888888',
                                            marginTop: 22,
                                            marginLeft: 'auto',
                                            marginRight: 10
                                        }}
                                    >
                                        {item.distance}
                                    </Text>
                                </View>
                            </Pressable>
                        );
                    }}
                />
            </View>
        );

        const renderScene = SceneMap({
            firstRoute: FirstRoute,
            secondRoute: SecondRoute
        });
        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,
                    borderBottomWidth: 0.5
                }}
            />
        );
        return (
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                // initialLayout={{ width: layout.width }}
                renderTabBar={renderTabBar}
                commonOptions={{
                    label: ({ route, focused }) => (
                        <Text
                            style={{
                                color: focused ? '#025c72' : '#888888',
                                fontWeight: focused ? '900' : 'thin',
                                fontSize: 20
                            }}
                        >
                            {route.title}
                        </Text>
                    )
                }}
            />
        );
    };

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

    //     const fetchStations = async () => {
    //         const fetchedStations = await chargeStationService.fetchChargeStations();
    //         setStations(fetchedStations);

    //         const TabItems = fetchedStations.map((station) => ({
    //             chargeStationAddress: station.Address,
    //             chargeStationName: station.StationName,
    //             lng: station.StationLng,
    //             lat: station.StationLat,
    //             date: '今天',
    //             stationID: station.StationID,
    //             imgURL: require('../../assets/dummyStationPicture.png'),
    //             distance: '400米'
    //         }));
    //         setTabItems(TabItems);
    //     };
    //     fetchStations();
    // }, []);
    const fetchStations = async () => {
        const fetchedStations = await chargeStationService.fetchChargeStations();
        setStations(fetchedStations);

        if (currentLocation) {
            const TabItems = await Promise.all(
                fetchedStations.map(async (station) => {
                    const distance = await calculateDistance(
                        Number(station.StationLat),
                        Number(station.StationLng),
                        currentLocation
                    );
                    return {
                        chargeStationAddress: station.Address,
                        chargeStationName: station.StationName,
                        lng: station.StationLng,
                        lat: station.StationLat,
                        date: '今天',
                        stationID: station.StationID,
                        imgURL: require('../../assets/dummyStationPicture.png'),
                        distance: distance !== null ? formatDistance(distance) : 'N/A'
                    };
                })
            );
            setTabItems(TabItems);
        }
    };

    useEffect(() => {
        if (currentLocation) {
            fetchStations();
        }
    }, [currentLocation]);

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

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'left', 'right']}>
            <View className="flex-1">
                <View className="min-h-[250px] flex-column mx-[5%]">
                    <View className="flex-1 justify-center">
                        <View className="pt-5 pl-4">
                            <Pressable
                                onPress={() => {
                                    if (router.canGoBack()) {
                                        router.back();
                                    } else {
                                        router.replace('/');
                                    }
                                }}
                            >
                                <CrossLogoSvg />
                            </Pressable>
                        </View>
                    </View>
                    <View className="flex-1 justify-center ">
                        <Text className="text-[50px] font-normal ">預約地點</Text>
                    </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 mt-2">
                    <LocationTabComponent titles={['附近的充電站', '所有的充電站']} tabItems={TabItems} />
                </View>
            </View>
        </SafeAreaView>
    );
};

export default ReservationLocationPage;
