"use client";

import React, { useState } from "react";
import Stack from "@mui/material/Stack";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";
import Box from "@mui/material/Box";
import ImportBomUpload from "./ImportBomUpload";
import ImportBomResultForm from "./ImportBomResultForm";
import ImportBomDetailTab from "./ImportBomDetailTab";
import type { BomFormatCheckResponse } from "@/app/api/bom";

export default function ImportBomWrapper() {
  const [batchId, setBatchId] = useState<string | null>(null);
  const [formatResults, setFormatResults] =
    useState<BomFormatCheckResponse | null>(null);
  const [uploadedCount, setUploadedCount] = useState<number>(0);
  const [currentTab, setCurrentTab] = useState<number>(0);

  const handleUploadSuccess = (
    id: string,
    results: BomFormatCheckResponse,
    count: number
  ) => {
    setBatchId(id);
    setFormatResults(results);
    setUploadedCount(count);
  };

  const handleBack = () => {
    setBatchId(null);
    setFormatResults(null);
  };

  const handleTabChange = (_e: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  return (
    <Stack spacing={3}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs value={currentTab} onChange={handleTabChange}>
          <Tab label="匯入 BOM" />
          <Tab label="BOM 明細" />
        </Tabs>
      </Box>

      {/* Tab 0: 原本匯入流程 */}
      {currentTab === 0 && (
        <Box sx={{ pt: 2 }}>
          {formatResults === null ? (
            <ImportBomUpload onSuccess={handleUploadSuccess} />
          ) : batchId ? (
            <ImportBomResultForm
              batchId={batchId}
              correctFileNames={formatResults.correctFileNames}
              failList={formatResults.failList}
              uploadedCount={uploadedCount}
              issueLogFileId={formatResults.issueLogFileId}
              onBack={handleBack}
            />
          ) : null}
        </Box>
      )}

      {/* Tab 1: BOM 詳細資料 */}
      {currentTab === 1 && (
        <Box sx={{ pt: 2 }}>
          <ImportBomDetailTab />
        </Box>
      )}
    </Stack>
  );
}