import { useEffect, useState } from 'react'
// import NavigateCatagory from '../../NavigateCatagory'
import { EyeIcon, KebabIcon, LocationPinIcon, RightHalfFillCircleIcon } from '../../../../../icons/ExportCommonIcons';
import assetImageFallback from "../../../../../../assets/image/asset-image.png"
import { useSceneContext } from '../../../../../../modules/scene/sceneContext';
import RenameInput from '../../../../../ui/inputs/RenameInput';
import { useResourceManagementId } from '../../../../../../store/builder/store';
import { getAssetThumbnail } from '../../../../../../services/factoryBuilder/asset/assets/getAssetThumbnail';
import { TypeBasedAssetIcons } from '../../../../../icons/AssetTypeIcons';

const AssetManagement = () => {
    // const [selectedCategory, setSelectedCategory] = useState("All Assets");
    const [expandedAssetId, setExpandedAssetId] = useState<string | null>(null);
    const [assets, setAssets] = useState<any[]>([]);
    const { setResourceManagementId } = useResourceManagementId();
    const { assetStore } = useSceneContext();
    const { assets: allAssets } = assetStore();

    async function getAsset(assetId: string) {
        let thumbnail = await getAssetThumbnail(assetId)
        if (thumbnail.thumbnail) {
            let assetImage = thumbnail.thumbnail ?? assetImageFallback;
            return assetImage;
        }
    }

    useEffect(() => {
        if (allAssets.length > 0) {
            const fetchAssets = async () => {
                const grouped: Record<string, any> = {};

                // Use Promise.all to handle all async operations
                await Promise.all(allAssets.map(async (asset: any) => {
                    
                    if (asset.eventData.type === "Storage" || asset.eventData.type === "Human") return;

                    const assetImage = await getAsset(asset.assetId);

                    if (!grouped[asset.assetId]) {
                        // 
                        grouped[asset.assetId] = {
                            id: asset.modelUuid,
                            assetId: asset.assetId,
                            name: asset.modelName,
                            type: asset.eventData.type,
                            model: asset.modelCode ?? "N/A",
                            status: asset.status ?? "Online",
                            usageRate: asset.usageRate ?? 15,
                            level: asset.level ?? "Level 1",
                            image: assetImage,
                            description: asset.description ?? "No description",
                            cost: asset.cost ?? 0,
                            count: 1,
                        };
                    } else {
                        grouped[asset.assetId].count += 1;
                    }
                }));

                setAssets(Object.values(grouped));
            }
            fetchAssets();
        }
    }, [allAssets]);

    function handleRenameAsset(newName: string) {

    }

    useEffect(() => {


    }, [assets]);

    function handleAssetClick(id: string) {
        setResourceManagementId(id);
    }

    // const dummyAssets = [
    //     {
    //         id: '1',
    //         name: 'Forklift Model X200',
    //         model: 'FLK-0025',
    //         status: 'Online',
    //         usageRate: 15,
    //         level: 'Level 1',
    //         image: assetImage,
    //         description: 'Electric forklift used for moving goods and materials in warehouse operations.',
    //         cost: 122000,
    //         count: 5,
    //     },
    //     {
    //         id: '2',
    //         name: 'Warehouse Robot WR-300',
    //         model: 'WRB-3001',
    //         status: 'Online',
    //         usageRate: 50,
    //         level: 'Level 2',
    //         image: assetImage,
    //         description: 'Automated robot for handling packages and inventory in the warehouse.',
    //         cost: 85000,
    //         count: 3,
    //     },
    //     {
    //         id: '3',
    //         name: 'Conveyor Belt System CB-150',
    //         model: 'CBS-150X',
    //         status: 'Online',
    //         usageRate: 95,
    //         level: 'Level 3',
    //         image: assetImage,
    //         description: 'High-speed conveyor belt system for efficient material handling.',
    //         cost: 45000,
    //         count: 2,
    //     },
    // ];


    return (
        <>
            {/* <NavigateCatagory
                    category={["All Assets", "Machines", "Workstation", "Vehicles"]}
                    selectedCategory={selectedCategory}
                    setSelectedCategory={setSelectedCategory}
                /> */}

            <div className='assetManagement-container assetManagement-wrapper'>
                {assets.map((asset, index) => (
                    <div className={`assetManagement-card-wrapper ${expandedAssetId === asset.id ? "openViewMore" : ""}`} key={index}>
                        <header>
                            <div className="header-wrapper">
                                {expandedAssetId === asset.id ?
                                    <>
                                        <div className="drop-icon" onClick={() => setExpandedAssetId(null)}>▾</div>
                                        <img className='asset-image' src={asset.image} alt="" />
                                    </>
                                    :
                                    <div className="icon"><TypeBasedAssetIcons assetType={asset.type}/></div>
                                }
                                <div className="asset-details-container">
                                    <div className="asset-details" >
                                        {/* <div className="asset-name">{asset.name}</div> */}
                                        <RenameInput value={asset.name} onRename={handleRenameAsset} />
                                        {asset.count !== 1 && <div>
                                            <span className="asset-id-label">x</span>
                                            <span className="asset-id">{asset.count}</span>
                                        </div>}
                                        <div className="asset-model">{asset.model}</div>
                                    </div>
                                    <div className="asset-status-wrapper">
                                        <div className={`indication ${asset.status}`}></div>
                                        <div className="status">{asset.status}</div>
                                    </div>
                                </div>

                            </div>
                            {expandedAssetId === asset.id && <div className="description">{asset.description}</div>}
                        </header>

                        {expandedAssetId === asset.id ? (
                            <div className="asset-estimate">
                                <div className="asset-estimate__unit-cost">
                                    <div className="asset-estimate__label">Cost of Asset</div>
                                    <div className="asset-estimate__value">₹ 1,22,000</div>
                                </div>

                                <div className="asset-estimate__breakdown">
                                    <div className="asset-estimate__in-scene">
                                        <div className="asset-estimate__label">In Scene</div>
                                        <div className="asset-estimate__value">5 items</div>
                                    </div>
                                    <div className="asset-estimate__total-cost">
                                        <div className="asset-estimate__label">Total Cost</div>
                                        <div className="asset-estimate__value">₹ 6,10,000</div>
                                    </div>
                                </div>

                                <div className="asset-estimate__view-button" onClick={() => handleAssetClick(asset.id)}>
                                    <EyeIcon isClosed={false} />
                                    <div className="asset-estimate__view-text">View in Scene</div>
                                </div>
                            </div>


                        ) : (
                            <div className="asset-contents">
                                <div className="asset-wrapper">
                                    <div className="key-wrapper">
                                        <div className="icon"><RightHalfFillCircleIcon /></div>
                                        <div className="key">Usage rate</div>
                                    </div>
                                    <div className="progress-wrapper">
                                        <div className="progress-bar">
                                            <div
                                                className="filled-value"
                                                style={{ width: `${asset.usageRate}%` }}
                                            ></div>
                                        </div>
                                        <div className="usage-value">{asset.usageRate}%</div>
                                    </div>
                                </div>

                                <div className="asset-wrapper">
                                    <div className="key-wrapper">
                                        <div className="icon"><LocationPinIcon /></div>
                                        <div className="key">{asset.level}</div>
                                    </div>

                                    <div
                                        className="viewMore"
                                        onClick={() =>
                                            setExpandedAssetId(expandedAssetId === asset.id ? null : asset.id)
                                        }
                                    >
                                        <div className="value">{expandedAssetId === asset.id ? "View Less" : "View More"}</div>
                                        <div className="icon"><KebabIcon /></div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                ))}
            </div >
        </>
    )
}

export default AssetManagement


