import { router, useLocalSearchParams } from 'expo-router';
import { View, Text, ScrollView, Pressable, Image, Dimensions, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { PreviousPageBlackSvg, StarSvg } from '../global/SVG';
import NormalButton from '../global/normal_button';
import { chargeStationService } from '../../service/chargeStationService';
import { useState } from 'react';
import { formatDate } from '../../util/lib';

const ManageVehiclePageComponent = () => {
    const { height: deviceHeight, width: deviceWidth } = Dimensions.get('window');
    const [loading, setLoading] = useState(false);
    const [loading2, setLoading2] = useState(false);
    const params = useLocalSearchParams();
    const carID = params?.carID;
    const carCapacitance = params?.capacitance;
    const carCapacitanceUnit = params?.capacitance_unit;
    const carCreatedAt = params?.createdAt;
    const carModel = params?.carModel;
    const carImage = params.carImage;
    const licensePlate = params?.licensePlate;
    console.log(carID, carCapacitance, carCapacitanceUnit, carCreatedAt);

    const handleDeleteCar = async (carID) => {
        const confirmDelete = () => {
            return new Promise((resolve) => {
                Alert.alert(
                    'Confirm Delete',
                    'Are you sure you want to delete this car?',
                    [
                        {
                            text: 'No',
                            onPress: () => resolve(false),
                            style: 'cancel'
                        },
                        { text: 'Yes', onPress: () => resolve(true) }
                    ],
                    { cancelable: false }
                );
            });
        };
        const userConfirmed = await confirmDelete();
        if (userConfirmed) {
            try {
                setLoading2(true);
                const isDeleted = await chargeStationService.deleteCar(carID);
                if (isDeleted) {
                    Alert.alert('Deletion Successful', 'Car has been deleted');
                    router.push('/mainPage');
                } else {
                    // Show an error message if deletion was not successful
                    Alert.alert('Deletion Failed', 'Unable to delete the car. Please try again.');
                }
            } catch (error) {
                console.error('Error deleting car:', error);
                Alert.alert('Error', 'An error occurred while deleting the car.');
            } finally {
                setLoading2(false);
            }
        }
    };

    const handleSetDefaultCar = async (carID) => {
        setLoading(true);
        try {
            const isSetDefault = await chargeStationService.setDefaultCar(carID);
            if (isSetDefault) {
                Alert.alert('設置成功', '已成功設置預設車輛');
                router.push('/mainPage');
            } else {
                console.log('Unable to set default car');
            }
        } catch (error) {
            console.log(error);
        } finally {
            setLoading(false);
        }
    };
    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView showsVerticalScrollIndicator={false} className="flex-1 mx-[5%]">
                <View style={{ marginTop: 25, flexDirection: 'column' }}>
                    <Pressable
                        className="self-start"
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <PreviousPageBlackSvg />
                    </Pressable>
                </View>

                <Text
                    style={{
                        fontSize: 30,
                        marginTop: 25,
                        marginBottom: 10
                    }}
                >
                    管理車輛
                </Text>
                <View className="items-center ">
                    <Image
                        source={{
                            uri: carImage
                        }}
                        resizeMode="contain"
                        style={{
                            width: deviceWidth * 0.8,
                            height: deviceHeight * 0.25
                        }}
                    />
                </View>

                <View className="flex-row space-x-2 ">
                    <View
                        style={{
                            width: 4,
                            height: '100%',
                            backgroundColor: '#02677D'
                        }}
                    />
                    <View>
                        <Text className="text-2xl">{carModel}</Text>
                        <Text className="text-lg text-[#888888]">{licensePlate}</Text>
                    </View>
                </View>
                <NormalButton
                    title={
                        loading ? (
                            <View
                                style={{
                                    flexDirection: 'row',
                                    alignItems: 'center'
                                }}
                            >
                                <ActivityIndicator size="small" color="#fff" />
                                <Text
                                    style={{
                                        fontWeight: '500',
                                        fontSize: 20,
                                        color: '#fff',
                                        marginLeft: 10
                                    }}
                                >
                                    設置中...
                                </Text>
                            </View>
                        ) : (
                            <Text
                                style={{
                                    fontWeight: '500',
                                    fontSize: 20,
                                    color: '#fff'
                                }}
                            >
                                設置為預設車輛 <StarSvg />
                            </Text>
                        )
                    }
                    onPress={() => {
                        if (!loading) {
                            handleSetDefaultCar(carID);
                        }
                    }}
                    extendedStyle={{ marginTop: 24 }}
                    disabled={loading}
                />
                <View className="w-full h-1 my-4 bg-[#DBE4E8]" />
                <View>
                    <Text className="text-xl pb-4">車輛資訊</Text>
                    <Text className="text-base text-[#888888]">加入日期</Text>
                    <Text className="text-base mb-3">{formatDate(carCreatedAt)}</Text>
                    <Text className="text-base text-[#888888]">總充電量</Text>
                    <Text className="text-base mb-3">{carCapacitance + carCapacitanceUnit}</Text>
                    <Text className="text-base text-[#888888]">上一次充電</Text>
                    <Text className="text-base mb-3">待DATA</Text>
                    <View className="my-4 pb-8">
                        <NormalButton
                            title={
                                <Text
                                    style={{
                                        color: 'white',
                                        fontSize: 20,
                                        fontWeight: '800'
                                    }}
                                >
                                    {loading2 ? '删除車輛中...' : '删除車輛'}
                                </Text>
                            }
                            onPress={() => {
                                handleDeleteCar(carID);
                            }}
                            extendedStyle={{
                                backgroundColor: '#D40000'
                            }}
                        />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ManageVehiclePageComponent;
