import { useEffect, useState } from "react";
import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { AddIcon, RemoveIcon } from "../../../../icons/ExportCommonIcons";
import MultiLevelDropDown from "../../../../ui/inputs/MultiLevelDropDown";

// Define the data structure for demonstration purposes
const DATA_STRUCTURE = {
  furnace: {
    coolingRate: "coolingRate",
    furnaceTemperature: "furnaceTemperature",
    heatingRate: "heatingRate",
    machineId: "machineId",
    powerConsumption: "powerConsumption",
    status: "status",
    timestamp: "timestamp",
    vacuumLevel: "vacuumLevel",
  },
  testDevice: {
    abrasiveLevel: {
      data1: "Data 1",
      data2: "Data 2",
      data3: "Data 3",
    },
    airPressure: "airPressure",
    machineId: "machineId",
    powerConsumption: "powerConsumption",
    status: "status",
    temperature: {
      data1: "Data 1",
      data2: "Data 2",
      data3: "Data 3",
    },
    timestamp: {
      data1: {
        Data01: "Data 01",
        Data02: "Data 02",
        Data03: "Data 03",
      },
      data2: "Data 2",
      data3: "Data 3",
    },
  },
};

interface Child {
  id: number;
  easing: string;
}

interface Group {
  id: number;
  easing: string;
  children: Child[];
}

const Data = () => {
  const { selectedChartId } = useWidgetStore();

  // State to store groups for all widgets (using Widget.id as keys)
  const [chartDataGroups, setChartDataGroups] = useState<
    Record<string, Group[]>
  >({});

  useEffect(() => {
    // Initialize data groups for the newly selected widget if it doesn't exist
    if (selectedChartId && !chartDataGroups[selectedChartId.id]) {
      setChartDataGroups((prev) => ({
        ...prev,
        [selectedChartId.id]: [
          {
            id: Date.now(),
            easing: "Connecter 1",
            children: [{ id: Date.now(), easing: "Linear" }],
          },
        ],
      }));
    }
  }, [selectedChartId]);

  // Handle adding a new child to the group
  const handleAddClick = (groupId: number) => {
    setChartDataGroups((prevGroups) => {
      const currentGroups = prevGroups[selectedChartId.id] || [];
      const group = currentGroups.find((g) => g.id === groupId);

      if (group && group.children.length < 7) {
        const newChild = { id: Date.now(), easing: "Linear" };
        return {
          ...prevGroups,
          [selectedChartId.id]: currentGroups.map((g) =>
            g.id === groupId ? { ...g, children: [...g.children, newChild] } : g
          ),
        };
      }
      return prevGroups;
    });
  };

  // Remove a child from a group
  const removeChild = (groupId: number, childId: number) => {
    setChartDataGroups((currentGroups) => {
      const currentChartData = currentGroups[selectedChartId.id] || [];

      return {
        ...currentGroups,
        [selectedChartId.id]: currentChartData.map((group) =>
          group.id === groupId
            ? {
                ...group,
                children: group.children.filter(
                  (child) => child.id !== childId
                ),
              }
            : group
        ),
      };
    });
  };

  return (
    <div className="dataSideBar">
      {selectedChartId?.title && (
        <div className="sideBarHeader">{selectedChartId?.title}</div>
      )}
      {/* Render groups dynamically */}
      {chartDataGroups[selectedChartId?.id]?.map((group) => (
        <div key={group.id} className="inputs-wrapper">
          {group.children.map((child, index) => (
            <div key={child.id} className="datas">
              <div className="datas__label">Input {index + 1}</div>
              <div className="datas__class">
                <MultiLevelDropDown data={DATA_STRUCTURE} />
                {/* Add Icon */}
                {group.children.length < 7 && (
                  <div
                    className="icon"
                    onClick={() => handleAddClick(group.id)} // Pass groupId to handleAddClick
                  >
                    <AddIcon />
                  </div>
                )}
                {/* Remove Icon */}

                <span
                  className={`datas__separator ${
                    group.children.length > 1 ? "" : "disable"
                  }`}
                  onClick={(e) => {
                    e.stopPropagation(); // Prevent event bubbling
                    removeChild(group.id, child.id); // Pass groupId and childId to removeChild
                  }}
                >
                  <RemoveIcon />
                </span>
              </div>
            </div>
          ))}
        </div>
      ))}

      {/* Info Box */}
      <div className="infoBox">
        <span className="infoIcon">i</span>
        <p>
          <em>
            By adding templates and widgets, you create a customizable and
            dynamic environment.
          </em>
        </p>
      </div>
    </div>
  );
};

export default Data;
