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

import { hasRole, Permissions } from "../../../utils/roles";
import SelfServeTab from "../../CANSelfServe/SelfServeTab";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TabPanel from "../../Controls/TabPanel";
import useStyles from "../../useStyles";
import CANFiltersTab from "./CANFiltersTab";
import CANSignalsTab from "./CANSignalsTab";
import CarUpdatesTab from "./CarUpdatesTab";
import CarDetailsTab from "./DetailsTab";
import DigitalTwinTab from "./DigitalTwinTab";
import ECUsTab from "./ECUsTab";
import FleetsTab from "./FleetsTab";
import RemoteCommandsTab from "./RemoteCommandsTab";
import RemoteDiagnosticCommandsTab from "./RemoteDiagnosticCommands";
import TRexLogsTab from "./TRexLogsTab";
import DTCTimeline from "../../DTCTimeline/DTCTimeline";

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

const TabViews = [
  {
    label: "Details",
    component: CarDetailsTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "Car Updates",
    component: CarUpdatesTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "CAN Filters",
    component: CANFiltersTab,
    rolesPerProvider: Permissions.FiskerRead,
  },
  {
    label: "Digital Twin",
    component: DigitalTwinTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "CAN Signals",
    component: CANSignalsTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "T.Rex logs",
    component: TRexLogsTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "ECUs",
    component: ECUsTab,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  },
  {
    label: "Remote Commands",
    component: RemoteCommandsTab,
    rolesPerProvider: Permissions.FiskerMagnaCreate,
  },
  {
    label: "Remote Diagnostic Commands",
    component: RemoteDiagnosticCommandsTab,
    rolesPerProvider: Permissions.CarDiagnostic,
  },
  {
    label: "Fleets",
    component: FleetsTab,
    rolesPerProvider: Permissions.FiskerRead,
  },
  {
    label: "CAN Signal Export",
    component: SelfServeTab,
    rolesPerProvider: Permissions.FiskerRead,
  },

  {
    label: "DTC Timeline",
    component: DTCTimeline,
    rolesPerProvider: Permissions.FiskerMagnaRead,
  }

];

const filterTabs = (data, groups, providers) => {
  return data.reduce((result, item) => {
    if (hasRole(groups, item.rolesPerProvider, providers)) {
      result.push(item);
    }
    return result;
  }, []);
};

const CarStatus = () => {
  const { vin } = useParams();
  const classes = useStyles();
  const { setTitle, setSitePath } = useStatusContext();
  const { hash } = useLocation();
  const [tabIndex, setTabIndex] = useState(0);
  const [tabs, setTabs] = useState([]);
  const { groups, providers } = useUserContext();

  useEffect(() => {
    const data = filterTabs(TabViews, groups, providers);
    setTabs(data);
  }, [groups, providers]);

  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" }}
        justifyContent="center"
      >
        <Tabs
          value={tabIndex}
          onChange={handleTabChange}
          aria-label="car tabs"
          variant="scrollable"
          indicatorColor="secondary">
          {tabs.map((item, index) => <Tab key={index} label={item.label} {...tabProps(index)} />)}
        </Tabs>
      </Box>
      {tabs.map((item, index) => (
        <TabPanel
          key={index}
          value={tabIndex}
          index={index}
          className={classes.tabContainer}
        >
          <item.component vin={vin} />
        </TabPanel>
      ))}
    </div>
  );
};

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

export default CarStatus;
