import {Colors, Picker, Text, TextField, View} from "react-native-ui-lib";
import React, {useEffect, useRef, useState} from "react";
import {ImageBackground, StyleSheet} from "react-native";
import {ScrollView} from "react-native-gesture-handler";
import {useAuthContext} from "@/contexts/AuthContext";
import {useUpdateUserData} from "@/hooks/firebase/useUpdateUserData";
import Ionicons from "@expo/vector-icons/Ionicons";
import * as tz from 'tzdata';
import * as Localization from 'expo-localization';
import debounce from "debounce";

const MyProfile = () => {
    const {user, profileData} = useAuthContext();

    const [timeZone, setTimeZone] = useState<string>(profileData?.timeZone! ?? Localization.getCalendars()[0].timeZone);
    const [lastName, setLastName] = useState<string>(profileData?.lastName || "");
    const [firstName, setFirstName] = useState<string>(
        profileData?.firstName || ""
    );

    const {mutateAsync: updateUserData} = useUpdateUserData();
    const isFirstRender = useRef(true);


    const handleUpdateUserData = async () => {
        await updateUserData({newUserData: {firstName, lastName, timeZone}});
    }

    const debouncedUserDataUpdate = debounce(handleUpdateUserData, 500);

    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }
        debouncedUserDataUpdate();
    }, [timeZone, lastName, firstName]);

    return (
        <ScrollView style={{paddingBottom: 100, flex: 1}}>
            <View style={styles.card}>
                <Text style={styles.subTit}>Your Profile</Text>
                <View row spread paddingH-15 centerV marginV-15>
                    <ImageBackground
                        style={styles.pfp}
                        source={require("../../../../assets/images/profile-picture.png")}
                    />

                    <Text style={styles.photoSet} color="#50be0c">
                        Change Photo
                    </Text>
                    <Text style={styles.photoSet}>Remove Photo</Text>
                </View>
                <View paddingH-15>
                    <Text text80 marginT-10 marginB-7 style={styles.label}>
                        First name
                    </Text>
                    <TextField
                        text70
                        placeholder="First name"
                        style={styles.txtBox}
                        value={firstName}
                        onChangeText={async (value) => {
                            setFirstName(value);
                        }}
                    />
                    <Text text80 marginT-10 marginB-7 style={styles.label}>
                        Last name
                    </Text>
                    <TextField
                        text70
                        placeholder="Last name"
                        style={styles.txtBox}
                        value={lastName}
                        onChangeText={async (value) => {
                            setLastName(value);
                        }}
                    />
                    <Text text80 marginT-10 marginB-7 style={styles.label}>
                        Email address
                    </Text>
                    <TextField
                        editable={false}
                        text70
                        placeholder="Email address"
                        value={user?.email?.toString()}
                        style={styles.txtBox}
                    />
                </View>
            </View>

            <View style={styles.card}>
                <Text style={styles.subTit}>Settings</Text>
                <Text style={styles.jakarta12}>Time Zone</Text>
                <View style={styles.viewPicker}>
                    <Picker
                        // editable={!isLoading}
                        value={timeZone}
                        onChange={(item) => {
                            setTimeZone(item as string)
                        }}
                        showSearch
                        floatingPlaceholder
                        style={styles.inViewPicker}
                        trailingAccessory={
                            <View style={{
                                justifyContent: "center",
                                alignItems: "center",
                                height: "100%",
                                marginTop: -38,
                                paddingRight: 15
                            }}>
                                <Ionicons name={"chevron-down"} style={{alignSelf: "center"}} size={20}
                                          color={"#000000"}/>
                            </View>
                        }
                    >
                        {timeZoneItems}
                    </Picker>
                </View>
            </View>
        </ScrollView>
    );
};

const timeZoneItems = Object.keys(tz.zones).sort().map((zone) => (
    <Picker.Item key={zone} label={zone.replace("/", " / ").replace("_", " ")} value={zone}/>
));

const styles = StyleSheet.create({
    card: {
        marginVertical: 15,
        backgroundColor: "white",
        width: "100%",
        borderRadius: 12,
        paddingHorizontal: 20,
        paddingVertical: 21,
    },
    pfp: {
        aspectRatio: 1,
        width: 65.54,
        backgroundColor: "green",
        borderRadius: 20,
    },
    txtBox: {
        backgroundColor: "#fafafa",
        borderRadius: 50,
        borderWidth: 2,
        borderColor: "#cecece",
        padding: 15,
        height: 45,
        fontFamily: "PlusJakartaSans_500Medium",
        fontSize: 13
    },
    subTit: {
        fontFamily: "Manrope_500Medium",
        fontSize: 15,
    },
    label: {
        fontFamily: "PlusJakartaSans_500Medium",
        fontSize: 12,
        color: "#a1a1a1"
    },
    photoSet: {
        fontFamily: "PlusJakartaSans_500Medium",
        fontSize: 13.07
    },
    jakarta12: {
        paddingVertical: 10,
        fontFamily: "PlusJakartaSans_500Medium",
        fontSize: 12,
        color: "#a1a1a1",
    },
    picker: {
        borderRadius: 50,
        paddingVertical: 12,
        paddingHorizontal: 16,
        backgroundColor: Colors.grey80,
        marginBottom: 16,
        borderColor: Colors.grey50,
        borderWidth: 1,
        marginTop: -20,
        height: 40,
        zIndex: 10,
    },
    viewPicker: {
        borderRadius: 50,
        backgroundColor: Colors.grey80,
        marginBottom: 16,
        borderColor: Colors.grey50,
        borderWidth: 1,
        marginTop: 0,
        height: 40,
        zIndex: 10,
    },
    inViewPicker: {
        borderRadius: 50,
        paddingVertical: 12,
        paddingHorizontal: 16,
        marginBottom: 16,
        marginTop: -20,
        height: 40,
        zIndex: 10,
    },
});

export default MyProfile;
