import { useEffect, useState } from "react";
import InputWithDropDown from "../../../ui/inputs/InputWithDropDown";

import defaultTexture from '../../../../assets/textures/floor/wall-tex.png';
import wallTexture1 from '../../../../assets/textures/floor/factory wall texture.jpg';

import { useBuilderStore } from "../../../../store/builder/useBuilderStore";
import { useSceneContext } from "../../../../modules/scene/sceneContext";
import { useVersionContext } from "../../../../modules/builder/version/versionContext";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
import { useSocketStore } from "../../../../store/builder/store";

// import { upsertWallApi } from "../../../../services/factoryBuilder/wall/upsertWallApi";

const SelectedWallProperties = () => {
    const [height, setHeight] = useState("");
    const [thickness, setThickness] = useState("");
    const { selectedWall } = useBuilderStore();
    const { wallStore } = useSceneContext();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { socket } = useSocketStore();
    const { userId, organization } = getUserData();
    const { projectId } = useParams();
    const { getWallById, updateWall } = wallStore();

    const [activeSide, setActiveSide] = useState<"side1" | "side2">("side1");

    const materials = [
        { texture: defaultTexture, textureId: "Default Material", textureName: "Default Material" },
        { texture: wallTexture1, textureId: "Material 1", textureName: "Grunge Concrete Wall" }
    ];

    const wall = selectedWall ? getWallById(selectedWall.userData.wallUuid) : null;

    useEffect(() => {
        if (wall) {
            setHeight(wall.wallHeight.toString());
            setThickness(wall.wallThickness.toString());
        }
    }, [wall, selectedWall]);

    const handleHeightChange = (val: string) => {
        setHeight(val);
        const height = parseFloat(val);
        if (!isNaN(height) && wall) {
            const updatedWall = updateWall(wall.wallUuid, { wallHeight: height });
            if (updatedWall && projectId) {

                // API

                // upsertWallApi(projectId, selectedVersion?.versionId || '', updatedWall);

                // SOCKET

                const data = {
                    wallData: updatedWall,
                    projectId: projectId,
                    versionId: selectedVersion?.versionId || '',
                    userId: userId,
                    organization: organization
                }

                socket.emit('v1:model-Wall:add', data);
            }
        }
    };

    const handleThicknessChange = (val: string) => {
        setThickness(val);
        const thickness = parseFloat(val);
        if (!isNaN(thickness) && wall) {
            const updatedWall = updateWall(wall.wallUuid, { wallThickness: thickness });
            if (updatedWall && projectId) {

                // API

                // upsertWallApi(projectId, selectedVersion?.versionId || '', updatedWall);

                // SOCKET

                const data = {
                    wallData: updatedWall,
                    projectId: projectId,
                    versionId: selectedVersion?.versionId || '',
                    userId: userId,
                    organization: organization
                }

                socket.emit('v1:model-Wall:add', data);
            }
        }
    };

    const handleSelectMaterial = (material: { textureId: string; textureName: string }) => {
        if (!wall) return;

        const updated = (activeSide === "side1" ? { insideMaterial: material.textureId } : { outsideMaterial: material.textureId })
        const updatedWall = updateWall(wall.wallUuid, updated);
        if (updatedWall && projectId) {

            // API

            // upsertWallApi(projectId, selectedVersion?.versionId || '', updatedWall);

            // SOCKET

            const data = {
                wallData: updatedWall,
                projectId: projectId,
                versionId: selectedVersion?.versionId || '',
                userId: userId,
                organization: organization
            }

            socket.emit('v1:model-Wall:add', data);
        }
    };

    if (!wall) return null;

    const selectedMaterials = {
        side1: materials.find((m) => m.textureId === wall.insideMaterial) ?? materials[0],
        side2: materials.find((m) => m.textureId === wall.outsideMaterial) ?? materials[0]
    };

    return (
        <div className="wall-properties-container">
            <section className="wall-properties-section">
                <div className="header">Wall</div>
                <div className="wall-properties">
                    <InputWithDropDown
                        label="Height"
                        value={height}
                        min={1}
                        max={25}
                        step={1}
                        onChange={handleHeightChange}
                    />
                    <InputWithDropDown
                        label="Thickness"
                        value={thickness}
                        min={0.1}
                        max={2}
                        step={0.1}
                        onChange={handleThicknessChange}
                    />
                </div>
            </section>
            <section>
                <div className="header-wrapper">
                    <div className="header">Materials</div>
                </div>

                <div className="material-preview">
                    <div className="sides-wrapper">
                        {(["side1", "side2"] as const).map((side) => (
                            <button
                                key={side}
                                className={`side-wrapper ${activeSide === side ? "active" : ""}`}
                                onClick={() => setActiveSide(side)}
                            >
                                <div className="label">Side {side === "side1" ? 1 : 2}</div>
                                <div className="texture-image">
                                    <img
                                        draggable={false}
                                        src={selectedMaterials[side].texture}
                                        alt={selectedMaterials[side].textureName}
                                    />
                                </div>
                            </button>
                        ))}
                    </div>

                    <div className="preview">
                        <img
                            draggable={false}
                            src={selectedMaterials[activeSide].texture}
                            alt={selectedMaterials[activeSide].textureName}
                        />
                    </div>
                </div>

                <div className="materials">
                    <div className="material-container">
                        {materials.map((material, index) => {
                            const isSelected = selectedMaterials[activeSide].textureId === material.textureId;

                            return (
                                <button
                                    className={`material-wrapper ${isSelected ? "selectedMaterial" : ""}`}
                                    key={`${material.textureName}_${index}`}
                                    onClick={() => handleSelectMaterial(material)}
                                >
                                    <div className="material-property">
                                        <div className="material-image">
                                            <img
                                                draggable={false}
                                                src={material.texture}
                                                alt={material.textureName}
                                            />
                                        </div>
                                        <div className="material-name">{material.textureName}</div>
                                    </div>
                                </button>
                            );
                        })}
                    </div>
                </div>
            </section>
        </div>
    );
};

export default SelectedWallProperties;
