import { DoDetail } from "@/app/api/do/actions";
import { decimalFormatter } from "@/app/utils/formatUtil";
import { GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { isEmpty, upperFirst } from "lodash";
import { useMemo, useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid/StyledDataGrid";
import CheckCircleOutlineOutlinedIcon from '@mui/icons-material/CheckCircleOutlineOutlined';
import DoDisturbAltRoundedIcon from '@mui/icons-material/DoDisturbAltRounded';
import { fetchInventories } from "@/app/api/inventory/actions";
import { InventoryResult } from "@/app/api/inventory";

type DoLineWithCalculations = {
    id?: number;
    itemNo: string;
    itemName: string;
    qty: number;
    uomCode: string;
    uom?: string;
    shortUom?: string;
    status: string;
    stockAvailable: number;
    isStockSufficient: boolean;
};

type Props = {

};

const DoLineTable: React.FC<Props> = ({

}) => {
    const { t } = useTranslation("do")
    const {
        watch
    } = useFormContext<DoDetail>()

    const [inventoryData, setInventoryData] = useState<InventoryResult[]>([]);
    const deliveryOrderLines = watch("deliveryOrderLines");

    useEffect(() => {
        const fetchInventoryData = async () => {
            try {
                const inventoryResponse = await fetchInventories({
                    code: "",
                    name: "",
                    type: "",
                    pageNum: 0,
                    pageSize: 1000 
                });
                setInventoryData(inventoryResponse.records);
            } catch (error) {
                console.error("Error fetching inventory data:", error);
            }
        };

        fetchInventoryData();
    }, [deliveryOrderLines]);

    const getStockAvailable = (line: any) => {
        const inventory = inventoryData.find(inventory => 
            inventory.itemCode === line.itemNo || inventory.itemName === line.itemName
        );
        
        if (inventory) {
            return inventory.availableQty || (inventory.onHandQty - inventory.onHoldQty - inventory.unavailableQty);
        }
        
        return 0;
    };

    const isStockSufficient = (line: any) => {
        const stockAvailable = getStockAvailable(line);
        return stockAvailable >= line.qty;
    };

    const sufficientStockIcon = useMemo(() => {
        return <CheckCircleOutlineOutlinedIcon fontSize={"large"} color="success" />
    }, []);

    const insufficientStockIcon = useMemo(() => {
        return <DoDisturbAltRoundedIcon fontSize={"large"} color="error" />
    }, []);

    const rowsWithCalculatedFields = useMemo(() => {
        return deliveryOrderLines.map((line, index) => ({
            ...line,
            id: line.id || index,
            shortUom: line.shortUom, // 假设 shortUom 就是 uomCode，如果有其他字段请修改
            stockAvailable: getStockAvailable(line),
            isStockSufficient: isStockSufficient(line),
        }));
    }, [deliveryOrderLines, inventoryData]);

    const columns = useMemo<GridColDef[]>(() => [
        {
            field: "itemNo",
            headerName: t("Item No."),
            flex: 0.6,
        },
        {
            field: "itemName",
            headerName: t("Item Name"),
            flex: 1,
            renderCell: (params: GridRenderCellParams<DoLineWithCalculations>) => {
                const name = isEmpty(params.value) ? "N/A" : params.value;
                const uom = params.row.uom || "";
                return `${name} (${uom})`;
            },
        },
        {
            field: "qty",
            headerName: t("Quantity"),
            flex: 0.7,
            align: "right",
            headerAlign: "right",
            renderCell: (params: GridRenderCellParams<DoLineWithCalculations>) => {
                return `${decimalFormatter.format(params.value)} (${params.row.shortUom})`;
            },
        },
        {
            field: "stockAvailable",
            headerName: t("Stock Available"),
            flex: 0.7,
            align: "right",
            headerAlign: "right",
            type: "number",
            renderCell: (params: GridRenderCellParams<DoLineWithCalculations>) => {
                return `${decimalFormatter.format(params.value)} (${params.row.shortUom})`;
            },
        },
        {
            field: "stockStatus",
            headerName: t("Stock Status"),
            flex: 0.5,
            align: "right",
            headerAlign: "right",
            type: "boolean",
            renderCell: (params: GridRenderCellParams<DoLineWithCalculations>) => {
                return params.row.isStockSufficient ? sufficientStockIcon : insufficientStockIcon;
            },
        },

 
    ], [t, inventoryData])

    return (
        <>
            <StyledDataGrid
                sx={{
                    "--DataGrid-overlayHeight": "100px",
                    ".MuiDataGrid-row .MuiDataGrid-cell.hasError": {
                        border: "1px solid",
                        borderColor: "error.main",
                    },
                    ".MuiDataGrid-row .MuiDataGrid-cell.hasWarning": {
                        border: "1px solid",
                        borderColor: "warning.main",
                    },
                }}
                disableColumnMenu
                rows={rowsWithCalculatedFields}
                columns={columns}
                getRowHeight={() => 'auto'}
            />
        </>
    )
}

export default DoLineTable;