"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 WarehouseTabsProps {
  tab0Content: ReactNode;
  tab1Content: ReactNode;
}

function TabPanel({
  children,
  value,
  index,
}: {
  children?: ReactNode;
  value: number;
  index: number;
}) {
  return (
    <div role="tabpanel" hidden={value !== index}>
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
}

export default function WarehouseTabs({ tab0Content, tab1Content }: WarehouseTabsProps) {
  const { t } = useTranslation("warehouse");
  const searchParams = useSearchParams();
  const router = useRouter();
  const [currentTab, setCurrentTab] = useState(() => {
    const tab = searchParams.get("tab");
    return tab === "1" ? 1 : 0;
  });

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

  const handleTabChange = (_e: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
    const params = new URLSearchParams(searchParams.toString());
    if (newValue === 0) params.delete("tab");
    else params.set("tab", String(newValue));
    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("Warehouse List")} />
          <Tab label={t("Stock Take Section & Warehouse Mapping")} />
        </Tabs>
      </Box>
      <TabPanel value={currentTab} index={0}>
        {tab0Content}
      </TabPanel>
      <TabPanel value={currentTab} index={1}>
        {tab1Content}
      </TabPanel>
    </Box>
  );
}