"use client";

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

type EquipmentTabsProps = {
  onTabChange?: (tabIndex: number) => void;
};

const EquipmentTabs: React.FC<EquipmentTabsProps> = ({ onTabChange }) => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useTranslation("common");
  
  const tabFromUrl = searchParams.get("tab");
  const initialTabIndex = tabFromUrl ? parseInt(tabFromUrl, 10) : 0;
  const [tabIndex, setTabIndex] = useState(initialTabIndex);

  useEffect(() => {
    const tabFromUrl = searchParams.get("tab");
    const newTabIndex = tabFromUrl ? parseInt(tabFromUrl, 10) : 0;
    if (newTabIndex !== tabIndex) {
      setTabIndex(newTabIndex);
      onTabChange?.(newTabIndex);
    }
  }, [searchParams, tabIndex, onTabChange]);

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

  return (
    <Tabs value={tabIndex} onChange={handleTabChange}>
      <Tab label={t("General Data")} />
      <Tab label={t("Repair and Maintenance")} />
    </Tabs>
  );
};

export default EquipmentTabs;