import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import { getUserId, getToken, getPromoCode } from "@/app/utils/token";
import { CommuneHub } from "@/app/types";
export const fetchUserCampaigns = createAsyncThunk(
  "campaign/fetchUserCampaigns",
  async (_, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!userId) {
        return rejectWithValue("User ID not found");
      }

      if (!token) {
        return rejectWithValue("Authentication token not found");
      }

      const response = await axios.get(
        `${baseURL}/sep-user-campaign?userId=${userId}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: "Campaigns fetched successfully",
        };
      } else {
        return rejectWithValue("No campaigns data received");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        "Failed to fetch campaigns";
      return rejectWithValue(errorMessage);
    }
  }
);
export const fetchCommuneHubs = createAsyncThunk(
  "commune/fetchCommuneHubs",
  async (_, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;

      if (!baseURL) {
        return rejectWithValue("API base URL not configured");
      }

      const response = await axios.get(`${baseURL}/event-hub`, {
        headers: {
          "Content-Type": "application/json",
        },
      });

      if (response.data && Array.isArray(response.data)) {
        return {
          data: response.data as CommuneHub[],
          message: "Commune hubs fetched successfully",
        };
      } else {
        return rejectWithValue("Invalid response format from commune hubs API");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        error.message ||
        "Failed to fetch commune hubs";
      return rejectWithValue(errorMessage);
    }
  }
);


export const deleteUserCampaign = createAsyncThunk(
  "campaign/deleteUserCampaign",
  async (campaignId: number, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!userId) {
        return rejectWithValue("User ID not found");
      }

      if (!token) {
        return rejectWithValue("Authentication token not found");
      }

      if (!campaignId) {
        return rejectWithValue("Campaign ID is required");
      }

      const response = await axios.delete(
        `${baseURL}/sep-user-campaign/${campaignId}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          data: {
            user: {
              user_id: userId,
            },
          },
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: "Campaign deleted successfully",
          campaignId: campaignId,
        };
      } else {
        return rejectWithValue("No response data received");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        "Failed to delete campaign";
      return rejectWithValue(errorMessage);
    }
  }
);

export const postponeUserCampaign = createAsyncThunk(
  "campaign/postponeUserCampaign",
  async (campaignId: number, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!userId) {
        return rejectWithValue("User ID not found");
      }

      if (!token) {
        return rejectWithValue("Authentication token not found");
      }

      if (!campaignId) {
        return rejectWithValue("Campaign ID is required");
      }

      const response = await axios.post(
        `${baseURL}/sep-user-campaign/${campaignId}/postpone`,
        {
          user: {
            user_id: userId,
          },
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: "Campaign postponed successfully",
          campaignId: campaignId,
        };
      } else {
        return rejectWithValue("No response data received");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        "Failed to postpone campaign";
      return rejectWithValue(errorMessage);
    }
  }
);
export const fetchUserWallets = createAsyncThunk(
  "wallet/fetchUserWallets",
  async (_, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!baseURL) {
        return rejectWithValue("API base URL not configured");
      }

      if (!userId) {
        return rejectWithValue("User ID not found");
      }

      if (!token) {
        return rejectWithValue("Authentication token not found");
      }

      const response = await axios.get(
        `${baseURL}/user-wallets/user/${userId}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          data: {
            user: {
              user_id: userId,
            },
          },
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: "User wallets fetched successfully",
        };
      } else {
        return rejectWithValue("No wallet data received");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        error.message ||
        "Failed to fetch user wallets";
      return rejectWithValue(errorMessage);
    }
  }
);
export const fetchCategories = createAsyncThunk(
  "category/fetchCategories",
  async (_, { rejectWithValue }) => {
    try {
      const response = await axios.get(
        `https://admin.eventx.fr/api/get-category?language=fr`, // Added /api
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data && response.data.status === 200) {
        return {
          data: response.data.categoryList as any,
          message: response.data.message || "Categories fetched successfully",
        };
      } else {
        return rejectWithValue(response.data?.message || "Failed to fetch categories");
      }
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.message ||
        error.response?.data?.error ||
        error.message ||
        "Failed to fetch categories";
      return rejectWithValue(errorMessage);
    }
  }
);