/* eslint-disable react/jsx-key */
import React, { useEffect } from "react";
import { observer } from "mobx-react";
import {
  Card,
  CardActions,
  CardContent,
  createStyles,
  Grid,
  Typography,
  Badge,
  IconButton,
  Theme,
} from "@mui/material";
import { makeStyles, withStyles } from "@mui/styles";

import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import PrintIcon from "@mui/icons-material/Print";
import RemoveIcon from "@mui/icons-material/Remove";

import { nanoid } from "nanoid";
import { Link, useNavigate } from "react-router-dom";

import { ipcRenderer } from "electron";
import { toJS } from "mobx";
import { useTranslation } from "react-i18next";
import Basket from "../../models/Application/Basket";
import Ticket from "../../models/Application/Ticket";
import ComponentToShow from "../elements/print/ComponentToShow";
import { getRootStore } from "../../models/root-store.ts";

const StyledBadge = withStyles((theme: Theme) =>
  createStyles({
    badge: {
      right: -3,
      top: 13,
      border: `2px solid ${theme.palette.background.paper}`,
      padding: "0 4px",
    },
  })
)(Badge);

const useStyles = makeStyles({
  paper: {
    alignItems: "center",
    padding: 20,
    margin: 10,
  },
  root: {
    margin: 10,
    width: 250,
    maxWidth: 250,
    height: 260,
    maxHeight: 300,
  },
  rootBasket: {
    margin: 10,
    width: 200,
    maxWidth: 200,
    height: 300,
    maxHeight: 350,
  },
  typo: {
    marginLeft: 25,
    marginTop: 25,
    marginBottom: 10,
  },
  typoAmount: {
    marginLeft: 25,
    marginTop: 15,
    marginBottom: 10,
  },
  total: {
    marginLeft: 20,
    marginTop: 30,
    marginBottom: 10,
  },
  delete: {
    paddingTop: 20,
    marginRight: -15,
    marginBottom: -20,
    display: "flex",
    justifyContentContent: "flex-end",
  },
  pos: {
    marginBottom: 12,
  },
});

function BasketTicketView({ obj }: { obj: Ticket }) {
  const useStyleBackground = makeStyles({
    root: {
      margin: 10,
      paddingRight: 5,
      backgroundColor: obj.color,
      width: "90%",
    },
  });
  const backGroundColorCustom = useStyleBackground();
  const { t } = useTranslation();

  return (
    <Grid key={obj.id} item>
      <Card className={backGroundColorCustom.root} variant="outlined">
        <Grid
          container
          spacing={0}
          direction="row"
          alignItems="center"
          justifyContent="center"
          style={{
            margin: 0,
            marginLeft: 20,
            marginBottom: 0,
          }}
        >
          <Grid item xs={8}>
            {obj.price ? (
              <Typography variant="h6">€{obj.price}</Typography>
            ) : null}
          </Grid>
          <Grid item xs={4} />
        </Grid>
        <CardContent>
          <Grid
            container
            spacing={0}
            direction="column"
            alignItems="center"
            justifyContent="center"
            style={{
              marginTop: -25,
              marginLeft: -25,
              marginBottom: -40,
            }}
          >
            <ComponentToShow obj={obj} />
          </Grid>
        </CardContent>
        <CardActions>
          <Grid
            container
            spacing={0}
            direction="row"
            alignItems="center"
            justifyContent="center"
          >
            <Grid item xs={6} />
            <Grid item xs={6} />
          </Grid>
        </CardActions>
      </Card>
    </Grid>
  );
}

const BasketView = observer(({ basket }: { basket: Basket }) => {
  const classes = useStyles();
  const [rootStore] = React.useState(() => getRootStore());

  const sendToPrint = async () => {
    const constructedArr = basket.all.map((ticket) => {
      return ticket.returnAllJSON();
    });
    console.log("sending constructed array", constructedArr);
    return ipcRenderer.send("mainSendToPrint", constructedArr);
  };

  useEffect(() => {
    ipcRenderer.on("workerDoneLoading", (event) => {
      basket.clear();
    });
    return () => {
      ipcRenderer.removeAllListeners("workerDoneLoading");
    };
  });

  return (
    <>
      <Grid item xs={3}>
        <Typography
          className={classes.typo}
          style={{ color: rootStore.settings.darkMode ? "white" : "black" }}
          variant="h4"
        >
          Basket:
          <IconButton
            aria-label="removeBasket"
            onClick={() => basket.clear()}
            style={{ marginLeft: 30, color: "red" }}
          >
            <DeleteForeverIcon fontSize="large" />
          </IconButton>
          <StyledBadge badgeContent={basket.amount} color="primary">
            <IconButton
              aria-label="print"
              onClick={sendToPrint}
              color="primary"
              style={{ marginLeft: 20 }}
            >
              <PrintIcon fontSize="large" />
            </IconButton>
          </StyledBadge>
        </Typography>
      </Grid>
      <Grid item xs={5}>
        <Typography
          className={classes.total}
          style={{ color: rootStore.settings.darkMode ? "white" : "black" }}
          variant="h4"
        >
          Total price: €{basket.price}
        </Typography>
      </Grid>
      <Grid item xs={4} />
      {basket.allSorted.map((ticketsByType: any) => (
        <Grid key={nanoid()} item>
          <Card
            style={{
              backgroundColor: "#666666",
              marginTop: 10,
              marginLeft: 20,
            }}
          >
            <Typography className={classes.typoAmount} variant="h5">
              Amount: {ticketsByType.length}
              <IconButton
                onClick={() => basket.removeLast(ticketsByType[0].idModel)}
                style={{ color: "red", marginLeft: 80 }}
              >
                <RemoveIcon style={{ color: "red" }} fontSize="large" />
              </IconButton>
            </Typography>
            <Grid item xs={2} />
            <Grid item xs={12}>
              <BasketTicketView obj={ticketsByType[0]} />
            </Grid>
          </Card>
        </Grid>
      ))}
    </>
  );
});

export default BasketView;
