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 FleetDetailsTab from "./DetailsTab";
import FleetVehiclesTab from "./VehiclesTab";
import FleetCANFiltersTab from "./CANFiltersTab";
import TabPanel from "../../Controls/TabPanel";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";

const tabHashes = [
  "details",
  "vehicles",
  "filters"
]

const FleetStatus = () => {
  const { name } = 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 = `Fleet ${name} Details`;
    setTitle(title);
    setSitePath([
      {
        label: "Fleets",
        link: "/fleets",
      },
      {
        label: title,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [name]);

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

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

      <TabPanel value={tabIndex} index={0} className={classes.fullWidth}>
        <FleetDetailsTab />
      </TabPanel>

      <TabPanel value={tabIndex} index={1} className={classes.fullWidth}>
        <FleetVehiclesTab />
      </TabPanel >

      <TabPanel value={tabIndex} index={2} className={classes.fullWidth}>
        <FleetCANFiltersTab />
      </TabPanel>
    </div >
  );
};

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

export default FleetStatus;
