import React, {useState} from 'react';
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform, KeyboardAvoidingView} from 'react-native';
import {useAuthStore} from '@/store/authStore';
import {useRouter} from 'expo-router';

import {Box} from "@/components/ui/box"
import {Button, ButtonText, ButtonIcon} from "@/components/ui/button"
import {ArrowRightIcon, EyeIcon, EyeOffIcon} from "@/components/ui/icon"
import {Center} from "@/components/ui/center"
import {Heading} from "@/components/ui/heading"
import {Input, InputField, InputIcon, InputSlot} from "@/components/ui/input"
import {VStack} from "@/components/ui/vstack"
import {Text} from "@/components/ui/text";

export default function Registration() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [emailError, setEmailError] = useState('');
    const [showPassword, setShowPassword] = useState(false)
    const {signUp, isLoading} = useAuthStore();
    const router = useRouter();

    const handleInternalRegistration = async () => {
        if (!email || !password || !firstName || !lastName) {
            alert('Proszę uzupełnić wszystkie pola');
            return;
        }

        if (!validateEmail(email)) {
            setEmailError('Nieprawidłowy format adresu email');
            return;
        }

        try {
            await signUp({email, password, firstName, lastName});
            alert(`Zalogowano jako ${email}`);
            router.replace('/');
        } catch (e) {
            alert("Błąd logowania: " + (e.response?.data?.message || e.message));
        }
    }

    const validateEmail = (email) => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    };

    const handleShowPassword = () => {
        setShowPassword((showState) => {
            return !showState
        })
    }

    if (isLoading) {
        return (
            <View style={styles.container}>
                <ActivityIndicator size="large"/>
            </View>
        );
    }

    return (
        <KeyboardAvoidingView
            behavior={Platform.OS === "ios" ? "padding" : "height"}
            style={{flex: 1}}
            keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
        >
            <SafeAreaView style={styles.container}>
                <Center>

                    <Box className="p-5 w-[80%] border border-background-300 rounded-lg">
                        <VStack className="pb-4" space="xs">
                            <Heading className="leading-[30px]">Rejestracja</Heading>
                            <Box className="flex flex-row">
                                {/* <Link href="/login" asChild> */}
                                <Button variant="link" size="sm" className="p-0"
                                        onPress={() => router.replace("/login")}>
                                    <ButtonText style={styles.signupbutton}>Masz już konto? Zaloguj się!</ButtonText>
                                    <ButtonIcon className="mr-1" size="md" as={ArrowRightIcon}/>
                                </Button>
                                {/* </Link>  */}
                            </Box>
                        </VStack>
                        <VStack space="xl" className="py-2">
                            {emailError ? <Text className="m-0 color-red-600">{emailError}</Text> : null}
                            <Input isRequired={true}>
                                <InputField type="email" className="py-2" placeholder="E-mail"
                                            onChangeText={(text) => {
                                                setEmail(text);
                                                if (text && !validateEmail(text)) {
                                                    setEmailError('Nieprawidłowy format adresu email');
                                                } else {
                                                    setEmailError('');
                                                }
                                            }}
                                />
                            </Input>
                            <Input isRequired={true}>
                                <InputField className="py-2" placeholder="Imię" onChangeText={setFirstName}/>
                            </Input>
                            <Input isRequired={true}>
                                <InputField className="py-2" placeholder="Nazwisko" onChangeText={setLastName}/>
                            </Input>
                            <Input isRequired={true}>
                                <InputField type={showPassword ? "text" : "password"} className="py-2"
                                            placeholder="Hasło"
                                            onChangeText={setPassword}/>
                                <InputSlot className="pr-3" onPress={handleShowPassword}>
                                    <InputIcon as={showPassword ? EyeIcon : EyeOffIcon}/>
                                </InputSlot>
                            </Input>
                        </VStack>
                        <VStack space="lg" className="pt-4">
                            <Button size="sm" onPress={handleInternalRegistration}>
                                <ButtonText>Zarejestruj się</ButtonText>
                            </Button>
                        </VStack>
                    </Box>

                </Center>
            </SafeAreaView>
        </KeyboardAvoidingView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    formContainer: {
        width: '80%',
    },
    input: {
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 5,
        marginBottom: 15,
        padding: 10,
    },
    errorText: {
        color: 'red',
        marginBottom: 10,
    },
    signupbutton: {
        fontWeight: '300',
        textAlign: 'left',
    },
});