import { Dispatch, SetStateAction, useState } from "react";
import { SuperadminPanelTownRegister } from "../sa_panel_town_register/sa_panel_town_register";
import "./css/styles.css";
import { State } from "../../../../data/datasource/api/entities/state";
import { SuperadminPanelTownList } from "../sa_panel_town_list/sa_panel_town_list";

// Interface for component props
interface props {
  windowActive: boolean; // Indicates if a window is active
  setWindowActive: Dispatch<SetStateAction<boolean>>; // Function to set windowActive state
  statesList: State[]; // List of states
}

// Main component for the Superadmin Panel Town Screen
export const SuperadminPanelTownScreen = ({
  windowActive,
  setWindowActive,
  statesList,
}: props) => {
  // State to control the visibility of the register panel
  const [showRegisterPanel, setShowRegisterPanel] = useState(false);
  // State to force re-render of the town list
  const [renderCount, setRenderCount] = useState(0);

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

  return (
    <div className="sa_panel_town_content">
      <div className="town_panel_header">
        Administrar pueblos mágicos
        <button
          className="town_add_btn"
          onClick={() => {
            setShowRegisterPanel(true);
            setWindowActive(true);
          }}
          disabled={windowActive}
        >
          Registrar Pueblo
        </button>
      </div>
      <div className="sa_panel_town_body">
        {/* Render the town list component */}
        <SuperadminPanelTownList
          windowActive={windowActive}
          setWindowActive={setWindowActive}
          statesList={statesList}
          key={renderCount} // Key to force re-render
        />

        {/* Conditionally render the register panel */}
        {showRegisterPanel && (
          <SuperadminPanelTownRegister
            setWindowActive={setWindowActive}
            setActualWindowActive={setShowRegisterPanel}
            statesList={statesList}
            forceRenderList={forceRenderList}
            isRegister={true}
          />
        )}
      </div>
    </div>
  );
};
