import {useState, useEffect} from 'react';
import Checkbox from '@mui/material/Checkbox';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';
import DeleteIcon from '@mui/icons-material/Delete';
import { DateTimePicker } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';

import moment from 'moment';
import {get_registration_tokens, add_registration_token, delete_registration_token, unpack_api_result} from '../api/Api';

function AdminPanel(props) {

  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [registrationTokens, setRegistrationTokens] = useState([]);
  const [expires, setExpires] = useState(null);
  const [isSingleUse, setIsSingleUse] = useState(false);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };

  const refetchTokens = () => {
    if(props.user !== null) {
      unpack_api_result(get_registration_tokens(props.user.jwt), props.setFlash)
        .then(result => setRegistrationTokens(result.registration_tokens));
    }
  }

  const deleteToken = (id) => {
    if(props.user !== null) {
      unpack_api_result(delete_registration_token(props.user.jwt, id), props.setFlash)
        .then(() => refetchTokens())
    }
  }

  const handleAddToken = () => {
    let input = {
      single_use: isSingleUse,
      expires: expires,
    }

    if(props.user !== null) {
      unpack_api_result(add_registration_token(props.user.jwt, input), props.setFlash)
        .then(() => refetchTokens())
    }
  }

  useEffect(() => {
    refetchTokens()
  }, [])

  let columns = [
    {
      id: 'single_use', 
      label: 'Single Use',
      minWidth: 30,
      format: value => (value ? "Yes" : "No")
    },
    { id: 'token', label: 'Token', minwidht: 300},
    {
      id: 'expires',
      label: 'Expires',
      minwidth: 200,
      format: value => (moment(value).format('LL HH:mm'))
    },
    {
      id: 'delete_button',
      label: '',
      minwidth: 20,
    }
  ];

  return (
    <>
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <div className="Add-GameNight">
          <form autoComplete="off" onSubmit={e => { e.preventDefault(); }}>
            <DateTimePicker
              label="Gamenight date and time"
              variant="standard"
              value={expires}
              onChange={setExpires}
              inputFormat="dd-MM-yyyy HH:mm"
              renderInput={(params) => <TextField {...params} />}/> 
            
            <Checkbox 
              label="Single use"
              value={isSingleUse}
              onChange={(e) => setIsSingleUse(e.target.checked)}/>

            <Button 
              variant="outlined"
              color="success"
              onClick={handleAddToken}>
              Create
            </Button>
          </form>
        </div>
      </LocalizationProvider>

      <TableContainer sx={{ maxHeight: 440 }}>
        <Table stickyHeader>
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {registrationTokens
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map((row) => {
                return (
                  <TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
                    {columns.map((column) => {
                      const value = row[column.id];
                      return (
                        <TableCell key={column.id} align={column.align}>
                          {column.format
                            ? column.format(value)
                            : value}
                        </TableCell>
                      );
                    })}
                    <TableCell>
                      <IconButton 
                        edge="end"
                        color="error"
                        onClick={(e) => {
                          e.stopPropagation();
                          deleteToken(row.id)
                        }}>
          <DeleteIcon />
        </IconButton>
                    </TableCell>
                  </TableRow>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
      {registrationTokens.length > rowsPerPage && <TablePagination
        rowsPerPageOptions={[10, 25, 100]}
        component="div"
        count={registrationTokens.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}/>
      }
    </>
  );
}

export default AdminPanel
