import React, { useEffect, useState } from "react";
import MultiLevelDropdown from "../../../../ui/inputs/MultiLevelDropDown";
import { AddIcon } from "../../../../icons/ExportCommonIcons";
import RegularDropDown from "../../../../ui/inputs/RegularDropDown";
import useChartStore from "../../../../../store/visualization/useChartStore";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
import { get3dWidgetInput } from "../../../../../services/visulization/zone/get3dWidgetInput";
import { useVersionContext } from "../../../../../modules/builder/version/versionContext";
import { useParams } from "react-router-dom";
import { adding3dWidgets } from "../../../../../services/visulization/zone/add3dWidget";

const Widget3InputCard3D = () => {
  const { selectedChartId } = useWidgetStore();
  const [widgetName, setWidgetName] = useState("untited");
  const { setMeasurements, updateDuration, updateName } = useChartStore();
  const [duration, setDuration] = useState("1h");
  const [dropDowndata, setDropDownData] = useState({});
  const [selections, setSelections] = useState<
    Record<string, { name: string; fields: string }>
  >({});
  const { selectedZone } = useSelectedZoneStore();
  const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
  const { userName, userId, organization, email } = getUserData();
  const [isLoading, setLoading] = useState<boolean>(true);
  const { selectedVersionStore } = useVersionContext();
  const { selectedVersion } = selectedVersionStore();
  const { projectId } = useParams()

  useEffect(() => {
    const fetchZoneData = async () => {
      try {
        setLoading(true);
        const response = await axios.get(`http://${iotApiUrl}/getinput`);
        if (response.status === 200) {
          // 
          setDropDownData(response.data);
          setLoading(false);
        } else {
          // 
        }
      } catch (error) {
        echo.error("Failed to fetch zone data");
        
      }
    };
    fetchZoneData();
  }, []);

  useEffect(() => {
    const fetchSavedInputes = async () => {
      if (selectedChartId.id !== "") {
        let response = await get3dWidgetInput(selectedChartId.id, organization, projectId, selectedVersion?.versionId || "")
        
        if (response) {
          setSelections(response.Datastructure.measurements);
          setDuration(response.Datastructure.duration);
          setWidgetName(response.widgetName);
        }

      }
    };

    fetchSavedInputes();
  }, [selectedChartId.id]);

  useEffect(() => {
    setMeasurements(selections);
    updateDuration(duration);
    updateName(widgetName);
  }, [selections, duration, widgetName]);

  const sendInputes = async (
    inputMeasurement: any,
    inputDuration: any,
    inputName: any
  ) => {

    let newWidget = {
      id: selectedChartId.id,
      widgetName: inputName,
      Data: {
        measurements: inputMeasurement,
        duration: inputDuration,
      },
    }

    let response = await adding3dWidgets(selectedZone.zoneUuid, organization, newWidget, projectId, selectedVersion?.versionId || "")
    
    if (response.message === "widget update successfully") {
      return true;
    } else {
      return false
    }

    // try {
    //   const response = await axios.post(
    //     `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`,
    //     {
    //       headers: {
    //         Authorization: "Bearer <access_token>",
    //         "Content-Type": "application/json",
    //         token: localStorage.getItem("token") || "",
    //         refresh_token: localStorage.getItem("refreshToken") || "",
    //       },
    //     },
    //     {
    //       organization,
    //       zoneUuid: selectedZone.zoneUuid,
    //       widget: {
    //         id: selectedChartId.id,
    //         widgetName: inputName,
    //         Data: {
    //           measurements: inputMeasurement,
    //           duration: inputDuration,
    //         },
    //       },
    //       projectId: projectId,
    //       versionId: selectedVersion?.versionId || ""
    //     } as any
    //   );
    //   
    //   if (response.status === 200) {
    //     return true;
    //   } else {
    //     // 
    //     return false;
    //   }
    // } catch (error) {
    //   echo.error("Failed to send input");
    //   
    //   return false;
    // }
  };

  const handleSelect = async (
    inputKey: string,
    selectedData: { name: string; fields: string } | null
  ) => {
    // async() => {
    const newSelections = { ...selections };
    if (selectedData === null) {
      delete newSelections[inputKey];
    } else {
      newSelections[inputKey] = selectedData;
    }
    // setMeasurements(newSelections); // Update Zustand store
    // 
    if (await sendInputes(newSelections, duration, widgetName)) {
      setSelections(newSelections);
    }
  };

  const handleSelectDuration = async (option: string) => {
    if (await sendInputes(selections, option, widgetName)) {
      setDuration(option);
    }
  };

  const handleNameChange = async (name: any) => {
    // 

    if (await sendInputes(selections, duration, name)) {
      setWidgetName(name);
    }
  };

  return (
    <>
      <div className="inputs-wrapper">
        <div className="datas">
          <div className="datas__label">Title</div>
          <RenameInput value={widgetName} onRename={handleNameChange} />
        </div>
        {[...Array(7)].map((_, index) => {
          const inputKey = `input${index + 1}`;
          return (
            <div key={index} className="datas">
              <div className="datas__label">Input {index + 1}</div>
              <div className="datas__class">
                <MultiLevelDropdown
                  data={dropDowndata}
                  onSelect={(selectedData) =>
                    handleSelect(inputKey, selectedData)
                  }
                  onUnselect={() => handleSelect(inputKey, null)}
                  selectedValue={selections[inputKey]} // Load from Zustand
                  isLoading={isLoading}
                  allSelections={selections}
                />
                <div className="icon">
                  <AddIcon />
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default Widget3InputCard3D;
