import { useCompareProductDataStore, useLoadingProgress, useIsComparing } from "../../../store/builder/store";
import { useSimulationState } from "../../../store/simulation/useSimulationStore";
import { usePlayButtonStore } from "../../../store/ui/usePlayButtonStore";
import { useEffect, useState } from "react";
import { useSceneContext } from "../../../modules/scene/sceneContext";
import useModuleStore from "../../../store/ui/useModuleStore";
import CompareLayOut from "../../ui/compareVersion/CompareLayOut";
import ComparisonResult from "../../ui/compareVersion/ComparisonResult";
import RegularDropDown from "../../ui/inputs/RegularDropDown";
import { useSimulationManager } from "../../../store/rough/useSimulationManagerStore";
import { useParams } from "react-router-dom";

type AssetData = {
    activeTime: number;
    idleTime: number;
    type: string;
    assetId: string;
};

export interface CompareProduct {
    productUuid: string;
    productName: string;
    // simulationData: {
    //     // costPerUnit: number;
    //     // workingDaysPerYear: number;
    //     // shiftLength: number;
    //     // shiftsPerDay: number;
    //     roiPercentage: number;
    //     // paybackPeriod: number;
    //     // totalCost: number;
    //     // revenueGenerated: number;
    //     netProfit: number;
    //     productionCapacity: number;
    //     paybackPeriod: number;
    //     // netLoss: number;
    //     machineIdleTime: number;
    //     machineActiveTime: number;
    //     throughputData: number;
    // };
    simulationData: {
        roiPercentage: number;
        netProfit: number;
        productionCapacity: number;
        paybackPeriod: number;
        machineIdleTime: number;
        machineActiveTime: number;
        throughputData: number;
        simulationTime?: number;
        simulationCost?: number;
        efficiencyScore?: number;
    };
}

const calculateSimulationData = (assets: AssetData[]) => {
    let totalActiveTime = 0;
    let totalIdleTime = 0;
    let throughput = 0;
    let productionCapacity = 0;
    let simulationCost = 0;

    // Cost weight per type (example values, adjust as needed)
    const costWeight: Record<string, number> = {
        roboticArm: 50,
        machine: 100,
        human: 30,
        transfer: 20,
        storageUnit: 10,
    };
    const energyUsage = assets.filter((a) => a.type === "human").reduce((sum, a) => sum + a.activeTime * 1, 0);

    assets.forEach((asset) => {
        totalActiveTime += asset.activeTime;
        totalIdleTime += asset.idleTime;

        if (asset.activeTime > 0) throughput += 1;

        productionCapacity += asset.activeTime;
        simulationCost += asset.activeTime * (costWeight[asset.type] || 10);
    });

    const machineActiveTime = assets.filter((a) => a.type === "machine").reduce((acc, a) => acc + a.activeTime, 0);

    const machineIdleTime = assets.filter((a) => a.type === "machine").reduce((acc, a) => acc + a.idleTime, 0);

    const simulationTime = totalActiveTime + totalIdleTime;

    // --- Efficiency Score ---
    // Weighted formula: lower cost + lower time => higher score
    // Example formula (normalize to 0–100):
    const efficiencyScore = Math.max(
        0,
        100 -
            (simulationTime / 1000) * 0.5 - // weight 0.5 for time
            (simulationCost / 1000) * 0.5 // weight 0.5 for cost
    );

    return {
        throughputData: throughput,
        machineActiveTime,
        machineIdleTime,
        productionCapacity,
        netProfit: 0, // placeholder
        roiPercentage: 0, // placeholder
        paybackPeriod: 0, // placeholder
        simulationTime,
        simulationCost,
        efficiencyScore,
        energyUsage,
    };
};

export const createCompareProduct = (productUuid: string, productName: string, assets: AssetData[]): CompareProduct => ({
    productUuid,
    productName,
    simulationData: calculateSimulationData(assets),
});

function ComparisonScene() {
    const { isPlaying } = usePlayButtonStore();
    const { productStore, versionStore } = useSceneContext();
    const { versionHistory, selectedVersion, setSelectedVersion } = versionStore();
    const { products, selectedProduct } = productStore();
    const { isComparing } = useIsComparing();
    const { activeModule } = useModuleStore();
    const { mainScene, comparisonScene, setComparisonState } = useSimulationState();
    const { loadingProgress } = useLoadingProgress();
    const { projectId } = useParams();
    const { setCompareProductsData } = useCompareProductDataStore();
    const [shouldShowComparisonResult, setShouldShowComparisonResult] = useState(false);

    const handleSelectVersion = (option: string) => {
        const version = versionHistory.find((version) => version.versionName === option);
        if (version) {
            setSelectedVersion(version);
        }
    };

    const handleSelectProduct = (option: string) => {
        const product = products.find((product) => product.productName === option);
        if (product && selectedVersion) {
            const data = {
                productUuid: product.productUuid,
                productName: product.productName,
                versionUuid: selectedVersion.versionId,
                versionName: selectedVersion.versionName,
            };
            setComparisonState(data);
        }
    };

    // useEffect(() => {
    //     if (mainProduct && comparisonProduct && compareProductsData.length > 1) {
    //         const hasMain = compareProductsData.some((val) => val.productUuid === mainProduct.productUuid);
    //         const hasComparison = compareProductsData.some((val) => val.productUuid === comparisonProduct.productUuid);
    //         if (hasMain && hasComparison && mainProduct.productUuid !== comparisonProduct.productUuid) {
    //             setShouldShowComparisonResult(true);
    //         } else {
    //             setShouldShowComparisonResult(false);
    //         }
    //     } else {
    //         setShouldShowComparisonResult(false);
    //     }
    // }, [compareProductsData, mainProduct, comparisonProduct]);

    useEffect(() => {
        // const selectedProductData = getProductById(selectedProduct.productUuid);
        if (mainScene && comparisonScene && selectedVersion) {
            const product1 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, mainScene.product.productUuid);

            const product2 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, comparisonScene.product.productUuid);

            const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainScene.product.productName, product1?.simulateData || []);
            const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonScene.product.productName, product2?.simulateData || []);

            const comparedArray = [compareProduct1, compareProduct2];

            if (product1 === undefined || product2 === undefined) {
                setShouldShowComparisonResult(false);
            } else if (comparedArray.length === 2) {
                setCompareProductsData(comparedArray);
                setShouldShowComparisonResult(true);
            }
        } else {
            setShouldShowComparisonResult(false);
        }
    }, [mainScene, comparisonScene, selectedVersion, projectId, setCompareProductsData]);

    return (
        <>
            {isComparing && activeModule === "simulation" && selectedProduct && (
                <>
                    {selectedVersion && !isPlaying && (
                        <div className="initial-selectLayout-wrapper">
                            <RegularDropDown
                                header={selectedVersion.versionName}
                                options={versionHistory.map((v) => v.versionName)} // Pass layout names as options
                                onSelect={handleSelectVersion}
                                search={false}
                            />
                            <br />
                            <RegularDropDown
                                header={selectedProduct.productName}
                                options={products.map((l) => l.productName)} // Pass layout names as options
                                onSelect={handleSelectProduct}
                                search={false}
                            />
                        </div>
                    )}
                    <CompareLayOut />

                    {shouldShowComparisonResult && !loadingProgress && <ComparisonResult />}
                </>
            )}
        </>
    );
}

export default ComparisonScene;
