import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, ScrollView, Pressable, Image, Dimensions, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { CrossLogoSvg, GreenStarSvg, RightArrowIconSvg } from '../global/SVG';
import NormalButton from '../global/normal_button';
import { chargeStationService } from '../../service/chargeStationService';
import { authenticationService } from '../../service/authService';
const truncateText = (text: any, maxLength: any) => {
    if (text.length <= maxLength) return text;
    return text.substr(0, maxLength) + '...';
};

const VehicleRow = ({ car, deviceWidth, deviceHeight, onPress }) => (
    <Pressable onPress={onPress}>
        <View
            className="rounded-xl mb-2 flex-row items-center justify-between "
            style={{
                width: deviceWidth * 0.9,
                height: deviceHeight * 0.12
                // backgroundColor: '#e9f2f7'
            }}
        >
            <Image
                style={{
                    width: deviceWidth * 0.32,
                    height: '100%'
                }}
                resizeMode="contain"
                source={{ uri: car.processedImageUrl }}
                // source={require('../../assets/car.png')}
            />
            <View className="flex-row items-center">
                <View className="flex-1 flex-col pl-2">
                    <Text style={{ fontSize: 22, fontWeight: '600' }}>{car.car_brand.name}</Text>
                    <Text style={{ fontSize: 18 }}>{truncateText(car.car_type.name, 10)}</Text>
                    <Text style={{ fontSize: 16, color: '#02677D' }}>{car.license_plate}</Text>
                </View>
                <View className="flex-1">
                    <RightArrowIconSvg />
                </View>
            </View>
        </View>
        <View className="border-t mx-4 border-[#CCCCCC]"></View>
    </Pressable>
);

const MyVehiclePageComponent = () => {
    const { height: deviceHeight, width: deviceWidth } = Dimensions.get('window');
    const [vehicles, setVehicles] = useState([]);
    const [defaultCar, setDefaultCar] = useState(null);
    const [processedUrls, setProcessedUrls] = useState({});
    const [isLoading, setIsLoading] = useState(false);

    const fetchData = useCallback(async () => {
        setIsLoading(true);
        try {
            const [carsResult, userInfoResult] = await Promise.all([
                chargeStationService.getUserCars(),
                authenticationService.getUserInfo()
            ]);
            let updatedVehicles = [...carsResult.data];

            for (let i = 0; i < updatedVehicles.length; i++) {
                const car = updatedVehicles[i];
                const processedUrl = await chargeStationService.getProcessedImageUrl(car.car_type.type_image_url);
                // console.log('processedUrl', processedUrl);
                updatedVehicles[i] = {
                    ...car,
                    processedImageUrl: processedUrl
                };
            }
            setVehicles(updatedVehicles);

            //all car data

            //find default from all car data
            const defaultCarId = userInfoResult.data.defaultCar.id;
            const defaultCar = updatedVehicles.find((car) => car.id === defaultCarId);
            setDefaultCar(defaultCar);

            //find processed Image urls
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setIsLoading(false);
        }
    }, []);

    function repeat(char, times) {
        return new Array(times + 1).join(char);
    }

    // Use the function

    useEffect(() => {
        fetchData();
    }, [fetchData]);

    const otherVehicles = vehicles.filter((car) => car.id !== defaultCar?.id);
    // console.log(repeat('-', 50));
    // console.log(otherVehicles);

    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={() => (router.canGoBack() ? router.back() : router.replace('/accountMainPage'))}
                    >
                        <CrossLogoSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginTop: 25, marginBottom: 10 }}>我的車輛</Text>
                </View>
                {isLoading ? (
                    <View className="flex flex-col justify-center items-center h-full  ">
                        <ActivityIndicator />
                    </View>
                ) : (
                    <>
                        <View className="items-center">
                            <Image
                                // source={require('../../assets/car.png')}
                                source={{ uri: defaultCar?.processedImageUrl }}
                                resizeMode="contain"
                                style={{ width: deviceWidth * 0.8, height: deviceHeight * 0.25 }}
                            />
                        </View>

                        {defaultCar && (
                            <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">{defaultCar.car_type.name}</Text>
                                    <Text className="text-lg text-[#888888]">{defaultCar.license_plate}</Text>
                                </View>
                            </View>
                        )}

                        <View className="w-full h-1 my-4 bg-[#DBE4E8]" />

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

                        {otherVehicles.map((car) => (
                            <VehicleRow
                                key={car.id}
                                car={car}
                                deviceHeight={deviceHeight}
                                deviceWidth={deviceWidth}
                                onPress={() =>
                                    router.push({
                                        pathname: 'manageVehiclePage',
                                        params: {
                                            carID: car.id,
                                            capacitance: car.car_type.capacitance,
                                            capacitance_unit: car.car_type.capacitance_unit,
                                            createdAt: car.car_type.createdAt,
                                            carModel: car.car_type.name,
                                            licensePlate: car.license_plate,
                                            carImage: car.processedImageUrl
                                        }
                                    })
                                }
                            />
                        ))}

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

export default MyVehiclePageComponent;
function repeat(arg0: string, arg1: number): any {
    throw new Error('Function not implemented.');
}
