"use client";
import { useState, useEffect } from "react";
import LoginOccupant from "./LoginOccupant";
import LoginEmployee from "./LoginEmployee";

import { Company, SelectListProps, BuildingMap } from "./types";
import { selectEmployeeTranslation, selectOccupantTranslation } from "./language";

const Select: React.FC<SelectListProps> = ({ selectionList, isEmployee, isOccupant, language, query }) => {
  const isEmployeee = query?.isEmployee == "true";
  const isOccupante = query?.isOccupant == "true";
  const userType = isEmployeee || isOccupante ? isEmployeee ? "employee" : "occupant" : "employee";

  const isEmployeeTrue = userType == "employee" && Array.isArray(selectionList)
  const isOccupantTrue = userType == "occupant" && !Array.isArray(selectionList)
  const initTranslation = userType == "employee" ? selectEmployeeTranslation[language] : selectOccupantTranslation[language]

  const [translation, setTranslation] = useState(initTranslation);
  const [listEmployeeSelection, setListEmployeeSelection] = useState<Company[]>(selectionList as Company[]);
  const [listOccupantSelection, setListOccupantSelection] = useState<BuildingMap>(selectionList as BuildingMap);

  useEffect(() => {
    if (isEmployee) { setListEmployeeSelection(selectionList as Company[]) }
    else if (isOccupant) { setListOccupantSelection(selectionList as BuildingMap) }
  }, []);

  useEffect(() => {
    setTranslation(isEmployee ? selectEmployeeTranslation[language] : selectOccupantTranslation[language]);
  }, [language]);

  return (
    <>
      <div className="flex h-full min-h-[inherit] flex-col items-center justify-center gap-4">
        <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
          {isEmployeeTrue && <LoginEmployee translation={translation} selectionList={listEmployeeSelection} lang={language} />}
          {isOccupantTrue && <LoginOccupant translation={translation} selectionList={listOccupantSelection} lang={language} />}
        </div>
      </div>
    </>
  );
}

export default Select;
