import { DoDetail, DoDetailLine } from "@/app/api/do/actions";
import { decimalFormatter } from "@/app/utils/formatUtil";
import { GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { isEmpty } from "lodash";
import { useMemo } 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';

type DoLineRow = DoDetailLine & {
    stockAvailable: number;
    isStockSufficient: boolean;
};

type Props = Record<string, never>;

const getStockAvailable = (line: DoDetailLine): number => {
    if (line.stockQty != null && !Number.isNaN(Number(line.stockQty))) {
        return Number(line.stockQty);
    }
    return 0;
};

const isStockSufficient = (line: DoDetailLine): boolean => {
    if (line.availableStatus === "available") return true;
    if (line.availableStatus === "insufficient") return false;
    return getStockAvailable(line) >= (line.qty ?? 0);
};

const DoLineTable: React.FC<Props> = () => {
    const { t } = useTranslation("do");
    const { watch } = useFormContext<DoDetail>();
    const deliveryOrderLines = watch("deliveryOrderLines");

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

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

    const rowsWithCalculatedFields = useMemo((): DoLineRow[] => {
        return deliveryOrderLines.map((line, index) => ({
            ...line,
            id: line.id || index,
            stockAvailable: getStockAvailable(line),
            isStockSufficient: isStockSufficient(line),
        }));
    }, [deliveryOrderLines]);

    const columns = useMemo<GridColDef[]>(() => [
        {
            field: "itemNo",
            headerName: t("Item No."),
            flex: 0.6,
        },
        {
            field: "itemName",
            headerName: t("Item Name"),
            flex: 1,
            renderCell: (params: GridRenderCellParams<DoLineRow>) => {
                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<DoLineRow>) => {
                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<DoLineRow>) => {
                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<DoLineRow>) => {
                return params.row.isStockSufficient ? sufficientStockIcon : insufficientStockIcon;
            },
        },
    ], [t, sufficientStockIcon, insufficientStockIcon]);

    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;
