import React, { useEffect, useState } from 'react'
import { useInputValues, useProductionCapacityData, useROISummaryData } from '../../../../store/builder/store';
import { useSelectedProduct } from '../../../../store/simulation/useSimulationStore';
import { usePlayButtonStore } from '../../../../store/usePlayButtonStore';

export default function ROIData() {
    const { inputValues } = useInputValues();
    const { productionCapacityData } = useProductionCapacityData()
    const { selectedProduct } = useSelectedProduct();
    const { isPlaying } = usePlayButtonStore();
    const { setRoiSummaryData } = useROISummaryData();
    useEffect(() => {
        if (!isPlaying) {
            setRoiSummaryData({
                productName: "",
                roiPercentage: 0,
                paybackPeriod: 0,
                totalCost: 0,
                revenueGenerated: 0,
                netProfit: 0,
                netLoss: 0,
            })
            return;
        }

        if (inputValues === undefined) return;

        const electricityCost = parseFloat(inputValues["Electricity cost"]);
        const fixedCost = parseFloat(inputValues["Fixed costs"]);
        const laborCost = parseFloat(inputValues["Labor Cost"]);
        const maintenanceCost = parseFloat(inputValues["Maintenance cost"]); // Remove space typ
        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) {




            const totalHoursPerYear = shiftLength * shiftsPerDay * workingDaysPerYear;

            // Total good units produced per year
            const annualProductionUnits = productionCapacityData * totalHoursPerYear;

            // Revenue for a year
            const annualRevenue = annualProductionUnits * sellingPrice;

            // Costs
            const totalMaterialCost = annualProductionUnits * materialCost;
            const totalLaborCost = laborCost * totalHoursPerYear;
            const totalEnergyCost = electricityCost * totalHoursPerYear;
            const totalMaintenanceCost = maintenanceCost + fixedCost;

            const totalAnnualCost = totalMaterialCost + totalLaborCost + totalEnergyCost + totalMaintenanceCost;

            // Annual Profit
            const annualProfit = annualRevenue - totalAnnualCost;
            console.log('annualProfit: ', annualProfit);

            // Net Profit over production period
            const netProfit = annualProfit * productionPeriod;

            // ROI
            const roiPercentage = ((netProfit + salvageValue - initialInvestment) / initialInvestment) * 100;

            // Payback Period
            const paybackPeriod = initialInvestment / (annualProfit || 1); // Avoid division by 0
            console.log('paybackPeriod: ', paybackPeriod);

            // console.log("--- ROI Breakdown ---");
            // console.log("Annual Production Units:", annualProductionUnits.toFixed(2));
            // console.log("Annual Revenue:", annualRevenue.toFixed(2));
            // console.log("Total Annual Cost:", totalAnnualCost.toFixed(2));
            // console.log("Annual Profit:", annualProfit.toFixed(2));
            // console.log("Net Profit:", netProfit.toFixed(2));
            // console.log("ROI %:", roiPercentage.toFixed(2));
            // console.log("Payback Period (years):", paybackPeriod.toFixed(2));

            setRoiSummaryData({
                productName: selectedProduct.productName,
                roiPercentage: parseFloat((roiPercentage / 100).toFixed(2)), // normalized to 0.x format
                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;

            // Cost per unit (based on full annual cost)
            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;

            // console.log("--- Fixed Product Count (" + productCount + ") ---");
            // console.log("Cost per Unit:", costPerUnit.toFixed(2));
            // console.log("Total Cost for " + productCount + " Units:", costForTargetUnits.toFixed(2));
            // console.log("Revenue for " + productCount + " Units:", revenueForTargetUnits.toFixed(2));
            // console.log("Profit:", netProfitForTarget.toFixed(2));
            // console.log("Loss:", netLossForTarget.toFixed(2));

        }

    }, [inputValues, productionCapacityData]);

    return (
        <></>
    )
}


