import { useEffect, useRef, useState } from 'react';
import { read, utils, writeFile } from 'xlsx';
import Handsontable from 'handsontable';
import 'handsontable/dist/handsontable.css'
import './App.css';

function App() {
  const ref = useRef<HTMLDivElement>(null);
  const [hot, setHot] = useState<Handsontable>();

  useEffect(() => {
    if(!ref || !ref.current) return;
    const _hot = new Handsontable(ref.current, {
      data: [ ["Sheet", "JS", ""], ["Hands", "on", "Table"] ],
      rowHeaders: true, colHeaders: true, height: 600, width: 800
    });
    setHot(_hot);
    return () => { if(hot && !hot.isDestroyed) hot.destroy() };
  }, []);

  const fetchFile = async() => {
    const ab = await (await fetch("https://docs.sheetjs.com/pres.numbers")).arrayBuffer();
    const wb = read(ab);
    const ws = wb.Sheets[wb.SheetNames[0]];
    const aoa = utils.sheet_to_json<any[]>(ws, { header: 1 });
    hot.loadData(aoa);
  };

  const download = async() => {
    if(!hot) return;
    const ws = utils.aoa_to_sheet(hot.getData());
    const wb = utils.book_new(ws);
    writeFile(wb, "SheetJSHOT.xlsx");
  };

  return (
    <>
      <button onClick={fetchFile}>Fetch File</button>
      <button onClick={download}>Download</button>
      <div ref={ref}/>
    </>
  )
}

export default App
