import React, { useEffect } from "react";
import { useParams } from "react-router";
import { useLocation } from "react-router-dom";
import clsx from "clsx";
import { Box, Tab, Tabs } from "@material-ui/core";

import CarDetailsTab from "./DetailsTab";
import CarUpdatesTab from "./CarUpdatesTab";
import CANFiltersTab from "./CANFiltersTab";
import TabPanel from "../../Controls/TabPanel";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";

const tabHashes = ["details", "updates", "filters"];

const CarStatus = () => {
  const { vin } = useParams();
  const classes = useStyles();
  const { setTitle, setSitePath } = useStatusContext();
  const { hash } = useLocation();
  const [tabIndex, setTabIndex] = React.useState(0);

  useEffect(() => {
    const key = hash.replace("#", "");
    const index = tabHashes.findIndex((element) => element === key);
    if (index >= 0) setTabIndex(index);
  }, [hash]);

  useEffect(() => {
    const title = `Vehicle ${vin} Details`;
    setTitle(title);
    setSitePath([
      {
        label: "Vehicles",
        link: "/vehicles",
      },
      {
        label: title,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin]);

  const handleTabChange = (_event, newIndex) => {
    setTabIndex(newIndex);
  };

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Box
        className={classes.tableToolbar}
        sx={{ borderBottom: 1, borderColor: "divider" }}
      >
        <Tabs
          value={tabIndex}
          onChange={handleTabChange}
          aria-label="car tabs"
          indicatorColor="secondary"
        >
          <Tab label="Details" {...tabProps(0)} />
          <Tab label="Car Updates" {...tabProps(1)} />
          <Tab label="CAN Filters" {...tabProps(2)} />
        </Tabs>
      </Box>

      <TabPanel value={tabIndex} index={0}>
        <CarDetailsTab />
      </TabPanel>

      <TabPanel value={tabIndex} index={1}>
        <CarUpdatesTab />
      </TabPanel>

      <TabPanel value={tabIndex} index={2}>
        <CANFiltersTab />
      </TabPanel>
    </div>
  );
};

function tabProps(index) {
  return {
    id: `tab-${index}`,
    "aria-controls": `tabpanel-${index}`,
  };
}

export default CarStatus;
