import React, { useEffect, useState } from "react";
import RenameInput from "../inputs/RenameInput";

import { useSelectedZoneStore } from "../../../store/useZoneStore";
import { getZoneData } from "../../../services/realTimeVisulization/zoneData/getZones";
import useModuleStore, {
  useSubModuleStore,
} from "../../../store/useModuleStore";
import {
  ArrowIcon,
  EyeIcon,
  LockIcon,
  RmoveIcon,
} from "../../icons/ExportCommonIcons";
import { useThree } from "@react-three/fiber";
import { useFloorItems, useZoneAssetId } from "../../../store/store";
import { zoneCameraUpdate } from "../../../services/realTimeVisulization/zoneData/zoneCameraUpdation";
import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi";

interface Asset {
  id: string;
  name: string;
  position?: [number, number, number]; // Proper 3D vector
  rotation?: { x: number; y: number; z: number }; // Proper rotation format
}

interface ZoneItem {
  id: string;
  name: string;
  assets?: Asset[];
}

interface ListProps {
  items?: ZoneItem[];
  placeholder?: string;
  remove?: boolean;
}

const List: React.FC<ListProps> = ({ items = [], remove }) => {
  const { activeModule, setActiveModule } = useModuleStore();
  const { selectedZone, setSelectedZone } = useSelectedZoneStore();
  const { zoneAssetId, setZoneAssetId } = useZoneAssetId();

  const { setSubModule } = useSubModuleStore();
  const [expandedZones, setExpandedZones] = useState<Record<string, boolean>>(
    {}
  );
  const { floorItems, setFloorItems } = useFloorItems();

  useEffect(() => {
    useSelectedZoneStore.getState().setSelectedZone({
      zoneName: "",
      activeSides: [],
      panelOrder: [],
      lockedPanels: [],
      zoneId: "",
      zoneViewPortTarget: [],
      zoneViewPortPosition: [],
      widgets: [],
    });
  }, [activeModule]);

  const toggleZoneExpansion = (zoneId: string) => {
    setExpandedZones((prev) => ({
      ...prev,
      [zoneId]: !prev[zoneId],
    }));
  };

  async function handleSelectZone(id: string) {
    try {
      if (selectedZone?.zoneId === id) {

        return;
      }

      setSubModule("zoneProperties");

      const email = localStorage.getItem("email");
      const organization = email?.split("@")[1]?.split(".")[0] || "";

      let response = await getZoneData(id, organization);

      setSelectedZone({
        zoneName: response?.zoneName,
        activeSides: response?.activeSides || [],
        panelOrder: response?.panelOrder || [],
        lockedPanels: response?.lockedPanels || [],
        widgets: response?.widgets || [],
        zoneId: response?.zoneId,
        zoneViewPortTarget: response?.viewPortCenter || [],
        zoneViewPortPosition: response?.viewPortposition || [],
      });


    } catch (error) {

    }
  }
  function handleAssetClick(asset: Asset) {
    setZoneAssetId(asset)
  }
  async function handleZoneNameChange(newName: string) {
    //zone apiiiiii
    const email = localStorage.getItem("email") || "";
    const organization = email?.split("@")[1]?.split(".")[0];
    let zonesdata = {
      zoneId: selectedZone.zoneId,
      zoneName: newName
    };
    let response = await zoneCameraUpdate(zonesdata, organization);
    if (response.message === "updated successfully") {
      setSelectedZone((prev) => ({ ...prev, zoneName: newName }));
    }
  }
  async function handleZoneAssetName(newName: string) {
    const email = localStorage.getItem("email") || "";
    const organization = email?.split("@")[1]?.split(".")[0];

    if (zoneAssetId?.id) {
      let response = await setFloorItemApi(organization, zoneAssetId.id, newName)
      console.log('response: ', response);
      setFloorItems((prevFloorItems: any[]) =>
        prevFloorItems.map((floorItems) =>
          floorItems.modeluuid === zoneAssetId.id
            ? { ...floorItems, modelname: response.modelname }
            : floorItems
        )
      );
    }
   
    console.log('newName: ', newName);

  }

  return (
    <>
      {items?.length > 0 ? (
        <ul className="list-wrapper">
          {items?.map((item) => (
            <React.Fragment key={`zone-${item.id}`}>
              <li className="list-container">
                <div className="list-item">
                  <div className="zone-header">
                    <div
                      className="value"
                      onClick={() => handleSelectZone(item.id)}
                    >
                      <RenameInput value={item.name} onRename={handleZoneNameChange} />
                    </div>
                  </div>
                  <div className="options-container">
                    <div className="lock option">
                      <LockIcon isLocked />
                    </div>
                    <div className="visibe option">
                      <EyeIcon isClosed />
                    </div>
                    {remove && (
                      <div className="remove option">
                        <RmoveIcon />
                      </div>
                    )}
                    {item.assets && item.assets.length > 0 && (
                      <div
                        className="expand-icon option"
                        onClick={() => toggleZoneExpansion(item.id)}
                      >
                        <ArrowIcon />
                      </div>
                    )}
                  </div>
                </div>
              </li>
              {/* Nested assets list - only shown when expanded */}
              {item.assets &&
                item.assets.length > 0 &&
                expandedZones[item.id] && (
                  <ul className="asset-list">
                    {item.assets.map((asset) => (
                      <li
                        key={`asset-${asset.id}`}
                        className="list-container asset-item"
                      >
                        <div className="list-item">
                          <div className="value" onClick={() => handleAssetClick(asset)} >
                            <RenameInput value={asset.name} onRename={handleZoneAssetName} />
                          </div>
                          <div className="options-container">
                            <div className="lock option">
                              <LockIcon isLocked />
                            </div>
                            <div className="visibe option">
                              <EyeIcon isClosed />
                            </div>
                            {remove && (
                              <div className="remove option">
                                <RmoveIcon />
                              </div>
                            )}
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
            </React.Fragment>
          ))}
        </ul>
      ) : (
        <div className="list-wrapper">
          <div className="no-item">No items to display</div>
        </div>
      )}
    </>
  );
};

export default List;
