import { Grid } from "@material-ui/core";
import clsx from "clsx";
import React, { useEffect } from "react";

import { LocalDateTimeString } from "../../../../utils/dates";
import { logger } from "../../../../services/monitoring";
import { useStatusContext } from "../../../Contexts/StatusContext";
import { useUserContext } from "../../../Contexts/UserContext";
import {
  useIssueContext,
  IssueProvider
} from "../../../Contexts/IssueContext";
import useStyles from "../../../useStyles";

const MainForm = ({ id }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { issue, getIssue } = useIssueContext();

  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    (async () => {
      try {
        if (!id || !token) return;
        await getIssue(id, token);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);


  if (issue) {
    return (
      <div className={clsx(classes.paper, classes.tableSize)}>
        <Grid container className={classes.root} spacing={2}>
          <Grid item md={12} className={classes.textCenterAlign}>
            <p>
              <b>ID</b>: {id}
            </p>
            <p>
              <b>VIN</b>: {issue.vin}
            </p>
            <p>
              <b>Title</b>: {issue.title}
            </p>
            <p>
              <b>Description</b>: {issue.description}
            </p>
            <p>
              <b>timestamp</b>: {LocalDateTimeString(issue.timestamp)}
            </p>
            {issue.images && issue.images.map((image, index) => (
              <img key={image.id} src={`data:image/png;base64, ${image.image}`} alt="Issue images" />
            ))}
          </Grid>
        </Grid>
      </div>
    );
  } else {
    return <p>Loading...</p>;
  }

};

const IssueDetails = (props) => (
  <IssueProvider>
    <MainForm {...props} />
  </IssueProvider>
);

export default IssueDetails;
