"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={`qr-code-handle-tabpanel-${index}`}
      aria-labelledby={`qr-code-handle-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
}

interface QrCodeHandleTabsProps {
  userTabContent: ReactNode;
  equipmentTabContent: ReactNode;
  warehouseTabContent: ReactNode;
}

const QrCodeHandleTabs: React.FC<QrCodeHandleTabsProps> = ({
  userTabContent,
  equipmentTabContent,
  warehouseTabContent,
}) => {
  const { t: tQrCodeHandle } = useTranslation("qrCodeHandle");
  const { t: tUser } = useTranslation("user");
  const { t: tWarehouse } = useTranslation("warehouse");
  const searchParams = useSearchParams();
  const router = useRouter();
  
  const getInitialTab = () => {
    const tab = searchParams.get("tab");
    if (tab === "equipment") return 1;
    if (tab === "warehouse") return 2;
    if (tab === "user") return 0;
    return 0;
  };

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

  useEffect(() => {
    const tab = searchParams.get("tab");
    if (tab === "equipment") {
      setCurrentTab(1);
    } else if (tab === "warehouse") {
      setCurrentTab(2);
    } else if (tab === "user") {
      setCurrentTab(0);
    }
  }, [searchParams]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
    let tabName = "user";
    if (newValue === 1) tabName = "equipment";
    else if (newValue === 2) tabName = "warehouse";
    const params = new URLSearchParams(searchParams.toString());
    params.set("tab", tabName);
    router.push(`?${params.toString()}`, { scroll: false });
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs value={currentTab} onChange={handleTabChange}>
          <Tab label={tUser("User")} />
          <Tab label={tQrCodeHandle("Equipment")} />
          <Tab label={tWarehouse("Warehouse")} />
        </Tabs>
      </Box>

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

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

      <TabPanel value={currentTab} index={2}>
        {warehouseTabContent}
      </TabPanel>
    </Box>
  );
};

export default QrCodeHandleTabs;