"use client";
import React from "react";
import {
  loginSelectEmployee,
  loginSelectOccupant,
} from "@/apicalls/login/login";
import { useRouter } from "next/navigation";
import LoginEmployee from "./LoginEmployee";
import LoginOccupant from "./LoginOccupant";
import { SelectListProps, Company, BuildingMap } from "./types";

function SelectList({
  selectionList,
  isEmployee,
  isOccupant,
  lang = "en",
}: SelectListProps) {
  const router = useRouter();

  // Log the complete selectionList object and its structure
  console.log("selectionList (complete):", selectionList);
  console.log(
    "selectionList (type):",
    Array.isArray(selectionList) ? "Array" : "Object"
  );

  if (isEmployee && Array.isArray(selectionList)) {
    console.log("Employee companies:", selectionList);
  } else if (isOccupant && !Array.isArray(selectionList)) {
    // Log each building and its occupants
    Object.entries(selectionList).forEach(([buildingKey, building]) => {
      console.log(`Building ${buildingKey}:`, building);
      console.log(`Occupants for building ${buildingKey}:`, building.occupants);
    });
  }

  const setSelectionHandler = (uu_id: string) => {
    if (isEmployee) {
      console.log("Selected isEmployee uu_id:", uu_id);
      loginSelectEmployee({ company_uu_id: uu_id })
        .then((responseData: any) => {
          if (responseData?.status === 200 || responseData?.status === 202) {
            router.push("/dashboard");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    } else if (isOccupant) {
      console.log("Selected isOccupant uu_id:", uu_id);
      // For occupants, the uu_id is a composite of buildKey|partUuid
      loginSelectOccupant({
        build_living_space_uu_id: uu_id,
      })
        .then((responseData: any) => {
          if (responseData?.status === 200 || responseData?.status === 202) {
            router.push("/dashboard");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }
  };

  return (
    <>
      {isEmployee && Array.isArray(selectionList) && (
        <LoginEmployee 
          selectionList={selectionList as Company[]} 
          lang={lang as "en" | "tr"} 
          onSelect={setSelectionHandler} 
        />
      )}

      {isOccupant && !Array.isArray(selectionList) && (
        <LoginOccupant 
          selectionList={selectionList as BuildingMap} 
          lang={lang as "en" | "tr"} 
          onSelect={setSelectionHandler} 
        />
      )}
    </>  
  );
}

export default SelectList;
