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";
import { validateSimulationDataApi } from "../../../services/simulation/comparison/validateSimulationDataApi";
import { calculateSimulationData } from "./functions/calculateSimulationData";

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

export interface CompareProduct {
    productUuid: string;
    productName: string;
    simulationData: {
        roiPercentage: number;
        netProfit: number;
        productionCapacity: number;
        paybackPeriod: number;
        machineIdleTime: number;
        machineActiveTime: number;
        throughputData: number;
        simulationTime?: number;
        simulationCost?: number;
        efficiencyScore?: number;
        // totalCost: number;
        // revenueGenerated: number;
        // costPerUnit: number;
        //workingDaysPerYear: number;
        //shiftLength: number;
        //shiftsPerDay: number;
    };
}
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 { simulationRecords } = useSimulationManager();
    const { projectId } = useParams();
    const { setCompareProductsData } = useCompareProductDataStore();
    const [shouldShowComparisonResult, setShouldShowComparisonResult] = useState(false);
    const { addSimulationRecord } = useSimulationManager();

    useEffect(() => {});

    const handleSelectVersion = (option: string) => {
        const version = versionHistory.find((version) => version.versionName === option);
        if (version) {
            setSelectedVersion(version);
            const singleData = {
                projectId: projectId,
                versionId: selectedVersion?.versionId || "",
                productUuid: selectedProduct?.productUuid || "",
            };
            validateSimulationDataApi(singleData).then((getData) => {
                echo.log(getData.message);
                const getSimulate = getData?.data?.existingSimulatedData;
                if (!getSimulate) return;
                if (!selectedVersion?.versionId || !projectId || getSimulate === undefined || !selectedProduct.productUuid) {
                    echo.warn("No prebacked Data found");
                    alert("Please run the simulation before comparing.");
                    return;
                }
                addSimulationRecord(projectId, selectedVersion?.versionId || "", selectedProduct.productUuid || "", getSimulate.data);
            });
        }
    };

    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,
            };
            const singleData = {
                projectId: projectId,
                versionId: selectedVersion.versionId,
                productUuid: product.productUuid,
            };
            validateSimulationDataApi(singleData).then((getData) => {
                echo.warn(getData.message);
                const getSimulate = getData?.data?.existingSimulatedData;
                if (!getSimulate) return;
                addSimulationRecord(projectId, selectedVersion?.versionId || "", product.productUuid || "", getSimulate.data);
            });
            setComparisonState(data);
        }
    };

    useEffect(() => {
        if (mainScene && comparisonScene && selectedVersion) {
            const mainVersion = useSimulationManager.getState().getProductById(projectId, mainScene.version.versionUuid, mainScene.product.productUuid);

            const compareVersion = useSimulationManager.getState().getProductById(projectId, comparisonScene.version.versionUuid, comparisonScene.product.productUuid);

            const mainVompareversion = createCompareProduct(mainVersion?.productId ?? "", mainScene.product.productName, mainVersion?.simulateData || []);
            const compareProduct2 = createCompareProduct(compareVersion?.productId ?? "", comparisonScene.product.productName, compareVersion?.simulateData || []);

            const comparedArray = [mainVompareversion, compareProduct2];

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

    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;
