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

interface MarketplaceListingDetailState {
  listing: ApiListingDetail | null;
  similar: ApiListing[];
  isLoading: boolean;
  error: string | null;
}

const initialState: MarketplaceListingDetailState = {
  listing: null,
  similar: [],
  isLoading: false,
  error: null,
};

export const fetchListingDetail = createAsyncThunk(
  "marketplaceListingDetail/fetch",
  async (listingId: number, { rejectWithValue }) => {
    try {
      const detailRes = await apiClient.post(
        API_ENDPOINTS.CLASSIFIED.GET_LISTING_DETAIL,
        { listing_id: listingId }
      );
      const detail = detailRes.data.result?.[0] as ApiListingDetail;
      if (!detail) return rejectWithValue("Listing not found");

      const similarRes = await apiClient.post(
        API_ENDPOINTS.CLASSIFIED.GET_LISTINGS,
        { category_id: detail.category_id, radius: -10 }
      );
      const similar = ((similarRes.data.result ?? []) as ApiListing[])
        .filter((l) => l.id !== detail.id)
        .slice(0, 6);

      return { listing: detail, similar };
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to load listing";
      return rejectWithValue(message);
    }
  }
);

const marketplaceListingDetailSlice = createSlice({
  name: "marketplaceListingDetail",
  initialState,
  reducers: {
    clearListingDetail: (state) => {
      state.listing = null;
      state.similar = [];
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchListingDetail.pending, (state) => {
        state.isLoading = true;
        state.error = null;
        state.listing = null;
        state.similar = [];
      })
      .addCase(fetchListingDetail.fulfilled, (state, action) => {
        state.isLoading = false;
        state.listing = action.payload.listing;
        state.similar = action.payload.similar;
      })
      .addCase(fetchListingDetail.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearListingDetail } = marketplaceListingDetailSlice.actions;
export default marketplaceListingDetailSlice.reducer;
