import React, { useEffect } from "react";
import RenameInput from "../../../ui/inputs/RenameInput";
import Vector3Input from "../customInput/Vector3Input";
import { useSelectedZoneStore } from "../../../../store/visualization/useZoneStore";
import {
  useEditPosition,
  usezonePosition,
  usezoneTarget,
} from "../../../../store/builder/store";
import { zoneCameraUpdate } from "../../../../services/visulization/zone/zoneCameraUpdation";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
import { useVersionContext } from "../../../../modules/builder/version/versionContext";
import { useSceneContext } from "../../../../modules/scene/sceneContext";

const ZoneProperties: React.FC = () => {
  const { Edit, setEdit } = useEditPosition();
  const { selectedZone, setSelectedZone } = useSelectedZoneStore();
  const { zonePosition, setZonePosition } = usezonePosition();
  const { zoneTarget, setZoneTarget } = usezoneTarget();
  const { zoneStore } = useSceneContext();
  const { zones, setZoneName } = zoneStore()

  const { projectId } = useParams();
  const { organization } = getUserData();
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();

  useEffect(() => {
    setZonePosition(selectedZone.zoneViewPortPosition);
    setZoneTarget(selectedZone.zoneViewPortTarget);
  }, [selectedZone?.zoneViewPortPosition, selectedZone?.zoneViewPortTarget]);

  async function handleSetView() {
    try {

      let zonesdata = {
        zoneUuid: selectedZone.zoneUuid,
        viewPortPosition: zonePosition,
        viewPortTarget: zoneTarget,
      };


      let response = await zoneCameraUpdate(zonesdata, organization, projectId, selectedVersion?.versionId || "");
      // console.log('response: ', response);
      if (response.message === "zone updated") {
        setEdit(false);
      } else {
        // console.log(response);
      }
    } catch (error) {
      echo.error("Failed to set zone view");
    }
  }

  function handleEditView() {
    setEdit(!Edit); // This will toggle the `Edit` state correctly
  }

  async function handleZoneNameChange(newName: string) {
    const zonesdata = {
      zoneUuid: selectedZone.zoneUuid,
      zoneName: newName,
    };
    // Call your API to update the zone
    let response = await zoneCameraUpdate(zonesdata, organization, projectId, selectedVersion?.versionId || "");
    if (response.message === "zone updated") {
      setSelectedZone((prev) => ({ ...prev, zoneName: newName }));
      setZoneName(selectedZone.zoneUuid, newName)
      // setZones((prevZones: any[]) =>
      //   prevZones.map((zone) =>
      //     zone.zoneUuid === selectedZone.zoneUuid
      //       ? { ...zone, zoneName: newName }
      //       : zone
      //   )
      // );
    } else {
      // console.log(response?.message);
    }
  }
  function handleVectorChange(
    key: "zoneViewPortTarget" | "zoneViewPortPosition",
    newValue: [number, number, number]
  ) {
    setSelectedZone((prev) => ({ ...prev, [key]: newValue }));
  }
  const checkZoneNameDuplicate = (name: string) => {
    console.log('zones: ', zones);
    return zones.some(
      (zone: any) =>
        zone.zoneName?.trim().toLowerCase() === name?.trim().toLowerCase() &&
        zone.zoneUuid !== selectedZone.zoneUuid
    );
  };

  return (
    <div className="zone-properties-container">
      <section>
        <div className="header">
          <RenameInput
            value={selectedZone.zoneName}
            onRename={handleZoneNameChange}
            checkDuplicate={checkZoneNameDuplicate}
          />
          <div className="button" onClick={handleEditView}>
            {Edit ? "Cancel" : "Edit"}
          </div>
        </div>
        <Vector3Input
          onChange={(value) => handleVectorChange("zoneViewPortTarget", value)}
          header="Viewport Target"
          value={zoneTarget as [number, number, number]}
          disabled={!Edit}
        />
        <Vector3Input
          onChange={(value) =>
            handleVectorChange("zoneViewPortPosition", value)
          }
          header="Viewport Position"
          value={zonePosition as [number, number, number]}
          disabled={!Edit}
        />

        {Edit && (
          <div className="button-save" onClick={handleSetView}>
            Set View
          </div>
        )}
      </section>
    </div>
  );
};

export default ZoneProperties;
