import { Button, Card, CardContent, Stack, Typography, Box } from "@mui/material";
import { useTranslation } from "react-i18next";
import { JoDetailPickLine } from "@/app/api/jo";
import { fetchInventories } from "@/app/api/inventory/actions";
import { InventoryResult } from "@/app/api/inventory";
import { useEffect, useState, useMemo } from "react";
import { useFormContext } from "react-hook-form";
import { JoDetail } from "@/app/api/jo";

type Props = {
    onActionClick?: () => void;
    pickLines: JoDetailPickLine[];
    handleRelease: () => void;
}

const JoRelease: React.FC<Props> = ({
    onActionClick,
    pickLines,
    handleRelease
}) => {

    const { t } = useTranslation("jo");
    const [inventoryData, setInventoryData] = useState<InventoryResult[]>([]);

    const { watch } = useFormContext<JoDetail>();

    const status = useMemo(() => {
        const currentStatus = watch("status").toLowerCase();
        console.log("JoRelease status:", currentStatus, "id:", pickLines[0]?.id);
        return currentStatus;
    }, [watch("status")])

    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();
    }, [pickLines]);

    const getStockAvailable = (pickLine: JoDetailPickLine) => {
        const inventory = inventoryData.find(inventory => 
            inventory.itemCode === pickLine.code || inventory.itemName === pickLine.name
        );
        
        if (inventory) {
            return inventory.availableQty || (inventory.onHandQty - inventory.onHoldQty - inventory.unavailableQty);
        }
        
        return 0;
    };

    const isStockSufficient = (pickLine: JoDetailPickLine) => {
        const stockAvailable = getStockAvailable(pickLine);
        return stockAvailable >= pickLine.reqQty;
    };

    const stockCounts = useMemo(() => {
        const totalLines = pickLines.length;
        const nonMatAndNonItemLines = pickLines.filter(pickLine => 
            pickLine.type !== 'mat' && pickLine.type !== 'item'
        );
        const sufficientLines = nonMatAndNonItemLines.filter(pickLine => isStockSufficient(pickLine)).length;
        const insufficientLines = nonMatAndNonItemLines.length - sufficientLines;

        return {
            total: totalLines,
            sufficient: sufficientLines,
            insufficient: insufficientLines
        };
    }, [pickLines, inventoryData]);

    
    return (
        <Card>
            <CardContent>
                <Stack 
                    direction="row" 
                    alignItems="center" 
                    justifyContent="space-between"
                    spacing={2}
                >
                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                    {t("Total lines: ")}<strong>{stockCounts.total}</strong>
                </Typography>

                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                    {t("Lines with sufficient stock: ")}<strong style={{ color: 'green' }}>{stockCounts.sufficient}</strong>
                </Typography>

                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                    {t("Lines with insufficient stock: ")}<strong style={{ color: 'red' }}>{stockCounts.insufficient}</strong>
                </Typography>

                <Button 
                    variant="contained" 
                    color="primary"
                    onClick={handleRelease}
                    disabled={stockCounts.insufficient > 0 || status !== "planning"}
                >
                    {t("Release")}
                </Button>
    
                </Stack>

            </CardContent>
        </Card>
    );
};

export default JoRelease;
