import { View, Text, ScrollView, Pressable, Alert } from 'react-native';
import React, { useContext, useEffect, useState } from 'react'; 
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { CrossLogoSvg } from '../global/SVG';
import { AuthContext } from '../../context/AuthProvider';
import NormalInput from '../global/normal_input';
import NormalButton from '../global/normal_button';
import { authenticationService } from '../../service/authService';
import * as SecureStore from 'expo-secure-store';
import { chargeStationService } from '../../service/chargeStationService';
import { User } from '../../types/user';
import { useTranslation } from '../../util/hooks/useTranslation';

const ChangeCarPageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [car, setCar] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const { t } = useTranslation();

    useEffect(() => {
        const getToken = async () => {
            const storedToken = await SecureStore.getItemAsync('accessToken');
            setToken(storedToken);
        };
        getToken();
    }, []);

    const validateLicensePlate = (licensePlate: string | null): string | null => {
        if (!licensePlate || licensePlate.trim() === '') {
            return t('accountSettings.change_car.enter_license_plate_error');
        }

        const trimmedPlate = licensePlate.trim();

        if (trimmedPlate.length < 2) {
            return t('accountSettings.change_car.license_plate_min_length');
        }

        if (trimmedPlate.length > 10) {
            return t('accountSettings.change_car.license_plate_max_length');
        }

        // Check for special characters (allow letters, numbers, hyphen, and spaces)
        const validFormat = /^[A-Za-z0-9-\s]+$/;
        if (!validFormat.test(trimmedPlate)) {
            return t('accountSettings.change_car.license_plate_invalid_format');
        }

        return null;
    };

    const saveLicensePlate = async (licensePlate: string | null) => {
        const validationError = validateLicensePlate(licensePlate);
        if (validationError) {
            setError(validationError);
            Alert.alert(t('common.error'), validationError);
            return;
        }

        try {
            const response = await chargeStationService.addCar(
                licensePlate!,
                '1834d087-bfc1-4f90-8f09-805e3d9422b5',
                'f599470d-53a5-4026-99c0-2dab34c77f39',
                true
            );
            if (response === true) {
                setError(null);
                Alert.alert(t('common.success'), t('accountSettings.change_car.save_success'), [
                    {
                        text: t('common.ok'),
                        onPress: () => router.replace('accountMainPage')
                    }
                ]);
                const newUser = {...user}
                newUser.car = car
                setUser({
                    ...newUser,
                } as User);
            } else {
                setError(t('accountSettings.change_car.save_failed'));
                Alert.alert(t('common.error'), t('accountSettings.change_car.save_failed'));
            }
        } catch (error) {
            setError(t('accountSettings.change_car.temporary_save_failed'));
            Alert.alert(t('common.error'), t('accountSettings.change_car.temporary_save_failed'));
        }
    };

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView className="flex-1 mx-[5%]">
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <CrossLogoSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginVertical: 25 }}>{t('accountSettings.change_car.change_license_plate_title')}</Text>
                    <Text className="text-xl ">{t('accountSettings.change_car.enter_new_license_plate')}</Text>
                    <View className="py-2">
                        <NormalInput
                            placeholder={t('accountSettings.change_car.enter_new_license_plate_placeholder')}
                            onChangeText={(t) => {
                                setCar(t);
                                setError(null); // Clear error when user types
                            }}
                            editable={!isLoading}
                        />
                        {error && <Text className="text-red-500 mt-1">{error}</Text>}
                    </View>
                    <NormalButton
                        title={<Text className="text-white">{isLoading ? t('accountSettings.change_car.changing') : t('common.confirm')}</Text>}
                        disabled={isLoading}
                        onPress={() => saveLicensePlate(car)}
                    />
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeCarPageComponent;