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 ContactDialog from './ContactDialog';
import AddIcon from '@mui/icons-material/Add';

function App() {
  const client = useAxios();
    const queryClient = useQueryClient()
    const [open, setOpen] = React.useState(false);
  const [openedContact, setOpenedContact] = React.useState({});
  const { data, status } = useQuery('contacts', async () => {
    const {data} = await client.get('/api/contacts');
    return data.map(({ 
      uid,
      first_name,
      last_name,
      middle_name,
      telephone,
      street,
      build,
      build_k,
      apartment
    }) => {
      return {
        'first_name': first_name,
        'last_name': last_name,
        'middle_name': middle_name,
        'telephone': telephone,
        'street': street,
        'build': build,
        'build_k': build_k,
        'apartment': apartment,
        'display_name': `${first_name} ${last_name} ${middle_name}`,
        'display_address': `${street} ${build} ${build_k} ${apartment}`,
        'uid': uid
      };
    })
  });
  const columns = [
    {
      name: "uid", label: "ID", options: {
        display: false
      }
    },
    {
      name: "display_name", label: "Имя"
    },
    {
      name: "telephone", label: "Телефон"
    },
    {
      name: "display_address", label: "Адрес"
    },
  ];

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

  const handleRowClick = (rowData) => {
    setOpenedContact(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
            }}
          />
      <ContactDialog 
        open={open}
        onClose={handleClose}
        contact={openedContact}
      />
    </Container>
  );

  function CustomToolbar() {
    if (data !== undefined) return (
      <Tooltip title='Новый контакт'>
        <IconButton onClick={() => {
          setOpenedContact({});
          setOpen(true);
        }}>
          <AddIcon />
        </IconButton>
      </Tooltip>
    )
    return (<></>)
  }
}
export default App;
