import { router } from 'expo-router';
import {
    View,
    Text,
    ScrollView,
    Pressable,
    Image,
    Dimensions,
    ImageBackground
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { CrossLogoSvg, GreenStarSvg, RightArrowIconSvg } from '../global/SVG';
import NormalButton from '../global/normal_button';
import { useEffect, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';
import { authenticationService } from '../../service/authService';

const VehicleRowComponent = ({
    deviceWidth,
    deviceHeight,
    carBrand,
    carModel,
    licensePlate,
    carID,
    capacitance,
    capacitance_unit,
    createdAt
}: {
    deviceWidth: number;
    deviceHeight: number;
    carBrand: string;
    carModel: string;
    licensePlate: string;
    carID: string;
    capacitance: number;
    capacitance_unit: string;
    createdAt: any;
}) => (
    <Pressable
        onPress={() =>
            router.push({
                pathname: 'manageVehiclePage',
                params: {
                    carID: carID,
                    capacitance: capacitance,
                    capacitance_unit: capacitance_unit,
                    createdAt: createdAt,
                    carModel: carModel,
                    licensePlate: licensePlate
                }
            })
        }
    >
        <View
            className="rounded-xl overflow-hidden mb-3"
            style={{
                width: deviceWidth * 0.9,
                height: deviceHeight * 0.12
            }}
        >
            <ImageBackground
                source={require('../../assets/myVehicleBackground.png')}
                resizeMode="cover"
                className="flex-1 flex-row items-center justify-between "
            >
                <Image
                    style={{
                        marginTop: 15,
                        marginLeft: 5,
                        width: deviceWidth * 0.35,
                        height: '100%'
                    }}
                    resizeMode="contain"
                    source={require('../../assets/car1.png')}
                    className=""
                />
                <View
                    className="flex-col "
                    style={{
                        paddingRight: deviceHeight < 600 ? 80 : 100
                    }}
                >
                    <Text
                        style={{
                            fontSize: deviceHeight < 600 ? 18 : 22,
                            fontWeight: '600'
                        }}
                    >
                        {carBrand}
                    </Text>
                    <Text style={{ fontSize: deviceHeight < 600 ? 14 : 18 }}>
                        {carModel}
                    </Text>
                    <Text
                        style={{
                            fontSize: deviceHeight < 600 ? 12 : 16,
                            color: '#02677D'
                        }}
                        className=" text-[#02677D]"
                    >
                        {licensePlate}
                    </Text>
                </View>
                <View className="pr-3">
                    <RightArrowIconSvg />
                </View>
            </ImageBackground>
        </View>
    </Pressable>
);

const MyVehiclePageComponent = () => {
    const { height: deviceHeight, width: deviceWidth } =
        Dimensions.get('window');
    console.log(deviceHeight, deviceWidth);
    const [myVehicleData, setMyVehicleData] = useState([]);
    const [defaultCarInfo, setDefaultCarInfo] = useState(null);
    const [defaultCarId, setDefaultCarId] = useState(null);

    const extractDefaultCarInfo = (response) => {
        const defaultCar = response.cars.find(
            (car) => car.id === response.defaultCar.id
        );
        if (defaultCar) {
            return {
                name: defaultCar.name,
                license_plate: defaultCar.license_plate
            };
        }

        return null;
    };

    useEffect(() => {
        const fetchData = async () => {
            try {
                const result = await chargeStationService.getUserCars();
                // console.log(JSON.stringify(result.data));
                setMyVehicleData(result.data);
            } catch (error) {
                console.log(error);
            }
        };
        fetchData();
    }, []);

    useEffect(() => {
        const fetchDefaultCar = async () => {
            try {
                const result = await authenticationService.getUserInfo();
                const response = result.data;
                const carInfo = extractDefaultCarInfo(response);
                setDefaultCarInfo(carInfo);
                setDefaultCarId(response.defaultCar.id);
                console.log('i am car info' + defaultCarId);
            } catch (error) {
                console.log(error);
            }
        };
        fetchDefaultCar();
    }, []);

    return (
        <SafeAreaView
            className="flex-1 bg-white"
            edges={['top', 'right', 'left']}
        >
            <ScrollView
                showsVerticalScrollIndicator={false}
                className="flex-1 mx-[5%]"
            >
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        className="self-start"
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <CrossLogoSvg />
                    </Pressable>
                    <Text
                        style={{
                            fontSize: 45,
                            marginTop: 25,
                            marginBottom: 10
                        }}
                    >
                        我的車輛
                    </Text>
                </View>
                <View className="items-center ">
                    <Image
                        source={require('../../assets/car.png')}
                        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>
                        <View className="flex-row items-center">
                            <Text className="text-lg text-[#02677D]">
                                預設車輛
                            </Text>
                            <GreenStarSvg />
                        </View>
                        <Text className="text-2xl">{defaultCarInfo?.name}</Text>
                        <Text className="text-lg text-[#888888]">
                            {defaultCarInfo?.license_plate}
                        </Text>
                    </View>
                </View>
                <View className="w-full h-1 my-4 bg-[#DBE4E8]" />

                <Text className="text-xl mb-4">其他車輛</Text>

                {myVehicleData
                    .filter((car) => car.id !== defaultCarId)
                    .map((car, index) => (
                        <VehicleRowComponent
                            deviceHeight={deviceHeight}
                            deviceWidth={deviceWidth}
                            carBrand={car.car_brand.name}
                            carModel={car.car_type.name}
                            licensePlate={car.license_plate}
                            carID={car.id}
                            capacitance={car.car_type.capacitance}
                            capacitance_unit={car.car_type.capacitance_unit}
                            createdAt={car.car_type.createdAt}
                            key={index}
                        />
                    ))}

                <NormalButton
                    title={
                        <Text
                            style={{
                                fontWeight: '700',
                                fontSize: 20,
                                color: '#fff'
                            }}
                        >
                            新增車輛
                        </Text>
                    }
                    onPress={() => router.push('addVehiclePage')}
                />
            </ScrollView>
        </SafeAreaView>
    );
};

export default MyVehiclePageComponent;
