import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import type { ApiListing } from "@/types/marketplace";

export type MyListingsStatusParam = "all" | 0 | 1 | 2 | 3;

export interface MyListingsStats {
  totalListings: number;
  draft: number;
  active: number;
  sold: number;
  paused: number;
  views: number;
}

interface MyListingsState {
  listings: ApiListing[];
  stats: MyListingsStats;
  isLoading: boolean;
  error: string | null;
}

const initialState: MyListingsState = {
  listings: [],
  stats: { totalListings: 0, draft: 0, active: 0, sold: 0, paused: 0, views: 0 },
  isLoading: false,
  error: null,
};

export const fetchMyListings = createAsyncThunk(
  "marketplaceMyListings/fetch",
  async (status: MyListingsStatusParam = "all", { rejectWithValue }) => {
    try {
      const channelId = Cookies.get("channel_id") ?? "";
      const res = await apiClient.post(API_ENDPOINTS.CLASSIFIED.GET_MY_LISTINGS, {
        channel_id: channelId,
        status,
      });
      return {
        listings: (res.data.result ?? []) as ApiListing[],
        stats: {
          totalListings: res.data.total_listings ?? 0,
          draft: res.data.total_draft_listing ?? 0,
          active: res.data.total_active_listing ?? 0,
          sold: res.data.total_sold_listing ?? 0,
          paused: res.data.total_paused_listing ?? 0,
          views: res.data.total_views ?? 0,
        } as MyListingsStats,
      };
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load listings");
    }
  }
);

const marketplaceMyListingsSlice = createSlice({
  name: "marketplaceMyListings",
  initialState,
  reducers: {
    clearMyListings: (state) => {
      state.listings = [];
      state.stats = initialState.stats;
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchMyListings.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchMyListings.fulfilled, (state, action) => {
        state.isLoading = false;
        state.listings = action.payload.listings;
        state.stats = action.payload.stats;
      })
      .addCase(fetchMyListings.rejected, (state, action) => {
        state.isLoading = false;
        state.listings = [];
        state.error = action.payload as string;
      });
  },
});

export const { clearMyListings } = marketplaceMyListingsSlice.actions;
export default marketplaceMyListingsSlice.reducer;
