"use client";

import { useState, ReactNode, useEffect } from "react";
import { Box, Tabs, Tab } from "@mui/material";
import { useTranslation } from "react-i18next";
import { useSearchParams, useRouter } from "next/navigation";

interface TabPanelProps {
  children?: ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`qc-item-all-tabpanel-${index}`}
      aria-labelledby={`qc-item-all-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
}

interface QcItemAllTabsProps {
  tab0Content: ReactNode;
  tab1Content: ReactNode;
  tab2Content: ReactNode;
  tab3Content: ReactNode;
}

const QcItemAllTabs: React.FC<QcItemAllTabsProps> = ({
  tab0Content,
  tab1Content,
  tab2Content,
  tab3Content,
}) => {
  const { t } = useTranslation("qcItemAll");
  const searchParams = useSearchParams();
  const router = useRouter();

  const getInitialTab = () => {
    const tab = searchParams.get("tab");
    if (tab === "1") return 1;
    if (tab === "2") return 2;
    if (tab === "3") return 3;
    return 0;
  };

  const [currentTab, setCurrentTab] = useState(getInitialTab);

  useEffect(() => {
    const tab = searchParams.get("tab");
    const tabIndex = tab ? parseInt(tab, 10) : 0;
    setCurrentTab(tabIndex);
  }, [searchParams]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
    const params = new URLSearchParams(searchParams.toString());
    if (newValue === 0) {
      params.delete("tab");
    } else {
      params.set("tab", newValue.toString());
    }
    router.push(`?${params.toString()}`, { scroll: false });
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs value={currentTab} onChange={handleTabChange}>
          <Tab label={t("Item and Qc Category Mapping")} />
          <Tab label={t("Qc Category and Qc Item Mapping")} />
          <Tab label={t("Qc Category Management")} />
          <Tab label={t("Qc Item Management")} />
        </Tabs>
      </Box>

      <TabPanel value={currentTab} index={0}>
        {tab0Content}
      </TabPanel>

      <TabPanel value={currentTab} index={1}>
        {tab1Content}
      </TabPanel>

      <TabPanel value={currentTab} index={2}>
        {tab2Content}
      </TabPanel>

      <TabPanel value={currentTab} index={3}>
        {tab3Content}
      </TabPanel>
    </Box>
  );
};

export default QcItemAllTabs;

