import {
    View,
    Text,
    ScrollView,
    Image,
    useWindowDimensions,
    StyleSheet,
    Pressable,
    Platform,
    Linking,
    ActivityIndicator,
    Alert
} from 'react-native';
import React, { useEffect, useMemo, useState } from 'react';
import { SceneMap, TabBar, TabView } from 'react-native-tab-view';
import NormalButton from '../global/normal_button';
import { router, useLocalSearchParams } from 'expo-router';
import { CheckMarkLogoSvg, DirectionLogoSvg, PreviousPageSvg } from '../global/SVG';
import { SafeAreaView } from 'react-native-safe-area-context';
import { chargeStationService } from '../../service/chargeStationService';
import * as Location from 'expo-location';
import { calculateDistance } from '../global/distanceCalculator';

interface ChargingStationTabViewProps {
    titles: string[];
}
interface StationCoordinates {
    StationLat: number;
    StationLng: number;
}

const ChargingStationTabView: React.FC<ChargingStationTabViewProps> = ({ titles }) => {
    const layout = useWindowDimensions();

    //tab 1
    const FirstRoute = () => (
        <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
            <Text className="text-lg" style={styles.text}>
                由於充電站車流眾多， 敬請客戶務必於預約時間的十五分鐘內到達充電站。
                若客戶逾時超過15分鐘，系統將視作自動放棄預約，客戶需要重新預約一次。 本公司有權保留全數費用，恕不退還。
            </Text>
        </ScrollView>
    );

    //tab 2
    const SecondRoute = () => (
        <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
            <Text className="text-lg " style={styles.text}></Text>
        </ScrollView>
    );

    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}
            renderLabel={({ route, focused }) => (
                <Text
                    style={{
                        color: focused ? '#000000' : '#CCCCCC',
                        fontWeight: focused ? '300' : 'thin',
                        fontSize: 17
                    }}
                >
                    {route.title}
                </Text>
            )}
            indicatorStyle={{
                backgroundColor: '#000000',
                height: 1
            }}
            style={{
                backgroundColor: 'white',

                elevation: 0,
                marginHorizontal: 15,
                borderBottomWidth: 0.5
            }}
        />
    );
    return (
        <TabView
            navigationState={{ index, routes }}
            renderScene={renderScene}
            onIndexChange={setIndex}
            initialLayout={{ width: layout.width }}
            renderTabBar={renderTabBar}
        />
    );
};

const ResultDetailPageComponent = () => {
    const params = useLocalSearchParams();
    const chargeStationID = params.chargeStationID as string;
    const chargeStationName = params.chargeStationName as string;
    const chargeStationAddress = params.chargeStationAddress as string;
    // const chargeStationLat = params.chargeStationLat as string;
    // const chargeStationLng = params.chargeStationLng as string;
    const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
    const [distance, setDistance] = useState<string | null>(null);
    const [coordinates, setCoordinates] = useState<StationCoordinates | null>(null);
    const [price, setPrice] = useState('');

    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();
    }, []);

    useEffect(() => {
        const getDistance = async () => {
            if (currentLocation) {
                let stationLat, stationLng;

                if (params.chargeStationLat && params.chargeStationLng) {
                    stationLat = Number(params.chargeStationLat);
                    stationLng = Number(params.chargeStationLng);
                } else if (coordinates) {
                    stationLat = coordinates.StationLat;
                    stationLng = coordinates.StationLng;
                } else {
                    console.log('No station coordinates available');
                    return;
                }

                try {
                    const distance = await calculateDistance(stationLat, stationLng, currentLocation);
                    setDistance(formatDistance(distance));
                } catch (error) {
                    console.error('Error calculating distance:', error);
                }
            }
        };

        getDistance();
    }, [params.chargeStationLat, params.chargeStationLng, coordinates, currentLocation]);

    useEffect(() => {
        const fetchPrice = async () => {
            try {
                const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
                setPrice(price);
            } catch (error) {
                console.error('Error fetching price:', error);
            }
        };
        fetchPrice();
    }, []);
    // console.log(chargeStationLat, chargeStationLng);

    const memoizedCoordinates = useMemo(() => {
        if (params.chargeStationLat && params.chargeStationLng) {
            return {
                StationLat: parseFloat(params.chargeStationLat as string),
                StationLng: parseFloat(params.chargeStationLng as string)
            };
        }
        return null;
    }, [params.chargeStationLat, params.chargeStationLng]);

    useEffect(() => {
        const fetchCoordinates = async () => {
            // If coordinates are provided in params, use them
            if (memoizedCoordinates) {
                setCoordinates(memoizedCoordinates);
            } else {
                // If not provided, fetch from API
                try {
                    const response = await chargeStationService.fetchChargeStations();
                    if (response && response.length > 0) {
                        const station = response.find((s) => s.StationID === chargeStationID);
                        if (station) {
                            setCoordinates({
                                StationLat: station.StationLat,
                                StationLng: station.StationLng
                            });
                        }
                    }
                } catch (error) {
                    console.error('Error fetching coordinates:', error);
                }
            }
        };
        fetchCoordinates();
    }, [chargeStationID, memoizedCoordinates]);

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

    const handleNavigationPress = () => {
        console.log('starting navigation press in resultDetail', coordinates);
        if (coordinates) {
            const { StationLat, StationLng } = coordinates;
            const label = encodeURIComponent(chargeStationName);

            const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${StationLat},${StationLng}`;
            // Fallback URL for web browser
            const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${StationLat},${StationLng}`;

            Linking.canOpenURL(googleMapsUrl)
                .then((supported) => {
                    if (supported) {
                        Linking.openURL(googleMapsUrl);
                    } else {
                        Linking.openURL(webUrl).catch((err) => {
                            console.error('An error occurred', err);
                            Alert.alert(
                                'Error',
                                "Unable to open Google Maps. Please make sure it's installed on your device.",
                                [{ text: 'OK' }],
                                { cancelable: false }
                            );
                        });
                    }
                })
                .catch((err) => console.error('An error occurred', err));
        }
    };

    const handleNavigaationPress = () => {
        const latitude = chargeStationLat;
        const longitude = chargeStationLng;
        console.log('latitude', latitude);
        console.log('longitude', longitude);
        const label = encodeURIComponent(chargeStationName);

        // Google Maps App URL
        const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;

        // Fallback URL for web browser
        const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;

        Linking.canOpenURL(googleMapsUrl)
            .then((supported) => {
                if (supported) {
                    Linking.openURL(googleMapsUrl);
                } else {
                    Linking.openURL(webUrl).catch((err) => {
                        console.error('An error occurred', err);
                        Alert.alert(
                            'Error',
                            "Unable to open Google Maps. Please make sure it's installed on your device.",
                            [{ text: 'OK' }],
                            { cancelable: false }
                        );
                    });
                }
            })
            .catch((err) => console.error('An error occurred', err));
    };

    const handleAddBooking = () => {
        if (coordinates) {
            router.push({
                pathname: 'makingBookingPage',
                params: {
                    chargeStationID: chargeStationID,
                    chargeStationAddress: chargeStationAddress,
                    chargeStationName: chargeStationName,
                    chargeStationLat: coordinates.StationLat.toString(),
                    chargeStationLng: coordinates.StationLng.toString()
                }
            });
        }
    };

    return (
        <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
            <ScrollView className="flex-1 ">
                <View className="relative">
                    <Image
                        source={require('../../assets/dummyStationPicture.png')}
                        resizeMode="cover"
                        style={{ flex: 1, width: '100%' }}
                    />

                    <View className="absolute top-8 left-7 ">
                        <Pressable
                            onPress={() => {
                                if (router.canGoBack()) {
                                    router.back();
                                } else {
                                    router.replace('./');
                                }
                            }}
                        >
                            <PreviousPageSvg />
                        </Pressable>
                    </View>
                </View>

                <View className="flex-column mx-[5%] mt-[5%]">
                    <View>
                        <Text className="text-3xl">{chargeStationName}</Text>
                    </View>
                    <View className="flex-row justify-between items-center">
                        <Text className="text-base" style={{ color: '#888888' }}>
                            {chargeStationAddress}
                        </Text>
                        <NormalButton
                            title={
                                <View className="flex-row items-center justify-center text-center space-x-1">
                                    <DirectionLogoSvg />
                                    <Text className="text-base ">路線</Text>
                                </View>
                            }
                            onPress={handleNavigationPress}
                            extendedStyle={{
                                backgroundColor: '#E3F2F8',
                                borderRadius: 61,
                                paddingHorizontal: 20,
                                paddingVertical: 6
                            }}
                        />
                    </View>
                    <View className="flex-row space-x-2 items-center pb-4 ">
                        <CheckMarkLogoSvg />
                        <Text>Walk-In</Text>
                        {/* <Text>{distance} </Text> */}
                    </View>
                    {coordinates ? (
                        <NormalButton
                            title={
                                <View className="pr-2">
                                    <Text
                                        style={{
                                            color: '#FFFFFF',
                                            fontWeight: 700,
                                            fontSize: 20
                                        }}
                                    >
                                        ＋ 新增預約
                                    </Text>
                                </View>
                            }
                            // onPress={() => console.log('ab')}
                            onPress={handleAddBooking}
                        />
                    ) : (
                        <NormalButton
                            title={
                                <View className="pr-2">
                                    <Text
                                        style={{
                                            color: '#FFFFFF',
                                            fontWeight: 700,
                                            fontSize: 20
                                        }}
                                    >
                                        <ActivityIndicator />
                                    </Text>
                                </View>
                            }
                            // onPress={() => console.log('ab')}
                            onPress={handleAddBooking}
                        />
                    )}

                    <View
                        className="flex-1 flex-row min-h-[20px] border-slate-300 my-6 rounded-2xl"
                        style={{ borderWidth: 1 }}
                    >
                        <View className="flex-1 m-4">
                            <View className="flex-1 flex-row ">
                                <View className=" flex-1 flex-column  ustify-between">
                                    <Text className="text-xl " style={styles.text}>
                                        收費
                                    </Text>

                                    <View className="flex-row items-center space-x-2">
                                        <Text className="text-3xl text-[#02677D]">${price}</Text>
                                        <Text style={styles.text}>每度電</Text>
                                    </View>
                                </View>
                                <View className="items-center justify-center">
                                    <View className="w-[1px] h-[60%] bg-[#CCCCCC]" />
                                </View>
                                <View className=" flex-1 pl-4 flex-column  justify-between">
                                    <Text className="text-xl " style={styles.text}>
                                        可用充電槍數目
                                    </Text>

                                    <View className="flex-row items-center space-x-2">
                                        <Text className="text-3xl text-[#02677D]">4</Text>
                                    </View>
                                </View>
                            </View>
                        </View>
                    </View>
                </View>

                <View className="min-h-[300px]">
                    <Text className="text-xl pb-2 mx-[5%]" style={styles.text}>
                        充電站資訊
                    </Text>
                    <ChargingStationTabView titles={['充電插頭', '其他']} />
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ResultDetailPageComponent;

const styles = StyleSheet.create({
    text: {
        fontWeight: 300,
        color: '#000000'
    }
});
