// src/store/crud.ts
import axiosInstance from '@/services/axiosClient';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import toast from 'react-hot-toast';

interface AddItemProps {
  id: number | string;
}

interface toggleItem extends AddItemProps  {
method :"add" | "delete"
type?  :string;
delFav?:string
}

interface CrudState {
  mainLoader: boolean;
  allFavItems: any[];
  itemId: number | string;
  count: number;
  categories: any[];
}

const initialState: CrudState = {
  mainLoader: false,
  allFavItems: [],
  itemId: "",
  categories:[],
  count:0
};

// Fetch all favorites
export const getAllFavItems = createAsyncThunk(
  'fav/getAllFavItems',
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstance.get(`/favorites`);
      return data?.data || {};
    } catch (error: any) {
      // toast.error(error?.response?.data?.message);
      return rejectWithValue(error.message);
    }
  }
);

// Add to favorites
export const toggleItemToFav = createAsyncThunk(
  'fav/toggleItemToFav',
  async ({ id,method,type,delFav }: toggleItem, { rejectWithValue, dispatch }) => {
    try {
      const axiosMethod = method == "delete" ? axiosInstance.patch(`/favorites/${id}`,{
        favoritable_type:type || "product"
      }) : axiosInstance.post(`/favorites`,{
        favoritable_id:id,
        favoritable_type:type || "product"
    });
      const { data } = await axiosMethod;
      if (data?.status === 'success') {
        toast.success(data?.message)
        dispatch(getAllFavItems());
        return { id, isFav: method == "add" ? true : false,is_favorite:data?.id };
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
      return rejectWithValue(error.message);
    }
  }
);

// Remove all items from favorites
export const removeAllFromFav = createAsyncThunk(
  'fav/removeAllFromFav',
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstance.delete(`/favorites`);
      if (data?.status === 'success') {
        toast.success(data?.message);
        return true;
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message);
      return rejectWithValue(error.message);
    }
  }
);

// Slice
const favSlice = createSlice({
  name: 'fav',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // Get all favorites
      .addCase(getAllFavItems.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(getAllFavItems.fulfilled, (state, action) => {
        state.mainLoader = false;
        state.allFavItems = [...action.payload?.products,...action.payload?.traders];
        state.count = action.payload?.count;
        state.categories = action.payload?.categories;
      })
      .addCase(getAllFavItems.rejected, (state) => {
        state.mainLoader = false;
      })
      // Add item
      .addCase(toggleItemToFav.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(toggleItemToFav.fulfilled, (state, action: PayloadAction<any>) => {
        state.mainLoader = false;
        // const { id, isFav,is_favorite } = action.payload;
      
        // if (isFav) {
        //   const exists = state.allFavItems.some(item => item.id == id);
        //   if (!exists) {
        //     state.allFavItems.push({ id,is_favorite });
        //     state.count += 1;
        //   }
        // } else {
        //   state.allFavItems = state.allFavItems.filter(item => item.id != id);
        //   state.count = Math.max(0, state.count - 1);
        // }
      })
      .addCase(toggleItemToFav.rejected, (state) => {
        state.mainLoader = false;
      })
      // Remove all
      .addCase(removeAllFromFav.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(removeAllFromFav.fulfilled, (state) => {
        state.mainLoader = false;
        state.allFavItems = [];
        state.categories= [];
        state.count = 0;
      })
      .addCase(removeAllFromFav.rejected, (state) => {
        state.mainLoader = false;
      });
  },
});

export default favSlice.reducer;
