import React, { useEffect, useState } from "react";
import InputRange from "../../../ui/inputs/InputRange";
import InputToggle from "../../../ui/inputs/InputToggle";
import { AI_Icon } from "../../../icons/ExportCommonIcons";
import LabeledButton from "../../../ui/inputs/LabledButton";
import {
  useAzimuth,
  useElevation,
  useLimitDistance,
  useRenderDistance,
  useResetCamera,
  useRoofVisibility,
  useSelectedWallItem,
  useShadows,
  useSocketStore,
  useTileDistance,
  useToggleView,
  useWallVisibility,
} from "../../../../store/store";
import { setEnvironment } from "../../../../services/factoryBuilder/environment/setEnvironment";
import * as CONSTANTS from "../../../../types/world/worldConstants";
import { validateBBox } from "@turf/helpers";
const GlobalProperties: React.FC = () => {
  const { toggleView, setToggleView } = useToggleView();
  const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();
  const { roofVisibility, setRoofVisibility } = useRoofVisibility();
  const { wallVisibility, setWallVisibility } = useWallVisibility();
  const { shadows, setShadows } = useShadows();
  const { resetCamera, setResetCamera } = useResetCamera();
  const { elevation, setElevation } = useElevation();
  const { azimuth, setAzimuth } = useAzimuth();
  const { renderDistance, setRenderDistance } = useRenderDistance();
  const { setPlaneValue, setGridValue, planeValue, gridValue } =
    useTileDistance();
  useEffect(() => {
 
  }, [gridValue, planeValue]);
  const { socket } = useSocketStore();
  const { limitDistance, setLimitDistance } = useLimitDistance();
  const [distance, setDistance] = useState<number>(40);
  useEffect(() => {}, [limitDistance]);

  const [limitGridDistance, setLimitGridDistance] = useState(false);
  const [gridDistance, setGridDistance] = useState<number>(3);

  const optimizeScene = async (value: any) => {
    const email = localStorage.getItem("email");
    const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";

    const data = await setEnvironment(
      organization,
      localStorage.getItem("userId")!,
      wallVisibility,
      roofVisibility,
      shadows,
      30,
      true
    );
    setRenderDistance(30);
    setLimitDistance(true);
  };
  const limitRenderDistance = async () => {
    const email = localStorage.getItem("email");
    const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";

    if (limitDistance) {
      let data = await setEnvironment(
        organization,
        localStorage.getItem("userId")!,
        wallVisibility,
        roofVisibility,
        shadows,
        75,
        !limitDistance
      );
      setRenderDistance(75);
    } else {
      let data = await setEnvironment(
        organization,
        localStorage.getItem("userId")!,
        wallVisibility,
        roofVisibility,
        shadows,
        renderDistance,
        !limitDistance
      );
    }
    setLimitDistance(!limitDistance);
  };

  function updateDistance(value: number) {
    setDistance(value);
    setRenderDistance(value);
  }
  function updateGridDistance(value: number) {
    setGridDistance(value);
    // setGridValue({ size: value * 100, divisions: (value * 100) / 4 });
    // setPlaneValue({ height: value * 100, width: value * 100 });
  }
  function updatedGrid(value: number) {
    console.log(" (value * 100) / 4 : ", (value * 100) / 4);
    setGridValue({ size: value * 100, divisions: (value * 100) / 4 });
    setPlaneValue({ height: value * 100, width: value * 100 });
  }

  const updatedDist = async (value: number) => {
    const email = localStorage.getItem("email");
    const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";
    setRenderDistance(value);
    // setDistance(value);
    const data = await setEnvironment(
      organization,
      localStorage.getItem("userId")!,
      wallVisibility,
      roofVisibility,
      shadows,
      value,
      limitDistance
    );
  };

  // Function to toggle roof visibility
  const changeRoofVisibility = async () => {
    const email = localStorage.getItem("email");
    const organization = email!.split("@")[1].split(".")[0];

    //using REST
    const data = await setEnvironment(
      organization,
      localStorage.getItem("userId")!,
      wallVisibility,
      !roofVisibility,
      shadows,
      renderDistance,
      limitDistance
    );
    //

    //using Socket
    // const visData = {
    //   organization: organization,
    //   userId: localStorage.getItem('userId')!,
    //   wallVisibility: wallVisibility,
    //   roofVisibility: !roofVisibility,
    //   shadowVisibility: shadows,
    //   socketId: socket.id
    // };
    // socket.emit('v1:Environment:set', visData)

    setRoofVisibility(!roofVisibility); // Toggle roof visibility
  };
  // Function to toggle wall visibility
  const changeWallVisibility = async () => {
    const email = localStorage.getItem("email");
    const organization = email!.split("@")[1].split(".")[0];
    //using REST
    const data = await setEnvironment(
      organization,
      localStorage.getItem("userId")!,
      !wallVisibility,
      roofVisibility,
      shadows,
      renderDistance,
      limitDistance
    );
    //

    //using Socket
    // const visData = {
    //   organization: organization,
    //   userId: localStorage.getItem('userId')!,
    //   wallVisibility: !wallVisibility,
    //   roofVisibility: roofVisibility,
    //   shadowVisibility: shadows,
    //   socketId: socket.id
    // };
    // socket.emit('v1:Environment:set', visData)

    setWallVisibility(!wallVisibility); // Toggle wall visibility
  };

  const shadowVisibility = async () => {
    const email = localStorage.getItem("email");
    const organization = email!.split("@")[1].split(".")[0];
    //using REST
    const data = await setEnvironment(
      organization,
      localStorage.getItem("userId")!,
      wallVisibility,
      roofVisibility,
      !shadows,
      renderDistance,
      limitDistance
    );
    //

    //using Socket
    // const visData = {
    //   organization: organization,
    //   userId: localStorage.getItem('userId')!,
    //   wallVisibility: wallVisibility,
    //   roofVisibility: roofVisibility,
    //   shadowVisibility: !shadows,
    //   socketId: socket.id
    // };
    // socket.emit('v1:Environment:set', visData)

    setShadows(!shadows);
  };
  const toggleResetCamera = () => {
    if (!toggleView) {
      setResetCamera(true); // Trigger reset camera action
    }
  };

  // function changeRenderDistance(e: any) {
  //   if (parseInt(e.target.value) < 20) {
  //     setRenderDistance(20);
  //   } else if (parseInt(e.target.value) > 75) {
  //     setRenderDistance(75);
  //   } else {
  //     setRenderDistance(parseInt(e.target.value));
  //   }
  // }
  return (
    <div className="global-properties-container">
      <div className="header">Environment</div>
      <div className="optimize-button" onClick={optimizeScene}>
        <AI_Icon />
        Optimize
      </div>

      <div className="split"></div>

      <InputToggle
        value={roofVisibility}
        inputKey="1"
        label="Roof Visibility"
        onClick={changeRoofVisibility}
      />
      <InputToggle
        value={wallVisibility}
        inputKey="2"
        label="Wall Visibility"
        onClick={changeWallVisibility}
      />
      <InputToggle
        value={shadows}
        inputKey="3"
        label="Shadows Visibility"
        onClick={shadowVisibility}
      />
      <LabeledButton
        label="Reset Camera"
        onClick={toggleResetCamera}
        value="Reset"
      />

      <div className="split"></div>
      {/* //visibleEdgeColor={CONSTANTS.outlineConfig.assetDeleteColor} */}
      <InputToggle
        inputKey="4"
        label="Limit Render Distance"
        value={limitDistance}
        // onClick={() => {
        //   setLimitDistance(!limitDistance);
        //   // setDistance(75);
        //   // setRenderDistance(75);
        // }}
        onClick={async () => {
          await limitRenderDistance(); // Call the function here
        }}
      />
      <InputRange
        label="Distance"
        disabled={!limitDistance}
        value={renderDistance}
        min={CONSTANTS.distanceConfig.minDistance}
        max={CONSTANTS.distanceConfig.maxDistance}
        onChange={(value: number) => updateDistance(value)}
        onPointerUp={updatedDist}
        key={"6"}
      />

      <div className="split"></div>

      <InputToggle
        inputKey="6"
        label="Display Grid"
        value={limitGridDistance}
        onClick={() => {
          setLimitGridDistance(!limitGridDistance);
        }}
      />
      <InputRange
        label="Tile Distance"
        disabled={!limitGridDistance}
        value={gridDistance}
        key={"7"}
        min={1}
        max={5}
        onChange={(value: number) => updateGridDistance(value)}
        onPointerUp={updatedGrid}
      />
    </div>
  );
};

export default GlobalProperties;
