// Import necessary modules and hooks from libraries
import { useState } from "react";
import { State } from "../../data/datasource/api/entities/state";
import axios, { AxiosError } from "axios";
import { TownDatasourceProd } from "../../data/datasource/api/town_datasource";
import { TownRepositoryProd } from "../../data/repository/town_repository";
import { showErrorAxios } from "../../core/utils/Messages";

// Initialize the town datasource and repository
const townDatasource = new TownDatasourceProd();
const townRepository = new TownRepositoryProd(townDatasource);

// Custom hook for fetching states list
export const useGetStatesList = () => {
  const [statesList, setStatesList] = useState<State[]>([]);

  // Function to fetch all states
  const getStates = async () => {
    try {
      const states = await townRepository.getStates();
      setStatesList(states);
    } catch (error: any) {
      if (axios.isAxiosError(error)) {
        error as AxiosError;
        showErrorAxios(error);
      }
    }
  };

  // Function to fetch a state by its ID
  const getStateById = async (idState: number): Promise<State | null> => {
    let stateReturned: State | null = null;
    try {
      const states = await townRepository.getStates();
      states.forEach((state) => {
        if (state.stateId === idState) {
          stateReturned = state;
          return;
        }
      });
    } catch (error: any) {
      if (axios.isAxiosError(error)) {
        error as AxiosError;
        showErrorAxios(error);
      }
    }
    return stateReturned;
  };

  return { getStates, statesList, getStateById };
};
