import React, { useState, useEffect } from "react";
import Search from "../../ui/inputs/Search";
import DropDownList from "../../ui/list/DropDownList";
import { useSceneContext } from "../../../modules/scene/sceneContext";
import { isPointInsidePolygon } from "../../../functions/isPointInsidePolygon";

interface AssetData {
  id: string;
  name: string;
  position?: [];
  rotation?: {};
}

interface ZoneData {
  id: string;
  name: string;
  assets: AssetData[];
}

const Outline: React.FC = () => {
  const [searchValue, setSearchValue] = useState<string>("");
  const [sceneAssetsDataList, setSceneAssetsDataList] = useState<
    ZoneData[] | AssetData[]
  >([]);
  // const [buildingsList, setBuildingsList] = useState<{ id: string; name: string }[]>([]);
  // const [isLayersOpen, setIsLayersOpen] = useState(true);
  // const [isBuildingsOpen, setIsBuildingsOpen] = useState(false);
  const [isZonesOpen, setIsZonesOpen] = useState(true);
  const { assetStore, zoneStore } = useSceneContext();
  const { assets } = assetStore();
  const { zones } = zoneStore();

  useEffect(() => {
    const assignedAssets = new Set<string>();

    const updatedZoneList: ZoneData[] =
      zones?.map((zone: any) => {
        const polygon2D = zone.points.map((p: any) => [
          p.position[0],
          p.position[2],
        ]);
        const assetsInZone = assets
          .filter((item: any) => {
            const [x, , z] = item.position;
            const inside = isPointInsidePolygon(
              [x, z],
              polygon2D as [number, number][]
            );
            if (inside) assignedAssets.add(item.modelUuid);
            return inside;
          })
          .map((item: any) => ({
            id: item.modelUuid,
            name: item.modelName,
            position: item.position,
            rotation: item.rotation,
          }));

        return {
          id: zone.zoneUuid,
          name: zone.zoneName,
          assets: assetsInZone,
        };
      }) ?? [];

    // Collect unassigned assets
    const unassignedAssets = assets
      .filter((item: any) => !assignedAssets.has(item.modelUuid))
      .map((item: any) => ({
        id: item.modelUuid,
        name: item.modelName,
        position: item.position,
        rotation: item.rotation,
      }));

    // Add as a separate "zone"
    if (unassignedAssets.length > 0) {
      updatedZoneList.push({
        id: "unassigned-zone",
        name: "Unassigned",
        assets: unassignedAssets,
      });
    }

    setSceneAssetsDataList(updatedZoneList);
  }, [zones, assets]);

  const handleSearchChange = (value: string) => {
    setSearchValue(value);
  };

  // const dropdownItems = [{ id: "1", name: "Ground Floor" }];

  return (
    <div className="outline-container">
      <Search onChange={handleSearchChange} />

      {searchValue ? (
        <div className="searched-content">
          <p>Results for "{searchValue}"</p>
        </div>
      ) : (
        <div className="outline-content-container">
          {/* <section className="outline-section">
            <DropDownList
              value="Layers"
              items={dropdownItems}
              isOpen={isLayersOpen}
              onToggle={() => setIsLayersOpen((prev) => !prev)}
              showKebabMenu={false}
              showFocusIcon={true}
              remove
            />
          </section> */}
          <section className="outline-section overflow">
            {/* <DropDownList
              value="Buildings"
              items={buildingsList}
              isOpen={isBuildingsOpen}
              onToggle={() => setIsBuildingsOpen((prev) => !prev)}
              showKebabMenu={false}
              showAddIcon={false}
            /> */}
            <DropDownList
              value="Zones"
              items={sceneAssetsDataList}
              isOpen={isZonesOpen}
              onToggle={() => setIsZonesOpen((prev) => !prev)}
              showKebabMenu={false}
              showAddIcon={false}
            />
          </section>
        </div>
      )}
    </div>
  );
};

export default Outline;
