import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import { IList } from "@/shared/types/list-type";
import { IStatistics } from "@/shared/types/statistics-type";
import { AxiosError } from "axios";
import { create } from "zustand";

const filterCategories: Record<string, string> = {
  broken_road_1: "broken_road_1",
  hotbed_of_accidents_2: "hotbed_of_accidents_2",
  local_defect_3: "local_defect_3",
  repair_plans_4: "repair_plans_4",
  repaired_5: "repaired_5",
  local_defect_fixed_6: "local_defect_fixed_6",
};

interface IStatisticsStore extends IFetch {
  data: IStatistics[];
  getStatistics: (
    endpoint: string,
    filter: { option: string; toggle: boolean },
    query: string
  ) => void;
}

export const useStatisticsStore = create<IStatisticsStore>((set) => ({
  isLoading: false,
  error: "",
  data: [],
  getStatistics: async (
    endpoint: string,
    filter: { option: string; toggle: boolean },
    query: string = ""
  ) => {
    try {
      set({ isLoading: true });
      const response = await apiInstance.get<IStatistics[]>(
        `/report/${endpoint}/stats`
      );

      let data = response.data.filter((loc) =>
        loc.name.toLowerCase().includes(query.toLowerCase())
      );

      if (
        filter.option === filterCategories[filter.option] &&
        filter.toggle === false
      ) {
        data = data.sort((a, b) => {
          const optionKey = filter.option as keyof IStatistics;
          return (Number(a[optionKey]) -
            Number(b[optionKey])) as number;
        });
      } else if (
        filter.option === "rating" &&
        filter.toggle === true
      ) {
        data = data.sort((a, b) => {
          const optionKey = filter.option as keyof IStatistics;
          return (Number(a[optionKey]) -
            Number(b[optionKey])) as number;
        });
      }

      set({ data: data });
    } catch (error: unknown) {
      if (error instanceof AxiosError) {
        set({ error: error.message });
      } else {
        set({ error: "an error ocured" });
      }
    } finally {
      set({ isLoading: false });
    }
  },
}));
