"use client";

import React, { useState } from "react";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Alert from "@mui/material/Alert";
import { uploadBomFiles } from "@/app/api/bom/client";
import { checkBomFormat, getBomFormatProgress ,BomExcelCheckProgress} from "@/app/api/bom/client";
import type { BomFormatCheckResponse } from "@/app/api/bom";

type Props = {
    onSuccess: (
        batchId: string,
        results: BomFormatCheckResponse,
        uploadedCount: number
        
    ) => void;
};

function getErrorMessage(err: unknown): string {
    if (err && typeof err === "object" && "response" in err) {
        const res = (err as { response?: { status?: number; data?: unknown } })
            .response;
        if (res?.status === 500)
            return "伺服器錯誤 (500)，請確認後端服務已啟動且 API 路徑正確。";
        if (res?.data && typeof res.data === "string" && res.data.length < 200)
            return res.data;
    }
    if (err && typeof err === "object" && "message" in err)
        return String((err as { message: string }).message);
    return "上傳或檢查失敗，請稍後再試。";
}

export default function ImportBomUpload({ onSuccess }: Props) {
    const [files, setFiles] = useState<File[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [progress, setProgress] = useState<BomExcelCheckProgress | null>(null);
const [startTime, setStartTime] = useState<number | null>(null);
    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const selected = e.target.files;
        if (!selected?.length) return;
        const list = Array.from(selected).filter((f) =>
            f.name.toLowerCase().endsWith(".xlsx")
        );
        setFiles(list);
        setError(null);
    };

    const handleUploadAndCheck = async () => {
        if (files.length === 0) {
          setError("請至少選擇一個 .xlsx 檔案");
          return;
        }
        setLoading(true);
        setError(null);
        setProgress(null);
      
        let timer: number | undefined;
        try {
          const { batchId } = await uploadBomFiles(files);
          setStartTime(Date.now());
      
          // 啟動輪詢：每 1 秒打一次 progress API
          timer = window.setInterval(async () => {
            try {
              const p = await getBomFormatProgress(batchId);
              setProgress(p);
            } catch (e) {
              // 進度查詢失敗可以暫時忽略或寫 console
              console.warn("load bom progress failed", e);
            }
          }, 1000);
      
          const results = await checkBomFormat(batchId); // 這裡會等後端整個檢查完
          onSuccess(batchId, results, files.length);
        } catch (err: unknown) {
          setError(getErrorMessage(err));
        } finally {
          setLoading(false);
          if (timer !== undefined) {
            window.clearInterval(timer);
          }
        }
      };

    return (
        <Card variant="outlined" sx={{ maxWidth: 560 }}>
            <CardContent>
                <Stack spacing={2.5}>
                    <Typography variant="h6" color="text.primary">
                        選擇 BOM Excel 檔案
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                        可多選 .xlsx 檔案，或選擇資料夾一次加入多個檔案。
                    </Typography>
                    <Stack direction="row" alignItems="center" spacing={2} flexWrap="wrap">
                        <Button variant="outlined" component="label">
                            選擇檔案
                            <input
                                type="file"
                                hidden
                                multiple
                                accept=".xlsx"
                                onChange={handleFileChange}
                            />
                        </Button>
                        <Button variant="outlined" component="label">
                            選擇資料夾
                            <input
                                type="file"
                                hidden
                                accept=".xlsx"
                                onChange={handleFileChange}
                                {...{ webkitdirectory: "" }}
                            />
                        </Button>
                        <Typography variant="body2" color="text.secondary">
                            {files.length > 0
                                ? `已選 ${files.length} 個檔案`
                                : "未選擇"}
                        </Typography>
                    </Stack>
                    <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                        <Button
                            variant="contained"
                            onClick={handleUploadAndCheck}
                            disabled={loading || files.length === 0}
                        >
                            {loading ? "上傳與檢查中…" : "上傳並檢查"}
                        </Button>
                        {loading && <CircularProgress size={24} />}
                        {loading && progress && (
                        <Typography variant="body2" color="text.secondary">
                            已檢查 {progress.processedFiles} / {progress.totalFiles} 個檔案
                            {progress.currentFileName && `，目前：${progress.currentFileName}`}
                            {startTime && progress.processedFiles > 0 && progress.totalFiles > 0 && (() => {
                            const elapsedMs = Date.now() - startTime;
                            const avgPerFile = elapsedMs / progress.processedFiles;
                            const remainingFiles = progress.totalFiles - progress.processedFiles;
                            const remainingMs = Math.max(0, remainingFiles * avgPerFile);
                            const remainingSec = Math.round(remainingMs / 1000);
                            return `，約還需 ${remainingSec} 秒`;
                            })()}
                        </Typography>
                        )}
                    </Box>
                    {error && (
                        <Alert severity="error" onClose={() => setError(null)}>
                            {error}
                        </Alert>
                    )}
                </Stack>
            </CardContent>
        </Card>
    );
}
