import { useEffect, useState } from 'react';
import { Button, View } from 'react-native';
import { pickDirectory } from '@react-native-documents/picker'
import { List, Text } from 'react-native-paper';
import { Directory, Paths } from 'expo-file-system/next';
import { StorageAccessFramework } from 'expo-file-system';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';


const prettyName = (uri: string | null) => {
    if (!uri) return null;
    const decodedUri = decodeURIComponent(uri);
    const match = decodedUri.match(/.*\/primary:(.+)/);

    if (match) {
        return match[1];
    }

    // Fallback to your original logic
    return uri.split('%3A').pop() || "Unknown";

}

export default function SettingsScreen() {
    const [directoryUri, setDirectoryUri] = useState<string | null>(null);
    // Load saved directory URI on component mount
    useEffect(() => {
        const loadDirectoryUri = async () => {
            try {
                const savedUri = await AsyncStorage.getItem(DATA_DIRECTORY_URI_KEY);
                if (savedUri) {
                    setDirectoryUri(savedUri);
                }
            } catch (error) {
                console.error('Error loading directory URI:', error);
            }
        };

        loadDirectoryUri();
    }, []);

    // Save directory URI whenever it changes
    const saveDirectoryUri = async (uri: string | null) => {
        try {
            if (uri) {
                await AsyncStorage.setItem(DATA_DIRECTORY_URI_KEY, uri);
            } else {
                await AsyncStorage.removeItem(DATA_DIRECTORY_URI_KEY);
            }
            setDirectoryUri(uri);
        } catch (error) {
            console.error('Error saving directory URI:', error);
        }
    };

    return (
        <View style={{ flex: 1, padding: 16, backgroundColor: 'white' }}>
            <List.Section title="Data" style={{ backgroundColor: 'white', }} titleStyle={{ fontSize: 24, fontWeight: 'bold' }}>
                <List.Item
                    left={props => <List.Icon {...props} icon="folder" />}
                    title={prettyName(directoryUri) ?? "No directory selected. Tap to select."}
                    right={props => <List.Icon {...props} icon="chevron-right" />}

                    onPress={async () => {
                        try {
                            const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();
                            if (permissions.granted) {
                                await saveDirectoryUri(permissions.directoryUri);
                            }
                        } catch (err) {
                            console.error(err);
                        }
                    }}
                />
            </List.Section>
            <Button title="Debug: List Files" onPress={async () => {
                if (!directoryUri) {
                    console.warn("No directory set.");
                    return;
                }
                try {
                    const dir = await StorageAccessFramework.readDirectoryAsync(directoryUri);
                    console.log("Directory contents:", dir.map((file, i) => prettyName(file)));
                } catch (error) {
                    console.error("Error reading directory:", error);
                }
            }
            } />
        </View>
    )

}