import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { AdminPanelPlaceRegister } from "../admin_panel_place_register/admin_panel_place_register";
import "./assets/css/styles.css";
import { AdminPanelPlaceList } from "../admin_panel_place_list/admin_panel_place_list";
import { Town } from "../../../../data/datasource/api/entities/town";
import { useCategory } from "../../../../domain/useCase/useCategory";
import { Place } from "../../../../data/datasource/api/entities/place";

// Interface for component props
interface props {
  isWindowActive: boolean;
  setIsWindowActive: Dispatch<SetStateAction<boolean>>;
  town: Town | undefined;
}

// Main component for the admin panel place screen
export const AdminPanelPlaceScreen = ({
  isWindowActive,
  setIsWindowActive,
  town,
}: props) => {
  // State variables
  const [renderCount, setRenderCount] = useState(0);
  const [isRegisterPane, setIsRegisterPane] = useState(true);
  const [actualPlace, setActualPlace] = useState<Place | undefined>();
  const [isPlaceRegisterWindowActive, setIsPlaceRegisterWindowActive] =
    useState(false);
  const { categoriesList, updateCategoriesList } = useCategory();

  // Function to force re-render the list
  const forceRenderList = () => {
    setRenderCount((prevCount) => prevCount + 1);
    setIsWindowActive(false);
  };

  // Function to set window visibility
  const setWindowVisibility = (visibility: boolean) => {
    setIsPlaceRegisterWindowActive(visibility);
    setIsWindowActive(visibility);
  };

  // Effect to update categories list on component mount
  useEffect(() => {
    updateCategoriesList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="admin_panel_place_content">
      <div className="panel_place_header">
        Administrar lugares dentro de Pueblo Mágico
        <button
          className="place_add_btn"
          disabled={isWindowActive || !town}
          onClick={() => {
            setIsRegisterPane(true);
            setWindowVisibility(true);
          }}
        >
          Registrar lugar
        </button>
      </div>
      <div className="panel_place_body">
        {isPlaceRegisterWindowActive && (
          <AdminPanelPlaceRegister
            setWindowVisibility={setWindowVisibility}
            idTown={town?.idTown || -1}
            categoriesList={categoriesList}
            forceRenderList={forceRenderList}
            isRegister={isRegisterPane}
            form={actualPlace}
          />
        )}
        <AdminPanelPlaceList
          idTown={town?.idTown || -1}
          key={renderCount}
          isWindowActive={isWindowActive}
          setWindowVisibility={setWindowVisibility}
          setActualPlace={setActualPlace}
          setIsRegisterPane={setIsRegisterPane}
        />
      </div>
    </div>
  );
};
