import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
  Grid,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import { logger } from "../../../services/monitoring";
import DeleteIcon from "@material-ui/icons/Delete";
import clsx from "clsx";
import { Link } from "react-router-dom";
import { useVehicleContext, VehicleProvider } from "../../Contexts/VehicleContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import DeleteConfirmation from "../../DeleteConfirmation";
import { RoleWrap } from "../../Controls/RoleWrap";
import useStyles from "../../useStyles";

const tableColumns = [
  {
    id: "car_ecu_name",
    label: "ECU Name",
  },
  {
    id: "car_ecu_version",
    label: "ECU Version",
  },
  {
    id: "delete",
    label: "Delete",
  },
];

const PAGE_SIZE = "FLASHPACK_MAPPINGS_TABLE_PAGE_SIZE";

const MainForm = () => {
  const { model, trim, year, flashpack } = useParams();
  const classes = useStyles();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("flashpack");
  const [order, setOrder] = useState("desc");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [rowToDelete, setRowToDelete] = useState({});
  const {
    getFlashpackECUMappings,
    flashpackECUMappings,
    totalFlashpackECUMappings,
    deleteFlashpackVersionECUMapping,
  } = useVehicleContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  useEffect(() => {
    setTitle(`${year} ${model} ${trim} Flashpack Version ${flashpack}`);
    setSitePath([
      {
        label: "Tools",
        link: "/tools/flashpacks",
      },
      {
        label: "Flashpack Versions",
        link: "/tools/flashpacks",
      },
      {
        label: `Flashpack ${flashpack}`,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    loadFlashpackECUMappings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, pageIndex, pageSize, orderBy, order]);

  const loadFlashpackECUMappings = async () => {
    try {
      if (!token) return;
      await getFlashpackECUMappings(
        model,
        trim,
        year,
        flashpack,
        {
          limit: pageSize,
          offset: pageSize * pageIndex,
          order: `${orderBy} ${order}`,
        },
        token
      );
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const handleChangePageIndex = (event, newIndex) => {
    setPageIndex(newIndex);
  };

  const handleChangePageSize = (event) => {
    setPageSize(parseInt(event.target.value, 10));
    setPageIndex(0);
  };

  const handleSort = (event, property) => {
    try {
      if (property === orderBy) {
        if (order === "asc") {
          setOrder("desc");
        } else {
          setOrder("asc");
        }
      } else {
        setOrderBy(property);
        setOrder("asc");
      }
    } catch (e) {
      logger.warn(e.stack);
    }
  };

  const onDeleteClick = (row) => {
    setRowToDelete(row);
    setShowDeleteModal(true);
  }

  const sendDelete = async () => {
    if (rowToDelete) {
      try {
        const result = await deleteFlashpackVersionECUMapping(rowToDelete.car_model, rowToDelete.car_trim, rowToDelete.car_year, rowToDelete.flashpack, rowToDelete.car_ecu_name, rowToDelete.car_ecu_version, token);
        if (!result || result.error) return;

        setMessage(`Deleted ${rowToDelete.car_year} ${rowToDelete.car_model} ${rowToDelete.car_trim} ${rowToDelete.flashpack} ${rowToDelete.car_ecu_name} ${rowToDelete.car_ecu_version}`);
        loadFlashpackECUMappings();
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    }
  };

  return (
    <div>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={clsx(classes.textJustifyAlign, classes.actionsBar)}>
          <Link to={`/tools/flashpackadd/${model}/${trim}/${year}/${flashpack}`} className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {flashpackECUMappings && flashpackECUMappings.map((row, index) => (
            <TableRow key={index}>
              <TableCell align="center">
                {row.car_ecu_name}
              </TableCell>
              <TableCell align="center">
                {row.car_ecu_version}
              </TableCell>
              <TableCell align="center">
                <RoleWrap
                  groups={groups}
                  providers={providers}
                  rolesPerProvider={Permissions.FiskerDelete}
                >
                  <IconButton
                    onClick={() => onDeleteClick(row)}
                    aria-label={`Send delete for ${row.car_year} ${row.car_model} ${row.car_trim} ${row.flashpack} ${row.car_ecu_name} ${row.car_ecu_version}`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete ${row.car_year} ${row.car_model} ${row.car_trim} ${row.flashpack} ${row.car_ecu_name} ${row.car_ecu_version}`} />
                  </IconButton>
                </RoleWrap>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {!flashpackECUMappings || flashpackECUMappings.length === 0 ? (
              <TableCell colSpan={8} align="center">No Flashpack ECU Mappings</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={3}
                count={totalFlashpackECUMappings}
                rowsPerPage={pageSize}
                page={pageIndex}
                SelectProps={{
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                }}
                onPageChange={handleChangePageIndex}
                onRowsPerPageChange={handleChangePageSize}
              />)}
          </TableRow>
        </TableFooter>
      </Table>
      <DeleteConfirmation
        message={rowToDelete && rowToDelete.car_year + " " + rowToDelete.car_model + " " + rowToDelete.car_trim + " " + rowToDelete.flashpack + " " + rowToDelete.car_ecu_name + " " + rowToDelete.car_ecu_version}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={sendDelete}
      />
    </div>
  );
};

const FlashpackDetails = () => (
  <VehicleProvider>
    <MainForm />
  </VehicleProvider>
);

export default FlashpackDetails;