import * as React from "react";
import { styled } from "@mui/material/styles";
import Tabs, { TabsProps } from "@mui/material/Tabs";
import Tab, { TabProps } from "@mui/material/Tab";
import Box from "@mui/material/Box";
import AutoGraphIcon from "@mui/icons-material/AutoGraph";
import { useRouter as useNextRouter } from "next/router";

import type { NavItemType } from "@/components/Layout2/_config";

const AntTabs = styled(Tabs)({
  // borderBottom: "1px solid #e8e8e8",
  minHeight: 0,
  "& .MuiTabs-indicator": {
    display: "none",
    backgroundColor: "#1890ff",
  },
  "& .MuiTabs-indicatorSpan": {
    display: "none",
  },
});

const AntTab = styled((props: StyledTabProps) => (
  <Tab disableRipple {...props} />
))(({ theme }) => ({
  textTransform: "none",
  minWidth: 0,
  minHeight: 0,
  [theme.breakpoints.up("sm")]: {
    minWidth: 0,
  },
  fontWeight: theme.typography.fontWeightMedium,
  fontFamily: "Inter",
  fontSize: "16px",
  lineHeight: "150%",
  marginRight: theme.spacing(1.25),
  color: theme.palette.text.secondary,
  borderRadius: "6px 6px 0 0",
  padding: "8px",
  "&:hover": {
    color: "#40a9ff",
    opacity: 1,
  },
  "&.Mui-selected": {
    color: theme.palette.primary.main,
    fontWeight: '600',
    // fontSize: '20px',
    backgroundColor: "rgba(51, 154, 250, 0.05)",
  },
  "&.Mui-focusVisible": {
    backgroundColor: "#d1eaff",
  },
}));

interface StyledTabsProps {
  children?: React.ReactNode;
  value: number;
  onChange: (event: React.SyntheticEvent, newValue: number) => void;
}

interface StyledTabProps extends TabProps {
  label: string;
}

export default function Nav(props: {
  items: NavItemType[];
  selected?: string;
}) {
  const { items, selected } = props;
  const [value, setValue] = React.useState(() => {
    const index = items.findIndex((item) => item.id === selected);
    return index === -1 ? 0 : index;
  });

  const nextRouter = useNextRouter();

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
    nextRouter.push(items[newValue].url);
  };

  // React.useEffect(() => {
  //   const index = items.findIndex((item) => item.id === selected);
  //   setValue(index === -1 ? 0 : index);
  // }, [selected]);

  return (
    <>
      <Box sx={{ bgcolor: "#fff" }}>
        <AntTabs value={value} onChange={handleChange} variant="scrollable">
          {items.map((item, index) =>
            item.Icon ? (
              <AntTab
                key={item.id}
                label={item.title}
                icon={item.Icon}
                iconPosition="start"
              />
            ) : (
              <AntTab key={item.id} label={item.title} />
            )
          )}
        </AntTabs>
        {/* <Box sx={{ p: 3 }} /> */}
      </Box>
    </>
  );
}
