import {useState, useEffect} from "react";
import {
    StyleSheet,
    Platform,
    ScrollView,
    KeyboardAvoidingView,
    View,
    ActivityIndicator,
} from "react-native";
import {TextInput, Button, Snackbar, useTheme} from "react-native-paper";
import {useLocalSearchParams, useRouter} from "expo-router";
import useLocationStore from "@/locationStore";

export default function EditLocation() {
    const theme = useTheme();
    const {id} = useLocalSearchParams();
    const router = useRouter();
    const [loading, setLoading] = useState(true);
    const [formData, setFormData] = useState({
        name: "",
        description: "",
        image: "",
        area: "",
        population: "",
        longitude: "",
        latitude: "",
    });

    const [message, setMessage] = useState("");
    const [visible, setVisible] = useState(false);

    const updateLocation = useLocationStore((state) => state.updateLocation);
    const getLocation = useLocationStore((state) => state.getLocation);

    useEffect(() => {
        const data = getLocation(id);
        if (data) {
            setFormData({
                name: data.name,
                description: data.description,
                image: data.image,
                area: data.area.toString(),
                population: data.population.toString(),
                longitude: data.longitude.toString(),
                latitude: data.latitude.toString(),
            });
        }
        setLoading(false);
    }, [id, getLocation]);

    const handleEditLocation = async () => {
        if (
            formData.name &&
            formData.description &&
            formData.image &&
            formData.area &&
            formData.population &&
            formData.longitude &&
            formData.latitude
        ) {
            // console.log("Form data:", formData);
            const response = await updateLocation(id, {
                name: formData.name,
                description: formData.description,
                image: formData.image,
                area: parseFloat(formData.area),
                population: parseInt(formData.population, 10),
                longitude: parseFloat(formData.longitude),
                latitude: parseFloat(formData.latitude),
            });

            if (response) {
                setMessage("Lokalizacja została zaktualizowana!");
                setVisible(true);
                // while (router.canGoBack()) {
                // Pop from stack until one element is left
                // router.back();
                // }
                setTimeout(() => {
                    router.replace("/");
                }, 300); // Replace the last remaining stack element
            } else {
                setMessage("Wystąpił błąd podczas aktualizacji lokalizacji!");
                setVisible(true);
            }
        } else {
            setMessage("Wypełnij wszystkie pola!");
            setVisible(true);
        }
    };

    if (loading) {
        return (
            <View
                style={[styles.container, {backgroundColor: theme.colors.background}]}
            >
                <ActivityIndicator size="large" color={theme.colors.primary}/>
            </View>
        );
    }

    return (
        <KeyboardAvoidingView
            style={{flex: 1}}
            behavior={Platform.OS === "ios" ? "padding" : "height"}
        >
            <ScrollView contentContainerStyle={styles.container}>
                <Snackbar
                    visible={visible}
                    onDismiss={() => setVisible(false)}
                    duration={3000}
                >
                    {message}
                </Snackbar>
                <TextInput
                    mode="outlined"
                    label="Nazwa"
                    placeholder="Wpisz nazwę"
                    style={{margin: 10, width: "100%"}}
                    value={formData.name}
                    onChangeText={(e) => setFormData({...formData, name: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Opis"
                    placeholder="Wpisz opis"
                    style={{margin: 10, width: "100%"}}
                    multiline={true}
                    value={formData.description}
                    onChangeText={(e) => setFormData({...formData, description: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Link do zdjęcia"
                    multiline={true}
                    placeholder="Wpisz link do zdjęcia"
                    style={{margin: 10, width: "100%"}}
                    value={formData.image}
                    onChangeText={(e) => setFormData({...formData, image: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Powierzchnia"
                    placeholder="Wpisz powierzchnię"
                    style={{margin: 10, width: "100%"}}
                    value={formData.area}
                    keyboardType="numbers-and-punctuation"
                    onChangeText={(e) => setFormData({...formData, area: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Ludność"
                    placeholder="Wpisz liczbę ludności"
                    style={{margin: 10, width: "100%"}}
                    value={formData.population}
                    keyboardType="numeric"
                    onChangeText={(e) => setFormData({...formData, population: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Długość geograficzna"
                    placeholder="Wpisz długość geograficzną"
                    style={{margin: 10, width: "100%"}}
                    value={formData.longitude}
                    keyboardType="numbers-and-punctuation"
                    onChangeText={(e) => setFormData({...formData, longitude: e})}
                />
                <TextInput
                    mode="outlined"
                    label="Szerokość geograficzna"
                    placeholder="Wpisz szerokość geograficzną"
                    style={{margin: 10, width: "100%"}}
                    value={formData.latitude}
                    keyboardType="numbers-and-punctuation"
                    onChangeText={(e) => setFormData({...formData, latitude: e})}
                />
                <Button
                    style={{margin: 10, width: "100%"}}
                    icon="plus-circle-outline"
                    mode={"contained"}
                    onPress={handleEditLocation}
                >
                    Edytuj
                </Button>
            </ScrollView>
        </KeyboardAvoidingView>
    );
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: "#25292e",
        justifyContent: "flex-start",
        alignItems: "center",
        flexGrow: 1,
    },
});
