"use client";

import React, { useMemo, useState } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import InputAdornment from "@mui/material/InputAdornment";
import Checkbox from "@mui/material/Checkbox";
import Accordion from "@mui/material/Accordion";
import AccordionSummary from "@mui/material/AccordionSummary";
import AccordionDetails from "@mui/material/AccordionDetails";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import Paper from "@mui/material/Paper";
import CircularProgress from "@mui/material/CircularProgress";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import SearchIcon from "@mui/icons-material/Search";
import type { BomFormatFileGroup } from "@/app/api/bom";
import { importBom, downloadBomFormatIssueLog } from "@/app/api/bom/client";
import { useTranslation } from "react-i18next";
type CorrectItem = {
  fileName: string;
  isAlsoWip: boolean;
  isDrink: boolean;
  isPowderMixture: boolean;
};

type Props = {
    batchId: string;
    correctFileNames: string[];
    failList: BomFormatFileGroup[];
    uploadedCount: number;
    issueLogFileId?: string;   // 新增
    onBack?: () => void;
  };
  export default function ImportBomResultForm({
    batchId,
    correctFileNames,
    failList,
    uploadedCount,
    issueLogFileId,
    onBack,
  }: Props) {
    console.log("issueLogFileId from props", issueLogFileId);
    const { t } = useTranslation(["importBom", "common", "importExcel"]);
    const [search, setSearch] = useState("");
    const [items, setItems] = useState<CorrectItem[]>(() =>
        correctFileNames.map((fileName) => ({
            fileName,
            isAlsoWip: false,
            isDrink: false,
            isPowderMixture: fileName.includes("箱料粉"),
        }))
    );
    const [submitting, setSubmitting] = useState(false);
    const [successMsg, setSuccessMsg] = useState<string | null>(null);

    const filteredCorrect = useMemo(() => {
        if (!search.trim()) return items;
        const q = search.trim().toLowerCase();
        return items.filter((i) => i.fileName.toLowerCase().includes(q));
    }, [items, search]);

    const handleToggleWip = (fileName: string) => {
        setItems((prev) =>
            prev.map((x) =>
                x.fileName === fileName
                    ? { ...x, isAlsoWip: !x.isAlsoWip }
                    : x
            )
        );
    };
    const handleToggleDrink = (fileName: string) => {
        setItems((prev) =>
            prev.map((x) =>
                x.fileName === fileName
                    ? { ...x, isDrink: !x.isDrink, isPowderMixture: false }
                    : x
            )
        );
    };
    const handleTogglePowderMixture = (fileName: string) => {
        setItems((prev) =>
            prev.map((x) =>
                x.fileName === fileName
                    ? { ...x, isPowderMixture: !x.isPowderMixture, isDrink: false }
                    : x
            )
        );
    };
    const handleDownloadIssueLog = async () => {
        const blob = await downloadBomFormatIssueLog(batchId, issueLogFileId!);
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `bom_excel_issue_log_${new Date().toISOString().slice(0, 10)}.xlsx`;
        a.click();
        URL.revokeObjectURL(url);
    };
    const handleConfirm = async () => {
        setSubmitting(true);
        setSuccessMsg(null);
        try {
            const blob = await importBom(batchId, items);
            //const url = URL.createObjectURL(blob);
            //const a = document.createElement("a");
            //a.href = url;
            //a.download = `bom_excel_issue_log_${new Date().toISOString().slice(0, 10)}.xlsx`;
            //a.click();
            //URL.revokeObjectURL(url);
            setSuccessMsg("匯入完成");
        } catch (err) {
            console.error(err);
            setSuccessMsg("匯入失敗，請查看主控台。");
        } finally {
            setSubmitting(false);
        }
    };

    const wipCount = items.filter((i) => i.isAlsoWip).length;
    const powderMixtureCount = items.filter((i) => i.isPowderMixture).length;
    const drinkCount = items.filter((i) => i.isDrink).length;
    const totalChecked = correctFileNames.length + failList.length;

    return (
        <Stack spacing={2}>
            <Stack direction="row" alignItems="center" spacing={2} flexWrap="wrap">
                {onBack && (
                    <Button variant="outlined" onClick={onBack}>
                        返回重選檔案
                    </Button>
                )}
                <Stack direction="column" spacing={0.5}>
                    <Typography variant="body2" color="text.secondary">
                        已上傳 {uploadedCount} 個檔案，檢查結果共 {totalChecked} 筆：正確 {correctFileNames.length} 個、失敗 {failList.length} 個
                    </Typography>
                    {uploadedCount !== totalChecked && (
                        <Typography variant="caption" color="warning.main">
                            上傳數與檢查筆數不符，可能因檔名重複；重新上傳後會為重複檔名自動加 _2、_3 等區分，全部都會列入檢查。
                        </Typography>
                    )}
                </Stack>
            </Stack>

            <Box
                sx={{
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr",
                    gap: 2,
                    alignItems: "stretch",
                }}
            >
                <Paper variant="outlined" sx={{ p: 2 }}>
                    <Typography variant="subtitle1" gutterBottom>
                        {t("Correct BOM List (Can Import)")}
                    </Typography>
                    <TextField
                        size="small"
                        placeholder="搜索檔名"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        InputProps={{
                            startAdornment: (
                                <InputAdornment position="start">
                                    <SearchIcon />
                                </InputAdornment>
                            ),
                        }}
                        sx={{ mb: 2, width: "100%" }}
                    />
                    <Stack spacing={0.5}>
                    <Stack direction="row" alignItems="center" spacing={1} sx={{ px: 0.5, pb: 0.5 }}>
                        <Typography variant="caption" color="text.secondary" sx={{ width: 40 }}>{t("WIP")}</Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ width: 40 }}>{t("Drink")}</Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ width: 56 }}>{t("Powder_Mixture")}</Typography>
                        <Typography variant="caption" color="text.secondary" sx={{ flex: 1 }}>{t("File Name")}</Typography>
                    </Stack>
                        {filteredCorrect.map((item) => (
                           <Stack
                           key={item.fileName}
                           direction="row"
                           alignItems="center"
                           spacing={1}
                       >
                           <Checkbox
                               checked={item.isAlsoWip}
                               onChange={() => handleToggleWip(item.fileName)}
                               size="small"
                           />
                           <Checkbox
                               checked={item.isDrink}
                               onChange={() => handleToggleDrink(item.fileName)}
                               size="small"
                           />
                           <Checkbox
                               checked={item.isPowderMixture}
                               onChange={() => handleTogglePowderMixture(item.fileName)}
                               size="small"
                           />
                           <Typography
                               variant="body2"
                               sx={{ flex: 1 }}
                               noWrap
                           >
                               {item.fileName}
                           </Typography>
                         
                       </Stack>
                        ))}
                    </Stack>
                </Paper>

                <Paper variant="outlined" sx={{ p: 2 }}>
                    <Typography variant="subtitle1" gutterBottom>
                        {t("Issue BOM List")}
                    </Typography>
                    {failList.length === 0 ? (
                        <Typography variant="body2" color="text.secondary">
                            無
                        </Typography>
                    ) : (
                        failList.map((f) => (
                            <Accordion key={f.fileName} disableGutters>
                                <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                                    <Typography variant="body2">
                                        {f.fileName}
                                    </Typography>
                                </AccordionSummary>
                                <AccordionDetails>
                                    <Stack component="ul" sx={{ pl: 2, m: 0 }}>
                                        {f.problems.map((p, i) => (
                                            <Typography
                                                key={i}
                                                component="li"
                                                variant="body2"
                                                color="error"
                                            >
                                                {p}
                                            </Typography>
                                        ))}
                                    </Stack>
                                </AccordionDetails>
                            </Accordion>
                        ))
                    )}
                </Paper>
            </Box>

            <Stack direction="row" alignItems="center" spacing={2}>
                <Button
                    variant="contained"
                    onClick={handleConfirm}
                    disabled={submitting || items.length === 0}
                >
                    確認匯入
                </Button>
                <Button
                variant="outlined"
                onClick={handleDownloadIssueLog}
                disabled={!issueLogFileId}
                >
                下載檢查結果 Excel
                </Button>
                {submitting && <CircularProgress size={24} />}
                {successMsg && (
                    <Typography variant="body2" color="primary">
                        {successMsg}
                    </Typography>
                )}
            </Stack>
            {items.length > 0 && (
                <Typography variant="caption" color="text.secondary">
                    將匯入 {items.length} 個 BOM
                    {wipCount > 0 ? `，其中 ${wipCount} 個同時建立 半成品` : ""}
                    {drinkCount > 0 ? `，${drinkCount} 個飲料` : ""}
                    {powderMixtureCount > 0 ? `，${powderMixtureCount} 個箱料粉` : ""}
                </Typography>
            )}
        </Stack>
    );
}
