import AsyncStorage from "@react-native-async-storage/async-storage";
import { useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    Alert,
    ImageBackground,
    KeyboardAvoidingView,
    Platform,
    ScrollView,
    Text,
    TextInput,
    TouchableOpacity,
    View
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { styles } from "./styles";

const converterBgImage = require("../assets/images/todo.png");

export default function CoordinateConverter() {
    const router = useRouter();
    const [todos, setTodos] = useState<string[]>([]);
    const [newTodo, setNewTodo] = useState<string>("");

    // Define a unique key for AsyncStorage
    const STORAGE_KEY = "@my_todo_list";

    // --- Persistence Logic ---
    useEffect(() => {
        loadTodos();
    }, []);
    useEffect(() => {
        saveTodos();
    }, [todos]);

    // Async function to load todos from AsyncStorage
    const loadTodos = async () => {
        try {
            const jsonValue = await AsyncStorage.getItem(STORAGE_KEY);
            if (jsonValue != null) {
                const parsedTodos = JSON.parse(jsonValue);
                if (Array.isArray(parsedTodos)) {
                    setTodos(parsedTodos);
                } else {
                    console.warn("Loaded data is not an array, initializing empty todo list.");
                    setTodos([]);
                }
            }
        } catch (e) {
            console.error("Failed to load todos:", e);
            Alert.alert("Error", "Failed to load your todo list.");
        }
    };

    // Async function to save todos to AsyncStorage
    const saveTodos = async () => {
        try {
            const jsonValue = JSON.stringify(todos);
            await AsyncStorage.setItem(STORAGE_KEY, jsonValue);
        } catch (e) {
            console.error("Failed to save todos:", e);
            Alert.alert("Error", "Failed to save your todo list.");
        }
    };

    const addTodo = () => {
        if (newTodo.trim().length > 0) {
            setTodos((prevTodos) => [...prevTodos, newTodo.trim()]);
            setNewTodo("");
        }
    };

    const removeTodo = (index: number) => {
        const todoToRemove = todos[index];

        Alert.alert(
            "Delete Todo",
            `Are you sure you want to delete "${todoToRemove}"?`,
            [
                {
                    text: "Cancel",
                    onPress: () => console.log("Delete Cancelled"),
                    style: "cancel"
                },
                {
                    text: "Delete",
                    onPress: () => {
                        const updatedTodos = todos.filter((_, i) => i !== index);
                        setTodos(updatedTodos);
                        console.log("Todo deleted:", todoToRemove);
                    },
                    style: "destructive"
                }
            ],
            { cancelable: true }
        );
    };

    return (
        <View style={styles.converterScreenRoot}>
            <ImageBackground
                source={converterBgImage}
                style={styles.converterBackgroundImage}
                resizeMode="cover"
            >
                <View style={styles.converterBackgroundOverlay} />
            </ImageBackground>

            <SafeAreaView style={styles.converterContentWrapper}>
                <KeyboardAvoidingView
                    style={styles.converterContainer}
                    behavior={Platform.OS === "ios" ? "padding" : "height"}
                >
                    <ScrollView
                        contentContainerStyle={styles.converterScrollContent}
                    >
                        {/* Custom Back Button */}
                        <TouchableOpacity
                            onPress={() => router.back()}
                            style={styles.backButton}
                        >
                            <Text style={styles.backButtonText}>
                                ← Go Back
                            </Text>
                        </TouchableOpacity>

                        <Text style={styles.converterTitle}>Todo List</Text>

                        {/* Todo Input Section */}
                        <View style={styles.todoInputContainer}>
                            <TextInput
                                style={styles.todoInputField}
                                placeholder="Add a new todo..."
                                placeholderTextColor="#666"
                                value={newTodo}
                                onChangeText={setNewTodo}
                                onSubmitEditing={addTodo}
                            />
                            <TouchableOpacity
                                onPress={addTodo}
                                style={styles.addTodoButton}
                            >
                                <Text style={styles.addTodoButtonText}>
                                    Add
                                </Text>
                            </TouchableOpacity>
                        </View>

                        {/* Todo List Display */}
                        <View style={styles.todoListContainer}>
                            {todos.length === 0 ? (
                                <Text style={styles.placeholderText}>
                                    Your todo list is empty. Add some tasks!
                                </Text>
                            ) : (
                                todos.map((todo, index) => (
                                    <View key={index} style={styles.todoItem}>
                                        <Text style={styles.todoText}>
                                            {todo}
                                        </Text>
                                        <TouchableOpacity
                                            onPress={() => removeTodo(index)}
                                            style={styles.removeTodoButton}
                                        >
                                            <Text
                                                style={styles.removeTodoButtonText}
                                            >
                                                X
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                ))
                            )}
                        </View>
                    </ScrollView>
                </KeyboardAvoidingView>
            </SafeAreaView>
        </View>
    );
}