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

// Define the props interface for the component
interface props {
  isWindowActive: boolean;
  statesList: State[];
}

// Define the main component
export const SuperAdminPanelAdminList = ({
  isWindowActive,
  statesList,
}: props) => {
  // State to manage loading status
  const [isLoading, setIsLoading] = useState(false);

  // Custom hooks to fetch towns and admins
  const { townsList, getTownsByState } = useTown();
  const { adminList, getAdminListByTown } = useAdmin();

  // Define columns for the DataTable
  const columns: TableColumn<Admin>[] = [
    {
      name: "Email",
      selector: (row) => row.email,
      sortable: true,
    },
    {
      name: "Nombre",
      selector: (row) => row.name.substring(0, 40),
      sortable: true,
    },
    {
      name: "Apellido",
      selector: (row) => row.lastName.substring(0, 40),
      sortable: true,
    },
    {
      name: "Estatus",
      selector: (row) => row.status?.substring(0, 40) ?? "",
      sortable: true,
    },
  ];

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

  // Function to refresh the list of admins based on selected town
  const refreshListAdmins = (idTown: number) => {
    setIsLoading(true);
    const getAdminsList = async () => {
      try {
        getAdminListByTown(idTown);
      } catch (error: any) {
        if (axios.isAxiosError(error)) {
          error as AxiosError;
          showErrorAxios(error);
        }
      }
    };
    getAdminsList();
    setIsLoading(false);
  };

  // Show loading spinner if data is being fetched
  if (isLoading) return <LoadingSpinner />;

  return (
    <div className="admin_list_cnt">
      <div className="admin_list_header">
        {/* Dropdown to select state */}
        Estado
        <select
          disabled={isWindowActive}
          name="state_select"
          onChange={(event) => {
            const index = Number(event.target.value);
            const state = statesList[index];
            refreshListTown(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>
        {/* Dropdown to select town */}
        Pueblo mágico
        <select
          disabled={isWindowActive}
          name="town_select"
          onChange={(event) => {
            const index = Number(event.target.value);
            const town = townsList[index];
            refreshListAdmins(town.idTown);
          }}
        >
          {townsList === null || townsList.length === 0 ? (
            <option disabled defaultValue="" value="">
              No hay pueblos
            </option>
          ) : (
            <>
              <option disabled selected value={0}>
                Selecciona el pueblo
              </option>
              {townsList.map((town, index) => {
                return (
                  <option key={town.idTown} value={index}>
                    {town.name}
                  </option>
                );
              })}
            </>
          )}
        </select>
      </div>
      <div className="admin_list_body">
        {/* DataTable to display list of admins */}
        <DataTable
          noDataComponent="No hay administradores que mostrar"
          progressPending={isLoading}
          disabled={isWindowActive}
          progressComponent={<LoadingSpinner style={{ display: "flex" }} />}
          columns={columns}
          data={adminList}
          selectableRows
          className="data_table"
        />
      </div>
    </div>
  );
};
