// app/features/campaign/campaignSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Campaign } from "@/app/types";
import { fetchGeoPricingLocations } from "@/app/redux/services/main/advert/advertServices";
// Campaign Form State Interface
export interface CampaignFormState {
  media_type: string;
  advert_type: string;
  advert_redirect_url?: string;
  location: string;
  startDate: string;
  endDate: string;
  price: number;
  commune: string;
  mapCentercommune: string;
  postcode: string;
  coupon_code: string;
  format: string;
  title: string;
  event_id: string;
  user_notes: string;
  duration: number;
  image: string;
  eventImageUrl: string;
  tier: string;
  totalprice: string;
  mapCenterlat: string;
  mapCenterlang: string;
  price_per_day: string;
  geo_price_level: string;

  // events: any[];
}

interface GeoPricingData {
  id: number;
  tier: number;
  image: string;
  large_image: string;
  large_image_rich_text: string;
  large_image_video: string;
  banner: string;
}
interface CampaignState {
  campaigns: Campaign[];
  selectedCampaign: Campaign | null;
  campaignForm: CampaignFormState;
  selectedEvents: CampaignFormState[];
  geoPricingData: GeoPricingData | null;
  geoPricingDataArray: any[];
  loading: boolean;
  error: string | null;
  success: boolean;
  isLoadingGeoPricing: boolean;
}

const initialFormState: CampaignFormState = {
  media_type: "image",
  advert_type: "large",
  advert_redirect_url: "",
  location: "",
  startDate: "",
  endDate: "",
  price: 0,
  title: "",
  commune: "Toulouse",
  mapCentercommune: "",
  postcode: "31000",
  coupon_code: "",
  user_notes: "",
  format: "250 X 350px",
  event_id: "",
  duration: 0,
  tier: "",
  image: "",
  eventImageUrl: "",
  totalprice: "",
  mapCenterlat: "",
  mapCenterlang: "",
  price_per_day: "",
  geo_price_level: "",
};

const initialState: CampaignState = {
  campaigns: [],
  selectedCampaign: null,
  campaignForm: initialFormState,
  selectedEvents: [],
  geoPricingData: null,
  isLoadingGeoPricing: false,
  geoPricingDataArray: [],
  loading: false,
  error: null,
  success: false,
};

export const advertSlice = createSlice({
  name: "campaign",
  initialState,
  reducers: {
    setSelectedCampaign: (state, action: PayloadAction<Campaign | null>) => {
      state.selectedCampaign = action.payload;
    },
    clearSelectedCampaign: (state) => {
      state.selectedCampaign = null;
    },

    updateCampaignFormAlt: (
      state: CampaignState,
      action: PayloadAction<{
        key: keyof CampaignFormState;
        value: string | number | any[] | boolean;
      }>
    ) => {
      const { key, value } = action.payload;
      (state.campaignForm as any)[key] = value;
    },

    setCampaignForm: (
      state,
      action: PayloadAction<Partial<CampaignFormState>>
    ) => {
      state.campaignForm = { ...state.campaignForm, ...action.payload };
    },

    resetCampaignForm: (state) => {
      state.campaignForm = initialFormState;
    },

    addToSelectedEvents: (state) => {
      state.selectedEvents.push({ ...state.campaignForm });
    },

    removeFromSelectedEvents: (state, action: PayloadAction<string>) => {
      state.selectedEvents = state.selectedEvents.filter(
        (event) => event.event_id !== action.payload
      );
    },

    setSelectedEvents: (state, action: PayloadAction<CampaignFormState[]>) => {
      state.selectedEvents = action.payload;
    },

    resetCampaignState: () => initialState,
    resetPrice: (state) => {
      state.campaignForm.price = 0;
    },
    setAdvertRedirectUrl: (state, action: PayloadAction<string>) => {
      state.campaignForm.advert_redirect_url = action.payload;
    },
    updateSelectedEventDuration: (
      state,
      action: PayloadAction<{
        eventId: string;
        duration: number;
        price: any;
      }>
    ) => {
      const { eventId, duration, price } = action.payload;
      const eventIndex = state.selectedEvents.findIndex(
        (event) => event.event_id === eventId
      );

      if (eventIndex !== -1) {
        state.selectedEvents[eventIndex] = {
          ...state.selectedEvents[eventIndex],
          duration,
          price,
        };
      }
    },
  },
  extraReducers: (builder) => {
    builder
      // Fetch Geo Pricing Locations
      .addCase(fetchGeoPricingLocations.pending, (state) => {
        state.isLoadingGeoPricing = true;
      })
      .addCase(fetchGeoPricingLocations.fulfilled, (state, action) => {
        state.isLoadingGeoPricing = false;
        if (action.payload) {
          state.geoPricingData = action.payload[0];
          state.geoPricingDataArray = action.payload;
        }
      })
      .addCase(fetchGeoPricingLocations.rejected, (state, action) => {
        state.isLoadingGeoPricing = false;
        state.geoPricingData = null;
      });
  },
});

export const {
  setSelectedCampaign,
  clearSelectedCampaign,
  updateCampaignFormAlt,
  setCampaignForm,
  resetCampaignForm,
  resetCampaignState,
  addToSelectedEvents,
  resetPrice,
  removeFromSelectedEvents,
  setAdvertRedirectUrl,
  updateSelectedEventDuration,
  setSelectedEvents,
} = advertSlice.actions;

export default advertSlice.reducer;
