import React, { useEffect } from 'react'
import { CompareProduct, useCompareProductDataStore, useInputValues, useMachineDowntime, useMachineUptime, useProductionCapacityData, useROISummaryData, useThroughPutData } from '../../../../store/builder/store';
import { usePlayButtonStore } from '../../../../store/usePlayButtonStore';
import { useProductContext } from '../../products/productContext';
import { useProductStore } from '../../../../store/simulation/useProductStore';

export default function ROIData() {
    const { selectedProductStore } = useProductContext();
    const { inputValues } = useInputValues();
    const { productionCapacityData } = useProductionCapacityData()
    const { selectedProduct } = selectedProductStore();
    const { isPlaying } = usePlayButtonStore();
    const { setRoiSummaryData } = useROISummaryData();
    const { products, getProductById } = useProductStore();
    const { compareProductsData, setCompareProductsData } = useCompareProductDataStore();
    const { machineActiveTime, setMachineActiveTime } = useMachineUptime();
    const { machineIdleTime, setMachineIdleTime } = useMachineDowntime();
    const { throughputData } = useThroughPutData()

    useEffect(() => {
        if (isPlaying) return;
        setRoiSummaryData({
            productName: "",
            roiPercentage: 0,
            paybackPeriod: 0,
            totalCost: 0,
            revenueGenerated: 0,
            netProfit: 0,
            netLoss: 0,
        });
    }, [isPlaying]);

    useEffect(() => {
        if (inputValues === undefined || !isPlaying) return;
        const electricityCost = parseFloat(inputValues["Electricity cost"]);
        const fixedCost = parseFloat(inputValues["Fixed costs"]);
        const laborCost = parseFloat(inputValues["Labor Cost"]);
        const laborCount = parseFloat(inputValues["Labor Count"]);
        const maintenanceCost = parseFloat(inputValues["Maintenance cost"]);
        const materialCost = parseFloat(inputValues["Material cost"]);
        const productionPeriod = parseFloat(inputValues["Production period"]);
        const salvageValue = parseFloat(inputValues["Salvage value"]);
        const sellingPrice = parseFloat(inputValues["Selling price"]);
        const initialInvestment = parseFloat(inputValues["Initial Investment"]);
        const shiftLength = parseFloat(inputValues["Shift length"]);
        const shiftsPerDay = parseFloat(inputValues["Shifts / day"]);
        const workingDaysPerYear = parseFloat(inputValues["Working days / year"]);

        if (!isNaN(electricityCost) && !isNaN(fixedCost) && !isNaN(laborCost) && !isNaN(maintenanceCost) &&
            !isNaN(materialCost) && !isNaN(productionPeriod) && !isNaN(salvageValue) && !isNaN(sellingPrice) &&
            !isNaN(shiftLength) && !isNaN(shiftsPerDay) && !isNaN(workingDaysPerYear) && productionCapacityData > 0) {
            console.log('productionCapacityData: ', productionCapacityData);

            // const totalHoursPerYear = shiftLength * shiftsPerDay * workingDaysPerYear;
            // const annualProductionUnits = productionCapacityData * totalHoursPerYear;
            // const annualRevenue = annualProductionUnits * sellingPrice;

            // const totalMaterialCost = annualProductionUnits * materialCost;
            // const totalLaborCost = laborCost * totalHoursPerYear;
            // const totalEnergyCost = electricityCost * totalHoursPerYear;
            // const totalMaintenanceCost = maintenanceCost + fixedCost;
            // const totalAnnualCost = totalMaterialCost + totalLaborCost + totalEnergyCost + totalMaintenanceCost;
            // const annualProfit = annualRevenue - totalAnnualCost;

            // const netProfit = annualProfit * productionPeriod;
            // const roiPercentage = ((annualProfit + salvageValue - initialInvestment) / initialInvestment) * 100;
            // const paybackPeriod = initialInvestment / (annualProfit || 1); // Avoid division by 0

            // setRoiSummaryData({
            //     productName: selectedProduct.productName,
            //     roiPercentage: parseFloat((roiPercentage / 100).toFixed(2)),
            //     paybackPeriod: parseFloat(paybackPeriod.toFixed(2)),
            //     totalCost: parseFloat(totalAnnualCost.toFixed(2)),
            //     revenueGenerated: parseFloat(annualRevenue.toFixed(2)),
            //     netProfit: netProfit > 0 ? parseFloat(netProfit.toFixed(2)) : 0,
            //     netLoss: netProfit < 0 ? -netProfit : 0
            // });

            // const productCount = 1000;
            // const costPerUnit = totalAnnualCost / annualProductionUnits;
            // const costForTargetUnits = productCount * costPerUnit;
            // const revenueForTargetUnits = productCount * sellingPrice;
            // const profitForTargetUnits = revenueForTargetUnits - costForTargetUnits;

            // const netProfitForTarget = profitForTargetUnits > 0 ? profitForTargetUnits : 0;
            // const netLossForTarget = profitForTargetUnits < 0 ? -profitForTargetUnits : 0;

            // const productData = getProductById(selectedProduct.productUuid);
            // const prev = useCompareProductDataStore.getState().compareProductsData;
            // const newData: CompareProduct = {
            //     productUuid: productData?.productUuid ?? '',
            //     productName: productData?.productName ?? '',
            //     simulationData: {
            //         // costPerUnit: parseFloat(costPerUnit.toFixed(2)),
            //         // workingDaysPerYear: parseFloat(workingDaysPerYear.toFixed(2)),
            //         // shiftLength: parseFloat(shiftLength.toFixed(2)),
            //         // shiftsPerDay: parseFloat(shiftsPerDay.toFixed(2)),
            //         roiPercentage: parseFloat((roiPercentage / 100).toFixed(2)),
            //         // paybackPeriod: parseFloat(paybackPeriod.toFixed(2)),
            //         // totalCost: parseFloat(totalAnnualCost.toFixed(2)),
            //         // revenueGenerated: parseFloat(annualRevenue.toFixed(2)),
            //         netProfit: netProfit > 0 ? parseFloat(netProfit.toFixed(2)) : 0,
            //         productionCapacity: parseFloat(productionCapacityData.toFixed(2)),
            //         // netLoss: netProfit < 0 ? parseFloat((-netProfit).toFixed(2)) : 0,
            //         machineIdleTime: parseFloat(machineIdleTime.toFixed(2)),
            //         machineActiveTime: parseFloat(machineActiveTime.toFixed(2)),
            //         throughputData: throughputData,
            //     }
            // };

            // const existingIndex = prev.findIndex((item: CompareProduct) =>
            //     item.productUuid === productData?.productUuid
            // );

            // if (existingIndex !== -1) {
            //     const updated = [...prev];
            //     updated[existingIndex] = newData;
            //     setCompareProductsData(updated);
            // } else {
            //     setCompareProductsData([...prev, newData]);
            // }

            const Annual_units = throughputData * workingDaysPerYear
            const Total_units = Annual_units * productionPeriod

            const Total_revenue = Total_units * sellingPrice
            const Total_variable_cost = Total_units * (materialCost + (laborCost))

            const Total_fixed_cost = (maintenanceCost + electricityCost + fixedCost) * workingDaysPerYear * productionPeriod
            const Total_cost = Total_variable_cost + Total_fixed_cost

            const Net_profit = Total_revenue - Total_cost + (salvageValue * workingDaysPerYear * productionPeriod)

            const ROI = (Net_profit / initialInvestment) * 100

            const Annual_net_profit = (Annual_units * (sellingPrice - materialCost - laborCost)) - (maintenanceCost + electricityCost + fixedCost) * workingDaysPerYear + (salvageValue * workingDaysPerYear)
            const Payback_period_years = initialInvestment / Annual_net_profit;

            setRoiSummaryData({
                productName: selectedProduct.productName,
                roiPercentage: ROI,
                paybackPeriod: Payback_period_years,
                totalCost: Total_cost,
                revenueGenerated: Total_revenue,
                netProfit: Net_profit > 0 ? Net_profit : 0,
                netLoss: Net_profit < 0 ? -Net_profit : 0
            });


            const productData = getProductById(selectedProduct.productUuid);
            const prev = useCompareProductDataStore.getState().compareProductsData;
            const newData: CompareProduct = {
                productUuid: productData?.productUuid ?? '',
                productName: productData?.productName ?? '',
                simulationData: {
                    // costPerUnit: costPerUnit,
                    // workingDaysPerYear: workingDaysPerYear,
                    // shiftLength: shiftLength,
                    // shiftsPerDay: shiftsPerDay,
                    roiPercentage: ROI,
                    // paybackPeriod: paybackPeriod,
                    // totalCost: totalAnnualCost,
                    // revenueGenerated: annualRevenue,
                    netProfit: Net_profit > 0 ? Net_profit : 0,
                    productionCapacity: productionCapacityData,
                    // netLoss: netProfit < 0 ? (-netProfit) : 0,
                    machineIdleTime: machineIdleTime,
                    machineActiveTime: machineActiveTime,
                    throughputData: throughputData,
                }
            };

            const existingIndex = prev.findIndex((item: CompareProduct) =>
                item.productUuid === productData?.productUuid
            );

            if (existingIndex !== -1) {
                const updated = [...prev];
                updated[existingIndex] = newData;
                setCompareProductsData(updated);
            } else {
                setCompareProductsData([...prev, newData]);
            }
        }

    }, [inputValues, productionCapacityData, throughputData, isPlaying]);

    useEffect(() => {
        console.log('compareProductsData: ', compareProductsData);
    }, [compareProductsData])

    return null;
}
