import React, { useState, type Node } from 'react';
import { SafeAreaView, ScrollView, StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import { read, utils, version } from 'xlsx';
import { getEnforcing } from 'react-native/Libraries/TurboModule/TurboModuleRegistry';
const DocumentPicker = getEnforcing('DocumentPicker');

const App: () => Node = () => {

  const [ aoa, setAoA ] = useState(["SheetJS".split(""), "5433795".split("")]);

  return (
    <SafeAreaView style={styles.outer}>
      <Text style={styles.title}>SheetJS × React Native Windows {version}</Text>
      <TouchableHighlight onPress={async() => {
        try {
          const b64 = await DocumentPicker.PickAndRead();
          const wb = read(b64);
          setAoA(utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { header: 1 } ));
        } catch(err) { alert(`Error: ${err.message}`); }
      }}><Text style={styles.button}>Click here to Open File!</Text></TouchableHighlight>
      <ScrollView contentInsetAdjustmentBehavior="automatic">
        <View style={styles.table}>{aoa.map((row,R) => (
          <View style={styles.row} key={R}>{row.map((cell,C) => (
            <View style={styles.cell} key={C}><Text>{cell}</Text></View>
          ))}</View>
        ))}</View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  cell: { flex: 4 },
  row: { flexDirection: 'row', justifyContent: 'space-evenly', padding: 10, backgroundColor: 'white', },
  table: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', },
  outer: { marginTop: 32, paddingHorizontal: 24, },
  title: { fontSize: 24, fontWeight: '600', },
  button: { marginTop: 8, fontSize: 18, fontWeight: '400', },
});

export default App;