import { Image } from 'expo-image';
import { Platform, RefreshControl, ScrollView, StyleSheet, useColorScheme, View, ViewToken } from 'react-native';

import { HelloWave } from '@/components/HelloWave';
import ParallaxScrollView from '@/components/ParallaxScrollView';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Card, FAB, IconButton, List, Surface, Text, useTheme } from 'react-native-paper';
import { useCallback, useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';
import { useNavigation } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useFileSystem, prettyName } from '@/hooks/useFilesystem';
import { format } from 'date-fns';
import { StorageAccessFramework } from 'expo-file-system';
import { FlatList } from 'react-native-gesture-handler';

export default function HomeScreen() {
  const navigation = useNavigation();
  const theme = useTheme();
  const { dataDirectoryUri, loadFiles, files, directorySize } = useFileSystem();
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = async () => {
    setRefreshing(true);
    await loadFiles();
    setRefreshing(false);
  };

  const styles = StyleSheet.create({
    fab: {
      position: 'absolute',
      margin: 16,
      right: 0,
      bottom: 0,
      backgroundColor: theme.colors.primary, // Use your theme's primary color
    },
    container: {
      backgroundColor: theme.colors.primary,
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      height: 100,
      zIndex: 1000,
    },
    safeArea: {
      flex: 1,
      marginTop: 100,
      backgroundColor: theme.colors.surface,
      // padding: 10
    },
    entryCard: {
      backgroundColor: theme.colors.surface,
      height: 150
      ,
      alignItems: 'center',
    },
  });
  const [loadedContents, setLoadedContents] = useState<Map<string, string>>(new Map());

  const loadFileContent = async (fileUri: string) => {
    if (loadedContents.has(fileUri)) return; // Already loaded

    try {
      // Replace with your actual file reading logic
      const content = await StorageAccessFramework.readAsStringAsync(fileUri);
      setLoadedContents(prev => new Map(prev).set(fileUri, content));
    } catch (error) {
      console.error('Error loading file content:', error);
    }
  };

  const onViewableItemsChanged = useCallback(({ viewableItems }: { viewableItems: ViewToken[] }) => {
    viewableItems.forEach(({ item }) => {
      loadFileContent(item.uri);
    });
  }, []);

  const viewabilityConfig = {
    itemVisiblePercentThreshold: 50, // Load when 50% visible
  };

  const renderFileItem = ({ item: f }: { item: typeof files[0] }) => (
    <View key={f.uri} style={styles.entryCard}>
      <View style={{
        width: '90%',
        height: '100%',
        paddingTop: 10,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.background,
      }}>
        <ThemedText style={{ fontWeight: "bold", marginBottom: 4 }}>
          {format(f.datetime, "hh:mm aaa")}
        </ThemedText>
        {loadedContents.has(f.uri) && (
          <ThemedText numberOfLines={3}>
            {loadedContents.get(f.uri)}
          </ThemedText>
        )}
      </View>
    </View>
  );

  return (
    <ThemedView style={{ flex: 1 }}>
      <View style={styles.container} />
      <SafeAreaView edges={['left', 'right']} style={styles.safeArea}>
        <FlatList
          data={files}
          renderItem={renderFileItem}
          keyExtractor={(item) => item.uri}
          onViewableItemsChanged={onViewableItemsChanged}
          viewabilityConfig={viewabilityConfig}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={onRefresh}
              tintColor={theme.colors.primary}
              colors={[theme.colors.primary]}
            />
          }
          ListHeaderComponent={
            <View style={{
              marginBottom: 16,
              backgroundColor: theme.colors.accent,
              padding: 2,
              paddingLeft: 10
            }}>
              <Text style={{ color: theme.colors.surface, fontSize: 10 }}>
                <Text style={{ fontWeight: "bold" }}>
                  {prettyName(dataDirectoryUri, { pathContext: 'full' })}:
                </Text>
                {' '}{files.length} {files.length == 1 ? "entry" : "entries"}, {directorySize} bytes
              </Text>
            </View>
          }
        />
        <FAB icon="plus" color={theme.colors.onPrimary} style={styles.fab} onPress={() => {
          navigation.navigate('NewEntry' as never);
        }} />
      </SafeAreaView>
    </ThemedView>
  );
}

