import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import {
  IMyReports,
  IMyReportsList,
} from "@/shared/types/my-reports";
import { AxiosError } from "axios";
import { create } from "zustand";

const filterCategories: Record<string, string> = {
  count_reviews: "count_reviews",
  total_likes: "total_likes",
};

interface IProfileReportsStore extends IFetch {
  data: IMyReportsList;
  getMyReports: (
    filter: { option: string; toggle: boolean },
    page: number,
    access_token: string
  ) => void;
}

export const useProfileReportsStore = create<IProfileReportsStore>(
  (set) => ({
    isLoading: false,
    error: "",
    data: {
      count: 0,
      previous: null,
      next: null,
      results: [],
    },
    getMyReports: async (
      filter: {
        option: string;
        toggle: boolean;
      },
      page: number,
      access_token: string
    ) => {
      try {
        const Authorization = `Bearer ${access_token}`;
        const config = {
          headers: {
            Authorization,
          },
        };
        set({ isLoading: true });
        const res = await apiInstance.get<IMyReportsList>(
          `/users/reports/?page=${page}`,
          config
        );

        let data = res.data;

        if (filter.option === "date" && filter.toggle === false) {
          data.results = data.results.sort((a, b) => {
            const dateA = new Date(a.created_at) as unknown as number;
            const dateB = new Date(b.created_at) as unknown as number;
            return dateA - dateB;
          });
        } else if (
          filter.option === "date" &&
          filter.toggle === true
        ) {
          data.results = data.results.sort((a, b) => {
            const dateA = new Date(a.created_at) as unknown as number;
            const dateB = new Date(b.created_at) as unknown as number;
            return dateB - dateA;
          });
        }

        if (
          filter.option === filterCategories[filter.option] &&
          filter.toggle === false
        ) {
          data.results = data.results.sort((a, b) => {
            const optionKey = filter.option as keyof IMyReports;
            return (Number(a[optionKey]) -
              Number(b[optionKey])) as number;
          });
        } else if (
          filter.option === "rating" &&
          filter.toggle === true
        ) {
          data.results = data.results.sort((a, b) => {
            const optionKey = filter.option as keyof IMyReports;
            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 });
      }
    },
  })
);
