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';
import { useFileSystem, prettyName } from '@/hooks/useFilesystem';


export default function SettingsScreen() {
    const { dataDirectoryUri, isLoading, files, hasDirectory, saveDataDirectoryUri } = useFileSystem();

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

}