import React, { useEffect, useState } from "react";
import {
  Backdrop,
  Modal,
  Fade,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
} from "@material-ui/core";

import useStyles from "../../useStyles";
import { useUpdatesContext } from "../../Contexts/UpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { LocalDateTimeString } from "../../../utils/dates";

export default function CarStatusModal(props) {
  const classes = useStyles();
  const [updates, setUpdates] = useState([]);
  const { setMessage } = useStatusContext();
  const { getVINUpdates } = useUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    (async () => {
      try {
        if (!props.vin) return;
        const result = await getVINUpdates(props.vin, token);
        if (result.error) {
          throw new Error(`Get VIN updates error. ${result.message}`);
        } else {
          setUpdates(result.data);
        }
      } catch (e) {
        setMessage(e.message);
      }
    })();
    // eslint-disable-next-line
  }, [props.vin]);
  return (
    <div>
      <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        className={classes.modal}
        open={props.vin !== null && props.vin !== undefined}
        onClose={props.handleClose}
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500,
        }}
      >
        <Fade in={props.vin}>
          <div className={classes.modaldialog}>
            <h2 id="transition-modal-title">{props.vin} Updates</h2>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell align="center">Date</TableCell>
                  <TableCell align="center">Update</TableCell>
                  <TableCell align="center">Status</TableCell>
                  <TableCell align="center">Updated</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {updates.map((update) => (
                  <TableRow key={update.id}>
                    <TableCell align="center">
                      {LocalDateTimeString(update.created)}
                    </TableCell>
                    <TableCell align="center">{`${update.updatepackage.package_name} ${update.updatepackage.version}`}</TableCell>
                    <TableCell align="center">{update.status}</TableCell>
                    <TableCell align="center">
                      {LocalDateTimeString(update.updated)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </Fade>
      </Modal>
    </div>
  );
}
