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";

interface Asset {
  id: string;
  name: string;
}

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

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

const List: React.FC<ListProps> = ({ items = [], remove }) => {
  console.log("items: ", items);
  const { activeModule, setActiveModule } = useModuleStore();
  const { selectedZone, setSelectedZone } = useSelectedZoneStore();
  const { setSubModule } = useSubModuleStore();
  const [expandedZones, setExpandedZones] = useState<Record<string, boolean>>(
    {}
  );

  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) {
        console.log("Zone is already selected:", selectedZone.zoneName);
        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 || [],
      });

      console.log("Zone selected:", response?.zoneName);
    } catch (error) {
      console.error("Error selecting zone:", error);
    }
  }

  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} />
                    </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">
                            <RenameInput value={asset.name} />
                          </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;
