import {
  Grid,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import DeleteIcon from "@material-ui/icons/Delete";
import clsx from "clsx";
import { Link } from "react-router-dom";
import { logger } from "../../services/monitoring";
import React, { useEffect, useState } from "react";
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 { DropDownList } from "../Controls/DropDownList";
import useStyles from "../useStyles";
import modelsTrimsYears from './modelsTrimsYears.json';

const tableColumns = [
  {
    id: "flashpack",
    label: "Flashpack Number",
  },
  {
    id: "os_version",
    label: "Part of OS Version",
  },
  {
    id: "car_model",
    label: "Model",
  },
  {
    id: "car_trim",
    label: "Trim",
  },
  {
    id: "car_year",
    label: "Year",
  },
  {
    id: "delete",
    label: "Delete",
  },
];

const PAGE_SIZE = "FLASHPACKS_TABLE_PAGE_SIZE";

const MainForm = () => {
  const classes = useStyles();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [rowToDelete, setRowToDelete] = useState({});
  const [model, setModel] = useLocalStorage("FLASHPACKS_MODEL", "Ocean");
  const [trim, setTrim] = useLocalStorage("FLASHPACKS_TRIM", "Sport");
  const [year, setYear] = useLocalStorage("FLASHPACKS_YEAR", 2024);
  const [trims, setTrims] = useLocalStorage("FLASHPACKS_TRIMS", modelsTrimsYears.oceanTrims);
  const [years, setYears] = useLocalStorage("FLASHPACKS_YEARS", modelsTrimsYears.oceanYears);
  const {
    getAllFlashpacks,
    flashpacks,
    totalFlashpacks,
    deleteFlashpackVersion,
  } = useVehicleContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

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

  useEffect(() => {
    loadFlashpacks(model, trim, year);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, pageIndex, pageSize]);

  const loadFlashpacks = async (model, trim, year) => {
    try {
      if (!token) return;
      await getAllFlashpacks(
        model,
        trim,
        year,
        {
          limit: pageSize,
          offset: pageSize * pageIndex,
        },
        token
      );
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const onModelChange = (event) => {
    let newModel = event.target.value

    setModel(newModel)

    switch (newModel) {
      case "Ocean":
        setTrims(modelsTrimsYears.oceanTrims);
        setYears(modelsTrimsYears.oceanYears);
        break;
      default:
        break;
    }

    if (trim && year) {
      loadFlashpacks(newModel, trim, year)
    }
  };

  const onTrimChange = (event) => {
    let newTrim = event.target.value

    setTrim(newTrim)

    if (model && year) {
      loadFlashpacks(model, newTrim, year)
    }
  };

  const onYearChange = (event) => {
    let newYear = event.target.value

    setYear(newYear)

    if (model && trim) {
      loadFlashpacks(model, trim, newYear)
    }
  };

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

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

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

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

        setMessage(`Deleted ${rowToDelete.car_year} ${rowToDelete.car_model} ${rowToDelete.car_trim} ${rowToDelete.flashpack}`);
        loadFlashpacks(model, trim, year);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    }
  };

  return (
    <div>
      <DropDownList label="Model" data={modelsTrimsYears.models} classes={classes} onChange={onModelChange} value={model} />
      <DropDownList label="Trim" data={trims} disabled={!model || !trims} classes={classes} onChange={onTrimChange} value={trim} />
      <DropDownList label="Year" data={years} disabled={!model || !years} classes={classes} onChange={onYearChange} value={year} />
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={clsx(classes.textJustifyAlign, classes.actionsBar)}>
          <Link to={`/tools/flashpack/add`} className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={"flashpack"}
          order={"desc"}
          columnData={tableColumns}
          onSortRequest={() => { return null }}
        />
        <TableBody>
          {flashpacks && flashpacks.map((row, index) => (
            <TableRow key={row.flashpack + row.car_model}>
              <TableCell align="center">
                <Link to={`/tools/flashpack/${row.car_model}/${row.car_trim}/${row.car_year}/${row.flashpack}`}>
                  {row.flashpack}
                </Link>
              </TableCell>
              <TableCell align="center">
                {row.os_version}
              </TableCell>
              <TableCell align="center">
                {row.car_model}
              </TableCell>
              <TableCell align="center">
                {row.car_trim}
              </TableCell>
              <TableCell align="center">
                {row.car_year}
              </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}`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete ${row.car_year} ${row.car_model} ${row.car_trim} ${row.flashpack}`} />
                  </IconButton>
                </RoleWrap>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {!flashpacks || flashpacks.length === 0 ? (
              <TableCell colSpan={8} align="center">No Flashpack Numbers</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={6}
                count={totalFlashpacks}
                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}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={sendDelete}
      />
    </div>
  );
};

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

export default Flashpacks;