import * as React from 'react';
import Grid from '@mui/material/Grid';
import { Container, Dialog, Typography, IconButton, Tooltip } from '@mui/material';
import MUIDataTable from "mui-datatables";
import { useAxios } from './axios';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import StudentDialog from './StudentDialog';
import AddIcon from '@mui/icons-material/Add';

function App() {
  const client = useAxios();
    const queryClient = useQueryClient()
    const [open, setOpen] = React.useState(false);
  const [openedStudent, setOpenedStudent] = React.useState({});
  const { data, status } = useQuery('students', async () => {
    const {data} = await client.get('/api/students');
    return data.map(({
      uid,
      first_name,
      last_name,
      middle_name,
      discipline,
      mark,
    }) => {
      return {
        'first_name': first_name,
        'last_name': last_name,
        'middle_name': middle_name,
        'discipline': discipline,
        'mark': mark,
        'display_name': `${first_name} ${last_name} ${middle_name}`,
        'uid': uid
      };
    })
  });
  const columns = [
    {
      name: "uid", label: "ID", options: {
        display: false
      }
    },
    {
      name: "display_name", label: "Имя"
    },
    {
      name: "mark", label: "Оценка"
    },
    {
      name: "discipline", label: "Дисциплина"
    },
  ];

  const commitDelete = useMutation(async (uid) => {
    await client.delete(`/api/students/${uid}`);
  }, {
    onSuccess: () => {
      queryClient.invalidateQueries('students');
    }
  });

  const handleRowClick = (rowData) => {
    setOpenedStudent(data.find(({uid}) => uid === rowData[0]));
    setOpen(true);
    console.log(data.find(({uid}) => uid === rowData[0]));
  };

  const handleRowsDelete = (rowsDeleted) => {
    const uids = rowsDeleted.data.map(({dataIndex}) => data[dataIndex]['uid']);
    for (const uid of uids) {
      commitDelete.mutate(uid);
    }
  };

  const handleClose = () => {
    setOpen(false);
  };

  if (data === undefined || status === 'loading') {
    return <div>Loading...</div>
  }
  return (
    <Container maxWidth="md">
          <MUIDataTable
            title={"Зачётная книжка"}
            data={data}
            columns={columns}
            options={{
              filterType: "textField",
              print: false,
              rowsPerPage: 10,
              rowsPerPageOptions: [10, 20, 50, 100],
              onRowClick: handleRowClick,
              customToolbar: () => {
                return <CustomToolbar />
              },
              onRowsDelete: handleRowsDelete
            }}
          />
      <StudentDialog
        open={open}
        onClose={handleClose}
        student={openedStudent}
      />
    </Container>
  );

  function CustomToolbar() {
    if (data !== undefined) return (
      <Tooltip title='Новая запись'>
        <IconButton onClick={() => {
          setOpenedStudent({});
          setOpen(true);
        }}>
          <AddIcon />
        </IconButton>
      </Tooltip>
    )
    return (<></>)
  }
}
export default App;
