import { TableContainer, Table, TableRow, TableCell, TableBody, TableHead } from '@mui/material';
import { WorkBook, WorkSheet, read, utils, writeFileXLSX } from "xlsx";
import { useRef, useState, useEffect } from "react";

import './App.css'

interface President {
  Name: string;
  Index: number;
}

function App() {
  const tbl = useRef<HTMLTableElement>(null);
  const xport = () => {
    const wb: WorkBook = utils.table_to_book(tbl.current);
    writeFileXLSX(wb, "SheetJSMaterialUI.xlsx");
  };

  const [pres, setPres] = useState<President[]>([]);
  useEffect(() => {
    let active = true;
    (async() => {
      const ab: ArrayBuffer = await (await fetch("https://docs.sheetjs.com/pres.xlsx")).arrayBuffer();
      const wb: WorkBook = read(ab);
      const ws: WorkSheet = wb.Sheets[wb.SheetNames[0]];
      const aoo: President[] = utils.sheet_to_json<President>(ws);
      if(active) setPres(aoo);
    })();
    return () => { active = false };
  }, []);

  return ( <>
    <button onClick={xport}>Export</button>
    <TableContainer><Table ref={tbl}>
      <TableHead><TableRow><TableCell>Name</TableCell><TableCell>Index</TableCell></TableRow></TableHead>
      <TableBody>
      {pres.map((row, idx) => (
        <TableRow key={idx}>
          <TableCell>{row.Name}</TableCell>
          <TableCell>{row.Index}</TableCell>
        </TableRow>
      ))}
      </TableBody>
    </Table></TableContainer>
  </> );
}

export default App