import { Dispatch, SetStateAction, useState } from "react";
import { useTown } from "../../../../domain/useCase/useTown";
import { State } from "../../../../data/datasource/api/entities/state";
import axios, { AxiosError } from "axios";
import "./assets/css/styles.css";
import { Town } from "../../../../data/datasource/api/entities/town";
import DataTable, { TableColumn } from "react-data-table-component";
import { LoadingSpinner } from "../../../components/loading_spinner/loading_spinner";
import { showErrorAxios } from "../../../../core/utils/Messages";
import { SuperadminPanelTownRegister } from "../sa_panel_town_register/sa_panel_town_register";

// Define the props interface for the component
interface props {
  windowActive: boolean;
  setWindowActive: Dispatch<SetStateAction<boolean>>;
  statesList: State[];
}

// Main component for displaying the list of towns
export const SuperadminPanelTownList = ({
  windowActive,
  setWindowActive,
  statesList,
}: props) => {
  // Custom hook to fetch towns data
  const { townsList, getTownsByState } = useTown();
  // State to manage loading spinner
  const [pending, setPending] = useState(false);
  // State to force re-render the DataTable
  const [renderCount, setRenderCount] = useState(0);
  // State to manage the visibility of the registration window
  const [actualWindowsActive, setActualWindowActive] = useState(false);

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

  // Define columns for the DataTable
  const columns: TableColumn<Town>[] = [
    {
      name: "Identificador",
      selector: (row) => row.idTown,
      sortable: true,
    },
    {
      name: "Nombre",
      selector: (row) => row.name,
      sortable: true,
    },
    {
      name: "Estado",
      selector: (row) => row.state,
      sortable: true,
    },
  ];

  // Function to refresh the list of towns based on selected state
  const refreshList = (stateId: number, name: string) => {
    setPending(true);
    const getTownsList = async () => {
      try {
        getTownsByState(stateId, name);
      } catch (error: any) {
        if (axios.isAxiosError(error)) {
          error as AxiosError;
          showErrorAxios(error);
        }
      }
    };
    getTownsList();
    setPending(false);
  };

  return (
    <div className="town_list_cnt">
      <div className="town_list_header">
        Estado
        <select
          disabled={windowActive}
          name="state_select"
          onChange={(event) => {
            const index = Number(event.target.value);
            const state = statesList[index];
            refreshList(state.stateId, state.name);
          }}
        >
          {statesList === null || statesList.length === 0 ? (
            <option disabled defaultValue="" value="">
              No hay estados
            </option>
          ) : (
            <>
              <option disabled selected value={0}>
                Selecciona el estado
              </option>
              {statesList.map((state, index) => {
                return (
                  <option key={state.stateId} value={index}>
                    {state.name}
                  </option>
                );
              })}
            </>
          )}
        </select>
      </div>
      <div className="town_list_body">
        {actualWindowsActive && (
          <SuperadminPanelTownRegister
            setWindowActive={setWindowActive}
            setActualWindowActive={setActualWindowActive}
            statesList={statesList}
            forceRenderList={forceRenderList}
            isRegister={false}
          />
        )}
        <DataTable
          key={renderCount}
          noDataComponent="No hay pueblos que mostrar"
          progressPending={pending}
          disabled={windowActive}
          progressComponent={<LoadingSpinner style={{ display: "flex" }} />}
          columns={columns}
          data={townsList}
          selectableRows
          className="data_table"
        />
      </div>
    </div>
  );
};
