"use client"; import React, { useState, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { BomWeightingScoreResult } from "@/app/api/settings/bomWeighting"; import { fetchBomWeightingScoresClient } from "@/app/api/settings/bomWeighting/client"; import type { BomScoreResult } from "@/app/api/bom"; import { fetchBomScoresClient } from "@/app/api/bom/client"; import BomWeightingScoreTable from "@/components/BomWeightingScoreTable"; import BomScoreTable from "@/components/BomScoreTable"; import Tabs from "@mui/material/Tabs"; import Tab from "@mui/material/Tab"; import Box from "@mui/material/Box"; import Paper from "@mui/material/Paper"; interface Props { bomWeightingScores: BomWeightingScoreResult[]; } const BomWeightingTabs: React.FC = ({ bomWeightingScores: initialBomWeightingScores }) => { const { t } = useTranslation("common"); const [tab, setTab] = useState(0); const [bomWeightingScores, setBomWeightingScores] = useState(initialBomWeightingScores); const [bomScores, setBomScores] = useState(null); const [loadingScores, setLoadingScores] = useState(false); const [loadError, setLoadError] = useState(null); const loadBomScores = React.useCallback(async () => { try { setLoadingScores(true); setLoadError(null); console.log("Fetching BOM scores from /bom/scores..."); const data = await fetchBomScoresClient(); console.log("BOM scores received:", data); setBomScores(data || []); } catch (err: any) { console.error("Failed to load BOM scores:", err); const errorMsg = err?.response?.data?.message || err?.message || t("Update Failed") || "Load failed"; setLoadError(errorMsg); setBomScores([]); } finally { setLoadingScores(false); } }, [t]); const loadBomWeightingScores = React.useCallback(async () => { try { console.log("Fetching BOM weighting scores..."); const data = await fetchBomWeightingScoresClient(); console.log("BOM weighting scores received:", data); setBomWeightingScores(data || []); } catch (err: any) { console.error("Failed to load BOM weighting scores:", err); } }, []); const handleWeightingUpdated = React.useCallback(async () => { // Refresh both weighting scores and BOM scores await Promise.all([ loadBomWeightingScores(), loadBomScores() ]); }, [loadBomWeightingScores, loadBomScores]); // Sync initial prop values useEffect(() => { setBomWeightingScores(initialBomWeightingScores); }, [initialBomWeightingScores]); useEffect(() => { if (tab !== 1) return; void loadBomScores(); }, [tab, loadBomScores]); return ( <> setTab(v)} indicatorColor="primary" textColor="primary" sx={{ pl: 2, minHeight: 44, }} > {tab === 0 && ( )} {tab === 1 && ( loadingScores ? (
{t("Loading")}
) : loadError ? (
{loadError}
) : bomScores && bomScores.length > 0 ? ( ) : (
{t("No data available")}
) )}
); }; export default BomWeightingTabs;