import axios, { AxiosRequestConfig } from "axios";
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
  CATEGORY_URL,
  FORGOT_PASSWORD_URL,
  LOGOUT_URL,
  RESET_PASSWORD_URL,
  SELLER_GET_LISTING_URL,
  SELLER_LOGIN_URL,
  SELLER_REGISTER_URL,
  TOKEN_STORAGE_KEY,
  UPDATE_PROFILE_URL,
  BUYER_REGISTER_URL,
  BUYER_LOGIN_URL,
  BUYER_UPDATE_PROFILE_URL,
  BUYER_GET_PROFILE_URL,
  SELLER_GET_PROFILE_URL,
  BUYER_GET_AUCTION_LISTING_URL,
  BUYER_GET_AUCTION_SEARCH_LISTING_URL,
  BUYER_GET_AUCTION_VIEW_LISTING_URL,
  BUYER_ADD_REVIEW_URL,
  BUYER_BUYER_VIEW_SELLER,
  BUYER_SELLER_STORE_LISTING,
  ADD_WALLET,
  SELLER_PAYMENT_FAILED_LISTING,
  SELLER_DELETE_LISTING,
  SELLER_UPDATE_LISTING,
  BUYER_ADD_BID,
  BUYER_GET_ORDER_URL,
  BUYER_ADD_ADDRESS,
  BUYER__DELETE_ADDRESS,
  BUYER__UPDATE_ADDRESS,
  BUYER__ALL_ADDRESS,
  BUYER_WISHLIST,
  BUYER_HOME_CONTENT,
  BUYER__TRACK_ORDER,
  SELLER_ALL_ORDERS,
  BUYER_WISHLIST_REMOVE,
  BUYER_WISHLIST_ALL,
  BUYER_SEND_MSG,
  BUYER_MESSAGE,
  BUYER_CONVERSATION,
  SELLER_EDIT_DETAIL,
  ADDRESS_UPDATE,
  CASH_WALLET,
  CASH_WALLET_HISTORY,
  GET_GUEST_AUCTION_LISTING_URL,
  LISTING_VIEW_PRICE,
  FILTER,
  ADD_TICKET,
  GET_TICKET,
  REPLIES_TICKET,
  TICKET_ID_REPLIES,
  Recommend_listing,
  Order_Status,
  BUYER_PLACE_ORDER,
  ABOUT_US,
  TERMS_UPDATE,
  CATEGORY_IMAGES,
  STATES,
  ALL_DRAFTS,
  CHANGE_PASSWORD,
  POST_DRAFT,
  NOTIFICATION_SETTING,
  DELETE_IMAGE,
  PRIORITY_BIDS,
  SUBSCRIBE,
  PRIORITY_BIDS_DATA,
  PRIORITY_BIDS_DATA_UPDATE,
  TERMS_POLICIES,
  ONGOING_BIDS_DATA,
  GETS_COUNT,
  GETS_INCREMENT,
  GETS_BIDS_DATA,
  GET_REVIEW_HISTORY,
  ONGOINGBIDS,
  TRACKLISTINGS,
  REPOST_LISTING,
  CANCEL_ORDER_LISTING,
  PRIORITY_BIDS_UNLOCK,
  TICKET_NOTIFICATION,
  NOTFICATION_ALL_READ,
  RATING_INFO,
  READ_NOTIFICATION,
} from "../constants";
// import { tr } from 'date-fns/locale';

export default function getJWT(): string | null {
  if (typeof window !== "undefined") {
    return localStorage.getItem(TOKEN_STORAGE_KEY);
  }
  return null;
}

// Updated axiosRequest function with abort signal support
export async function axiosRequest(
  url: string,
  method: string,
  data?: any,
  jwtRequire: boolean = false,
  config: AxiosRequestConfig = {} // Added config parameter for abort signal
) {
  const requestHeaders: Record<string, string> = {};

  if (jwtRequire) {
    const token = getJWT();
    if (token) {
      requestHeaders["Authorization"] = `Bearer ${token}`;
    }
  }

  if (!(data instanceof FormData)) {
    requestHeaders["Content-Type"] = "application/json";
  }

  const fullConfig: AxiosRequestConfig = {
    url,
    method,
    headers: requestHeaders,
    data,
    ...config, // Merge with provided config (includes signal if provided)
  };

  try {
    const response = await axios(fullConfig);
    if (response?.data?.message == "Bearer token is missing") {
      if (window.location.pathname !== "/auth/login") {
        localStorage.removeItem("token");
        window.location.href = "/auth/login";
      }
      return;
    }
    return handleApiResponse(response.data);
  } catch (error: any) {
    if (error?.response?.data?.message == "Unauthenticated.") {
      if (window.location.pathname !== "/auth/login") {
        localStorage.removeItem("token");
        window.location.href = "/auth/login";
      }
      return;
    }
    throw error;
  }
}

function handleApiResponse(responseData: any) {
  if (
    responseData &&
    responseData.hasOwnProperty("success") &&
    responseData.hasOwnProperty("error") &&
    responseData.hasOwnProperty("status_code") &&
    (responseData.hasOwnProperty("data") ||
      responseData.hasOwnProperty("message"))
  ) {
    if (responseData.message === "Unauthenticated") {
      // Clear token if needed
      localStorage.removeItem("token"); // or sessionStorage
      // Redirect to login
      window.location.href = "auth/login";
      return; // prevent further execution
    }
    if (responseData.success) {
      return responseData;
    } else {
      throw new Error(responseData.error || "Unknown error occurred");
    }
  } else {
    throw new Error("Invalid response format");
  }
}

//api functions

export const categoryApiCall = createAsyncThunk("category", async () => {
  try {
    const categoryData = await axiosRequest(CATEGORY_URL, "GET");
    return categoryData;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const sellerGetList = createAsyncThunk("seller/listing", async () => {
  try {
    const listData = await axiosRequest(
      SELLER_GET_LISTING_URL,
      "GET",
      "",
      true
    );
    return listData;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const sellerRegister = createAsyncThunk(
  "auth/seller_register",
  async (payload: any) => {
    try {
      const response = await axiosRequest(SELLER_REGISTER_URL, "POST", payload);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const sellerLogin = createAsyncThunk(
  "auth/seller_login",
  async (payload: any) => {
    try {
      const response = await axiosRequest(SELLER_LOGIN_URL, "POST", payload);
      // console.log("response=", response);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        // console.log("e", error);
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const buyerLogin = createAsyncThunk(
  "BuyerAuth/buyer_login",
  async (payload: any) => {
    try {
      const response = await axiosRequest(BUYER_LOGIN_URL, "POST", payload);
      // console.log("response=", response);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        // console.log("e", error);
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const buyerRegister = createAsyncThunk(
  "BuyerAuth/buyer_register",
  async (payload: any) => {
    try {
      const response = await axiosRequest(BUYER_REGISTER_URL, "POST", payload);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const logout = createAsyncThunk("logout", async () => {
  try {
    const response = await axiosRequest(
      LOGOUT_URL,
      "POST",
      new FormData(),
      true
    );

    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const forgotPassword = createAsyncThunk(
  "auth/forgot_password",
  async (email: string, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(FORGOT_PASSWORD_URL, "POST", {
        email,
      });
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data); // Use rejectWithValue to return error payload
      } else {
        return rejectWithValue(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const resetPassword = createAsyncThunk(
  "auth/reset_password",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(RESET_PASSWORD_URL, "POST", payload);
      const data = response.data;
      return data; // full response from API
    } catch (error: any) {
      const message =
        error?.response?.data?.error ||
        error?.message ||
        "An unknown error occurred";
      return rejectWithValue(message);
    }
  }
);

export const updateProfileBuyer = createAsyncThunk(
  "BuyerAuth/update_profile",
  async (payload: FormData, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER_UPDATE_PROFILE_URL,
        "POST",
        payload,
        true
      );
      return response;
    } catch (error: any) {
      // console.error(
      //   "Profile Update Error:",
      //   error?.response?.data || error.message
      // );
      return rejectWithValue(error?.response?.data || "Profile update failed.");
    }
  }
);

export const updateProfile = createAsyncThunk(
  "auth/update_profile",
  async (payload: any) => {
    try {
      const response = await axiosRequest(
        UPDATE_PROFILE_URL,
        "POST",
        payload,
        true
      );
      // console.log("Response:", payload, response);
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    //  catch (error) {
    //   console.log(error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const SallerBuyer = createAsyncThunk("auth/seller_profile_buyer", async () => {
  try {
    const profileData = await axiosRequest(
      SELLER_GET_PROFILE_URL,
      "Get",
      "",
      true
    );
    return profileData;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const profileBuyer = createAsyncThunk(
  "BuyerAuth/get_buyer",
  async () => {
    try {
      const profileData = await axiosRequest(
        BUYER_GET_PROFILE_URL,
        "Get",
        "",
        true
      );
      return profileData;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const auctionListing = createAsyncThunk(
  "buyerAuth/getAuctionListing",
  async ({
    page,
    CurrentUserID,
    latitude,
    longitude,
    currency,
    order_type,
    subLocation,
  }: {
    page: number;
    CurrentUserID?: any;
    latitude?: string;
    longitude?: string;
    currency?: any;
    order_type?: any;
    subLocation?: any;
  }) => {
    try {
      const url = `${BUYER_GET_AUCTION_LISTING_URL}?page=${page}&user_id=${CurrentUserID || ""
        }&latitude=${latitude ?? ""}&longitude=${longitude ?? ""}&currency=${currency ?? ""
        }&order_type=${order_type}&subLocation=${subLocation}`;
      const AuctionList = await axiosRequest(url, "Get", "", true);
      return AuctionList;
    } catch (error: any) {
      // console.error("❌ API Error:", error);
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const guestListing = createAsyncThunk(
  "buyerAuth/getAuctionListing",
  async (page: number) => {
    try {
      const AuctionList = await axiosRequest(
        `${GET_GUEST_AUCTION_LISTING_URL}?page=${page}`, // Make sure this URL is correct for your guest listing
        "Get",
        "",
        true
      );

      return AuctionList;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

// export const searchListing = createAsyncThunk(
//   "buyerAuth/getSearchListing",
//   async (
//     payload: {
//       keyword?: string;
//       category_id?: any;
//       ad_type?: string;
//       fuel_type?: any;
//       location_longitude?: string;
//       location_latitude?: string;
//       starting_price?: number;
//       ending_price?: number;
//       user_id?: number;
//       page?: number;
//       limit?: number;
//       location?: any;
//       sub_location?: any;
//     },
//     { rejectWithValue }
//   ) => {
//     try {
//       const requestPayload = {
//         keyword: payload.keyword || "",
//         category_id: payload.category_id || null,
//         ad_type: payload.ad_type || "",
//         location_longitude: Number(payload.location_longitude) || null,
//         location_latitude: Number(payload.location_latitude) || null,
//         starting_price: payload.starting_price || null,
//         ending_price: payload.ending_price || null,
//         fuel_type: payload.fuel_type || null,
//         user_id: Number(payload.user_id) || null,
//         page: payload.page || 1,
//         limit: payload.limit || 10,
//         location: payload.location || "",
//         sub_location: payload.sub_location || "",
//       };
//       console.log("requestPayload", requestPayload);
//       // 🛠️ Construct URL safely without extra characters
//       const url = `${BUYER_GET_AUCTION_SEARCH_LISTING_URL}?page=${
//         requestPayload.page
//       }&user_id=${requestPayload.user_id ?? ""}&location_latitude=${
//         requestPayload.location_latitude ?? ""
//       }&location_longitude=${
//         requestPayload.location_longitude ?? ""
//       }&location=${requestPayload.location}&sub_location=${
//         requestPayload.sub_location
//       }`;
//       const response = await axiosRequest(url, "POST", requestPayload, true);
//       console.log("response", response?.data?.listings?.length, response);
//       return response;
//     } catch (error: any) {
//       // console.error("❌ API Error:", error);
//       return rejectWithValue(
//         error.response?.data?.error ||
//           "An error occurred while processing your request. Please try again later."
//       );
//     }
//   }
// );

// Updated searchListing thunk with abort support
export const searchListing = createAsyncThunk(
  "buyerAuth/getSearchListing",
  async (
    payload: {
      keyword?: string;
      category_id?: any;
      ad_type?: string;
      fuel_type?: any;
      location_longitude?: string;
      location_latitude?: string;
      starting_price?: number;
      ending_price?: number;
      user_id?: number;
      page?: number;
      limit?: number;
      location?: any;
      sub_location?: any;
      signal?: AbortSignal; // New optional signal property
    },
    { rejectWithValue }
  ) => {
    try {
      const requestPayload = {
        keyword: payload.keyword || "",
        category_id: payload.category_id || null,
        ad_type: payload.ad_type || "",
        location_longitude: Number(payload.location_longitude) || null,
        location_latitude: Number(payload.location_latitude) || null,
        starting_price: payload.starting_price || null,
        ending_price: payload.ending_price || null,
        fuel_type: payload.fuel_type || null,
        user_id: Number(payload.user_id) || null,
        page: payload.page || 1,
        limit: payload.limit || 10,
        location: payload.location || "",
        sub_location: payload.sub_location || "",
      };
      const url = `${BUYER_GET_AUCTION_SEARCH_LISTING_URL}?page=${requestPayload.page
        }&user_id=${requestPayload.user_id ?? ""}&location_latitude=${requestPayload.location_latitude ?? ""
        }&location_longitude=${requestPayload.location_longitude ?? ""
        }&location=${requestPayload.location}&sub_location=${requestPayload.sub_location
        }`;

      const response = await axiosRequest(
        url,
        "POST",
        requestPayload,
        true,
        { signal: payload.signal } // Pass the signal to axios
      );
      return response;
    } catch (error: any) {
      // if (error.name === "CanceledError" || error.name === "AbortError") {
      //   return rejectWithValue("Request was canceled");
      // }
      return rejectWithValue(
        error.response?.data?.error ||
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
);

export const viewListing = createAsyncThunk(
  "buyerAuth/view_listing/data",
  async ({ id, user_id }: { id: any; user_id: any }, { rejectWithValue }) => {
    try {
      const url = `${BUYER_GET_AUCTION_VIEW_LISTING_URL}/${id}?user_id=${user_id || ""}`;
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data);
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const addReview = createAsyncThunk(
  "buyerAuth/add_review",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER_ADD_REVIEW_URL,
        "POST",
        payload,
        true
      );

      if (response.success) {
        return response;
      } else {
        // Reject with API error message
        return rejectWithValue(response.error || "Review submission failed.");
      }
    } catch (error: any) {
      // If Axios throws an error
      const errorMessage =
        error.response?.data?.error ||
        error.message ||
        "An unexpected error occurred.";
      return rejectWithValue(errorMessage);
    }
  }
);
export const viewSaller = createAsyncThunk(
  "BuyerAuth/add_seller",
  async (payload: { seller_id: string; user_id: string }) => {
    try {
      const requestPayload = {
        seller_id: payload.seller_id,
        user_id: payload.user_id,
      };
      const response = await axiosRequest(
        BUYER_BUYER_VIEW_SELLER,
        "POST",
        requestPayload,
        true
      );
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    // catch (error) {
    //   console.error("Error:", error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const storeListing = createAsyncThunk(
  "auth/get_store",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER_SELLER_STORE_LISTING,
        "POST",
        payload,
        true
      );

      if (response.success) {
        return response.data;
      } else {
        // console.error("API Error Response:", response.data?.error);
        return rejectWithValue(response.data.error || "An error occurred.");
      }
    } catch (error: any) {
      if (error.response) {
        const errorMessage = error.response.data?.error || "An error occurred.";
        return rejectWithValue(errorMessage); // Reject with error message
      } else {
        // console.error("Network Error:", error);
        return rejectWithValue(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const paymentListing = createAsyncThunk(
  "auth/payment_listing",
  async (payload: any) => {
    try {
      const response = await axiosRequest(ADD_WALLET, "POST", payload, true);
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    // catch (error) {
    //   console.error("Error:", error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const cashOutWallet = createAsyncThunk(
  "auth/cashOutWallet",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(CASH_WALLET, "POST", payload, true);
      if (!response.success) {
        // Explicitly reject if success is false
        return rejectWithValue(response.error || "Unexpected error occurred.");
      }
      return response;
    } catch (error: any) {
      // console.error("API error:", error);

      // Extract the API error message or fallback message
      const errorMessage =
        error.response?.data?.error || // Specific API error
        error.message || // General Axios error
        "An error occurred. Please try again.";

      return rejectWithValue(errorMessage);
    }
  }
);

export const viewPrice = createAsyncThunk(
  "/viewPrice",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        LISTING_VIEW_PRICE,
        "POST",
        payload,
        true
      );
      if (!response.success) {
        // Reject with the error message from the response
        return rejectWithValue(response.error || "Unknown error occurred.");
      }
      return response; // Success case
    } catch (error: any) {
      // console.error("Error:", error);

      // Extract the error message from the response if available
      const errorMessage =
        error.response?.data?.error ||
        "An unexpected error occurred. Please try again later.";
      return rejectWithValue(errorMessage);
    }
  }
);

export const cashWalletHistory = createAsyncThunk(
  "auth/cashWalletHistory",
  async () => {
    try {
      const response = await axiosRequest(CASH_WALLET_HISTORY, "Get", "", true);
      return response.data;
    } catch {
      return null;
    }
  }
);
export const paymentFailed = createAsyncThunk(
  "auth/payment_listing",
  async (payload: any) => {
    try {
      const response = await axiosRequest(
        SELLER_PAYMENT_FAILED_LISTING,
        "POST",
        payload,
        true
      );
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    // catch (error) {
    //   console.error("Error:", error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const deleteListing = createAsyncThunk(
  "auth/delete_listing",
  async (payload: { id: number }, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        `${SELLER_DELETE_LISTING}/${payload.id}`,
        "DELETE",
        null,
        true
      );

      // console.log("Response from delete listing:", response);

      if (response?.status_code === 200 && response?.success) {
        return response; // ✅ Return the whole response
      } else {
        return rejectWithValue(response?.error || "Failed to delete listing");
      }
    } catch {
      // console.log(error);
      return rejectWithValue("An error occurred while deleting.");
    }
  }
);

export const updateSellerListing = createAsyncThunk(
  "auth/update_sellerListing",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        SELLER_UPDATE_LISTING,
        "POST",
        payload,
        true
      );
      return response;
    } catch (error: any) {
      // console.log("error:", error);
      if (error?.response && error?.response?.data) {
        return rejectWithValue({
          status: error?.response?.data?.status_code,
          message: error?.response?.data?.error || "Something went wrong",
        });
      }
    }
  }
);

export const createBid = createAsyncThunk(
  "auth/createBid",
  async (payload: { listing_id: any; amount: any }, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(BUYER_ADD_BID, "POST", payload, true);

      return response.data;
    } catch (error: any) {
      // console.error("Error occurred:", error);
      // console.error("Error Response Data:", error.response?.data);
      return rejectWithValue(
        error.response?.data?.error ||
        "An error occurred while processing your request 12."
      );
    }
  }
);

export const address = createAsyncThunk(
  "BuyerAuth/buyer_address",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER_ADD_ADDRESS,
        "POST",
        payload,
        true
      );
      return response;
    } catch (error: any) {
      // console.error("Error in address thunk:", error);
      return rejectWithValue(
        error?.response?.data?.error || "Failed to add address."
      );
    }
  }
);

export const addressUpdate = createAsyncThunk(
  "Buyer/updateAddress",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER__UPDATE_ADDRESS,
        "POST",
        payload,
        true
      );
      return response;
    } catch (error: any) {
      // console.error("Error in updateAddress:", error);
      return rejectWithValue(
        error?.response?.data?.error || "Failed to update address."
      );
    }
  }
);

export const deleteAddress = createAsyncThunk(
  "Buyer/deleteAddress",
  async (payload: { id: any }) => {
    try {
      const response = await axiosRequest(
        `${BUYER__DELETE_ADDRESS}/${payload.id}`,
        "DELETE",
        null,
        true
      );
      console.log("Response from delete address:", response);
      return { id: payload.id }; // Returning the ID of the deleted listing
    } catch (error: any) {
      // console.error("Error:", error);
      if (error.response && error.response.data) {
        throw new Error(
          error.response.data.error || "Failed to fetch address data"
        );
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const allAddress = createAsyncThunk("address/fetchAll", async () => {
  try {
    const addressData = await axiosRequest(BUYER__ALL_ADDRESS, "GET", "", true);
    return addressData;
  } catch (error: any) {
    if (error.response && error.response.data) {
      throw new Error(
        error.response.data.message || "Failed to fetch address data"
      );
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const allOrders = createAsyncThunk("BuyerAuth/order", async () => {
  try {
    const ordersData = await axiosRequest(BUYER_GET_ORDER_URL, "GET", "", true);
    return ordersData;
  } catch (error: any) {
    if (error.response && error.response.data) {
      throw new Error(
        error.response.data.message || "Failed to fetch address data"
      );
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const trackOrder = createAsyncThunk(
  "buyerAuth/getAuction_ViewListing",
  async (id: string) => {
    try {
      const url = `${BUYER__TRACK_ORDER}/${id}`;
      const response = await axiosRequest(url, "GET", "", true);
      // console.log("check auction view track order", response);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const sellerAllOrders = createAsyncThunk(
  "auth/seller_order",
  async (page: number, { rejectWithValue }) => {
    try {
      const url = `${SELLER_ALL_ORDERS}?page=${page}`;
      const ordersData = await axiosRequest(url, "GET", null, true);
      return ordersData;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(
          error.response.data.message || "Failed to fetch orders data."
        );
      }
      return rejectWithValue(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
);

export const Wishlist = createAsyncThunk(
  "BuyerAuth/wishlist",
  async (id: string) => {
    try {
      const response = await axiosRequest(
        `${BUYER_WISHLIST}/${id}/add`,
        "POST",
        "",
        true
      );
      return response;
    } catch {
      // console.error("Error:", error);
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
);

export const DeleteWishlist = createAsyncThunk(
  "Buyer/deleteWishlist",
  async (id: string) => {
    //  console.log(id)
    try {
      const response = await axiosRequest(
        `${BUYER_WISHLIST_REMOVE}/${id}/remove`,
        "DELETE",
        null,
        true
      );

      // console.log("Response from delete :", response);
      return response; // Returning the ID of the deleted listing
    } catch {
      // console.error("Error:", error);
      throw new Error(
        "An error occurred while trying to delete the listing. Please try again later."
      );
    }
  }
);

export const fetchAllWishlist = createAsyncThunk(
  "wishlist/fetchAll",
  async () => {
    try {
      const wishlistData = await axiosRequest(
        BUYER_WISHLIST_ALL,
        "GET",
        "",
        true
      );
      // wishlistData.data?.wishlists.length

      return wishlistData;
    } catch (error: any) {
      if (error.response && error.response.data) {
        throw new Error(
          error.response.data.message || "Failed to fetch wishlist data"
        );
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const homeContent = createAsyncThunk("Buyer/homeContent", async () => {
  try {
    const response = await axiosRequest(BUYER_HOME_CONTENT, "GET", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      throw new Error(
        error.response.data.message || "Failed to fetch content data"
      );
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const sendMessage = createAsyncThunk(
  "sendMessage",
  async (payload: any) => {
    try {
      const response = await axiosRequest(
        BUYER_SEND_MSG,
        "POST",
        payload,
        true
      );
      return response;
    } catch {
      // console.log(error);

      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
);

export const message = createAsyncThunk("buyer/messages", async () => {
  try {
    const response = await axiosRequest(BUYER_MESSAGE, "GET", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      throw new Error(
        error.response.data.message || "Failed to fetch message  data"
      );
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

interface ConversationPayload {
  id: string;
  listingID: string;
}

export const conversation = createAsyncThunk<any, ConversationPayload>(
  "buyer/conversation",
  async ({ id, listingID }) => {
    try {
      const response = await axiosRequest(
        `${BUYER_CONVERSATION}/${id}/${listingID}/messages`,
        "GET",
        "",
        true
      );
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        throw new Error(
          error.response.data.message || "Failed to fetch message data"
        );
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const addTickets = createAsyncThunk<
  { success: boolean; data: any; message?: string },
  { listing_id: string; category: string; subject: string; message: string },
  { rejectValue: string }
>("tickets/addTickets", async (payload, { rejectWithValue }) => {
  try {
    const response = await axiosRequest(ADD_TICKET, "POST", payload, true);
    return response; // Ensure response has the shape: { success, data, message }
  } catch (error: any) {
    return rejectWithValue(
      error.response?.data?.message ||
      "An error occurred while adding the ticket. Please try again later."
    );
  }
});

export const getTickets = createAsyncThunk(
  "tickets/getTickets",
  async (_, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(GET_TICKET, "GET", "", true);
      return response; // Assuming response is the data you want to store in Redux state
    } catch (error: unknown) {
      if (axios.isAxiosError(error)) {
        return rejectWithValue(
          error.response?.data?.message ||
          "An error occurred while fetching tickets. Please try again later."
        );
      }
      return rejectWithValue("An unexpected error occurred.");
    }
  }
);

export const repliesTickets = createAsyncThunk(
  "tickets/repliesTickets",
  async (id: number, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        `${REPLIES_TICKET}/${id}/replies`,
        "GET",
        "",
        true
      );
      return { ticketId: id, replies: response.data }; // Structure payload for Redux
    } catch (error: any) {
      return rejectWithValue(
        error.response?.data?.message ||
        "An error occurred while fetching replies. Please try again later."
      );
    }
  }
);

// Async thunk to fetch replies for a specific ticket by ID
interface ReplyPayload {
  id: number; // Ticket ID
  message: string; // Reply content
}

export const repliesTicketsId = createAsyncThunk(
  "tickets/repliesTicketsId",
  async ({ id, message }: ReplyPayload, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        `${TICKET_ID_REPLIES}/${id}/reply`,
        "POST",
        { message },
        true
      );
      return { ticketId: id, reply: response.data }; // Payload for the newly added reply
    } catch (error: any) {
      return rejectWithValue(
        error.response?.data?.message ||
        "An error occurred while posting the reply. Please try again later."
      );
    }
  }
);

export const editSeller = createAsyncThunk(
  "seller/editDetail",
  async (id: string) => {
    try {
      const url = `${SELLER_EDIT_DETAIL}/${id}`;
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const editaddress = createAsyncThunk(
  "addressUpdate",
  async (id: number) => {
    try {
      const response = await axiosRequest(
        `${ADDRESS_UPDATE}/${id}`,
        "GET",
        "",
        true
      );
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        throw new Error(
          error.response.data.message || "Failed to fetch message  data"
        );
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const AllFilter = createAsyncThunk("filter", async (payload: any) => {
  try {
    const response = await axiosRequest(FILTER, "POST", payload, true);
    return response;

  } catch {
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
});

export const recommendData = createAsyncThunk(
  "recommendData",
  async (
    {
      id,
      user_id,
      location,
      sub_location,
    }: {
      id: string | number;
      user_id: number;
      location?: string;
      sub_location?: string;
    },
    { rejectWithValue }
  ) => {
    try {
      const url = `${Recommend_listing}?id=${id}&user_id=${user_id}&location=${location}&sub_location=${sub_location}`; // ✅ Corrected '&' instead of second '?'
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      if (error.response?.data) {
        return rejectWithValue(error.response.data);
      } else {
        return rejectWithValue(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const updateOrderStatus = createAsyncThunk(
  "sellerOrders/updateStatus",
  async (
    { id, status }: { id: number; status: string },
    { rejectWithValue }
  ) => {
    try {
      const url = `${Order_Status}/${id}/status`;
      const response = await axiosRequest(url, "PUT", { status }, true);
      return { id, status, response };
    } catch (error: any) {
      return rejectWithValue(
        error.response?.data || "Failed to update order status"
      );
    }
  }
);
export const placeOrder = createAsyncThunk(
  "placeOrder",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        BUYER_PLACE_ORDER,
        "POST",
        payload,
        true
      );

      // If API returns a failed response (success: false), return an error
      if (!response.success) {
        return rejectWithValue(
          response.error || "An unexpected error occurred."
        );
      }

      return response;
    } catch (error: any) {
      // console.error("Error:", error);

      // Extract error message from API response
      const errorMessage =
        error?.response?.data?.error ||
        "An error occurred while processing your request. Please try again later.";
      return rejectWithValue(errorMessage);
    }
  }
);

export const about = createAsyncThunk("about", async () => {
  try {
    const response = await axiosRequest(ABOUT_US, "GET", "", true);
    return response;
  } catch {
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
  // catch (error) {
  //   console.error("Error:", error);
  //   throw new Error(
  //     "An error occurred while processing your request. Please try again later."
  //   );
  // }
});

export const polices = createAsyncThunk("polices", async () => {
  try {
    const response = await axiosRequest(TERMS_POLICIES, "GET", "", true);
    return response;
  } catch {
    // console.error("Error:", error);
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
});

export const terms = createAsyncThunk("terms", async () => {
  try {
    const response = await axiosRequest(TERMS_UPDATE, "GET", "", true);
    return response;
  } catch {
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
  // catch (error) {
  //   console.error("Error:", error);
  //   throw new Error(
  //     "An error occurred while processing your request. Please try again later."
  //   );
  // }
});

export const categoryImages = createAsyncThunk("categoryImages", async () => {
  try {
    const response = await axiosRequest(CATEGORY_IMAGES, "GET", "", true);
    return response;
  } catch {
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
});

export const stateLocation = createAsyncThunk(
  "state",
  async (countryCode: string) => {
    try {
      const response = await axiosRequest(
        `${STATES}/${countryCode}`,
        "GET",
        "",
        true
      );
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }

  }
);

export const SavedDrafts = createAsyncThunk("savedDrafts", async () => {
  try {
    const response = await axiosRequest(ALL_DRAFTS, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const Security = createAsyncThunk(
  "change password",
  async (payload: any) => {
    try {
      const response = await axiosRequest(
        CHANGE_PASSWORD,
        "POST",
        payload,
        true
      );
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    // catch (error) {
    //   console.error("Error:", error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const postDraft = async (payload: any): Promise<any> => {
  try {
    const response = await axiosRequest(POST_DRAFT, "POST", payload, true);

    return response;
  } catch (error) {
    throw error;
  }
};

export const Notification = createAsyncThunk(
  "change password",
  async (payload: any) => {
    try {
      const response = await axiosRequest(
        NOTIFICATION_SETTING,
        "POST",
        payload,
        true
      );
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
    // catch (error) {
    //   console.error("Error:", error);
    //   throw new Error(
    //     "An error occurred while processing your request. Please try again later."
    //   );
    // }
  }
);

export const deleteImage = async (payload: any): Promise<any> => {
  try {
    const response = await axiosRequest(DELETE_IMAGE, "POST", payload, true);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    // console.error("Error deleting Image:", error);
    throw error;
  }
};

export const priorityBids = createAsyncThunk(
  "auth/priorityBids_data",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(PRIORITY_BIDS, "POST", payload, true);
      return response;
    } catch (error: any) {
      const apiError = error?.response?.data?.error || "Something went wrong.";
      return rejectWithValue(apiError);
    }
  }
);

export const subscribeNewsletter = createAsyncThunk(
  "subscribeNewsletter",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(SUBSCRIBE, "POST", payload, true);
      // console.log("chek respose", response);
      return response;
    } catch (error: any) {
      const apiError = error?.response?.data?.error || "Something went wrong.";
      return rejectWithValue(apiError);
    }
  }
);

export const priorityBidsData = createAsyncThunk(
  "priorityData",
  async (id: string, { rejectWithValue }) => {
    try {
      const url = `${PRIORITY_BIDS_DATA}/${id}`;
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      // console.error("Error fetching priority bids data:", error);
      return rejectWithValue(error.response?.data || "Something went wrong");
    }
  }
);

export const priorityBidsUpdate = createAsyncThunk(
  "priorityBidsUpdate",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(
        PRIORITY_BIDS_DATA_UPDATE,
        "POST",
        payload,
        true
      );
      // console.log("priorityBidsUpdate", response);
      return response;
    } catch (error: any) {
      const apiError =
        error?.response?.data?.error ||
        error?.message ||
        "Something went wrong.";
      // console.log("apiError", apiError);
      return rejectWithValue(apiError); // sends to `.rejected` case
    }
  }
);

export const onGoingBids = createAsyncThunk(
  "ongoingBids/getBids",
  async (id: string) => {
    try {
      const url = `${ONGOING_BIDS_DATA}/${id}/bids`;
      const response = await axiosRequest(url, "GET", "", true);
      // console.log("check auction view track order", response);
      return response;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return error.response.data;
      } else {
        throw new Error(
          "An error occurred while processing your request. Please try again later."
        );
      }
    }
  }
);

export const messageCount = createAsyncThunk("messageCount", async () => {
  try {
    const response = await axiosRequest(GETS_COUNT, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const getsIncrement = createAsyncThunk("increment", async () => {
  try {
    const response = await axiosRequest(GETS_INCREMENT, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const bidsHistory = createAsyncThunk("bid history", async () => {
  try {
    const response = await axiosRequest(GETS_BIDS_DATA, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const reviewsHistory = createAsyncThunk("reviewsHistory", async () => {
  try {
    const response = await axiosRequest(GET_REVIEW_HISTORY, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const ongoingBids = createAsyncThunk(
  "ongoingbids",
  async (id: string, { rejectWithValue }) => {
    try {
      const url = `${ONGOINGBIDS}/${id}/bids_clone`;
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data || "Something went wrong");
    }
  }
);


export const tracklistings = createAsyncThunk(
  "track/listings",
  async (id: string, { rejectWithValue }) => {
    try {
      const url = `${TRACKLISTINGS}/${id}`;
      const response = await axiosRequest(url, "GET", "", true);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data || "Something went wrong");
    }
  }
);

export const repostListing = createAsyncThunk(
  "repost/listing",
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(REPOST_LISTING, "POST", payload, true);
      // console.log("chek respose", response);
      return response;
    } catch (error: any) {
      const apiError = error?.response?.data?.error || "Something went wrong.";
      return rejectWithValue(apiError);
    }
  }
);


export const cancelOrder = createAsyncThunk("cancel/ordeer", async (payload: any) => {
  try {
    const response = await axiosRequest(CANCEL_ORDER_LISTING, "POST", payload, true);
    return response;

  } catch {
    throw new Error(
      "An error occurred while processing your request. Please try again later."
    );
  }
});




export const unlockPriorityBids = createAsyncThunk(
  "unlockPriorityBids",
  async (id: any, { rejectWithValue }) => {
    try {
      const url = `${PRIORITY_BIDS_UNLOCK}/${id}`;
      const response = await axiosRequest(url, "GET", "", true);
      // Return full response so slice gets it in fulfilled
      return response;
    } catch (error: any) {
      if (error.response) {
        console.error("❌ API Error Response:", error.response);
        console.error("❌ API Error Data:", error.response.data);
        return rejectWithValue(error.response.data);
      }

      console.error("❌ Unexpected Error:", error.message || error);
      return rejectWithValue({
        message:
          "An error occurred while processing your request. Please try again later.",
      });
    }
  }
);

export const ticketNotification = createAsyncThunk("ticket notification", async () => {
  try {
    const response = await axiosRequest(TICKET_NOTIFICATION, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});



export const readNotification = createAsyncThunk(
  "readNotification",
  async () => {
    try {
      const response = await axiosRequest(NOTFICATION_ALL_READ, "POST", null, true);
      return response;
    } catch {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
);


export const ratingInfo = createAsyncThunk("ratingInfo", async () => {
  try {
    const response = await axiosRequest(RATING_INFO, "Get", "", true);
    return response;
  } catch (error: any) {
    if (error.response && error.response.data) {
      return error.response.data;
    } else {
      throw new Error(
        "An error occurred while processing your request. Please try again later."
      );
    }
  }
});

export const readNotificationData = createAsyncThunk(
  "readNotificationData",
  async (id, { rejectWithValue }) => {
    try {
      const response = await axiosRequest(`${READ_NOTIFICATION}/${id}/read`, "POST",
        "",
        true
      );
      return response;
    } catch (error: any) {
      return rejectWithValue(
        error.response?.data?.message || "An error occurred while processing your request. Please try again later."
      );
    }
  }
);
