// app/features/auth/authSlice.ts
import { createSlice } from "@reduxjs/toolkit";
import {
  loginUser,
  handleGoogleOAuthCallback,
} from "../../services/auth/authServices";
import { fetchUserWallets } from "../../../redux/services/main/campaigns/mycampaign";
import Cookies from "js-cookie";
interface User {
  id: number;
  email: string;
  firstName: string;
  lastName: string;
  avatar?: string;
  role: string;
  isVerified: boolean;
  createdAt: string;
}
interface WalletUser {
  id: number;
  name: string;
  christian_name: string;
  sur_name: string;
  username: string;
  email?: string;
  phone?: string;
  // Add other user fields as needed based on your API response
}
interface Wallet {
  id: number;
  balance: string;
  created_at: string;
  expiry_date: string;
  updated_at: string;
  notes: string;
  user_id: number;
  user: WalletUser;
}
interface AuthState {
  user: User | null;
  wallet: Wallet | null;
  token: string | null;
  loading: boolean;
  error: string | null;
  success: boolean;
  isAuthenticated: boolean;
  isSidebarOpen: boolean;
}

const initialState: AuthState = {
  user: null,
  wallet: null,
  token: null,
  loading: false,
  error: null,
  success: false,
  isAuthenticated: false,
  isSidebarOpen: false,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    updateUserProfile: (state, action) => {
      if (state.user) {
        state.user = { ...state.user, ...action.payload };
      }
    },

    // Clear authentication state (logout)
    clearAuth: (state) => {
      state.user = null;
      state.token = null;
      state.isAuthenticated = false;
      state.error = null;
      state.success = false;
      localStorage.removeItem("token");
    },
    toggleSidebar: (state) => {
      state.isSidebarOpen = !state.isSidebarOpen;
    },
    clearError: (state) => {
      state.error = null;
    },
  },

  extraReducers: (builder) => {
    builder
      // Login cases
      .addCase(loginUser.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.success = false;
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.loading = false;
        state.user = action.payload.data;
        state.token = action.payload.token;
        state.isAuthenticated = true;
        state.success = true;
        state.error = null;
        localStorage.setItem("user_id", action.payload.data.user_id);
        localStorage.setItem("promo_code", action.payload.data.promo_code);
        localStorage.setItem(
          "stripe_coupon_id",
          action.payload.data.stripe_coupon_id
        );
        localStorage.setItem("user_info", JSON.stringify(action.payload.data));
        Cookies.set("stripe_coupon_id", action.payload.data.stripe_coupon_id);
        Cookies.set("promo_code", action.payload.data.promo_code);
        Cookies.set("user_info", JSON.stringify(action.payload.data));
        Cookies.set("user_id", JSON.stringify(action.payload.data.user_id));
        Cookies.set(
          "stripe_customer_id",
          JSON.stringify(action.payload.data.stripe_customer_id)
        );
        Cookies.set(
          "promo_code_assigned",
          JSON.stringify(action.payload.data.promo_code_assigned)
        );
        Cookies.set("token", action.payload.token);
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        state.isAuthenticated = false;
        state.success = false;
        state.user = null;
        state.token = null;
      })
      .addCase(fetchUserWallets.fulfilled, (state, action) => {
        state.loading = false;
        state.wallet = action.payload.data[0];
      })
      // Google OAuth callback cases
      .addCase(handleGoogleOAuthCallback.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.success = false;
      })
      .addCase(handleGoogleOAuthCallback.fulfilled, (state, action) => {
        state.loading = false;
        state.user = action.payload.data as any; // API response structure doesn't match User interface
        state.token = action.payload.token;
        state.isAuthenticated = true;
        state.success = true;
        state.error = null;
        // Save to localStorage (same as loginUser)
        localStorage.setItem("user_id", String(action.payload.data.user_id));
        localStorage.setItem(
          "promo_code",
          action.payload.data.promo_code || ""
        );
        localStorage.setItem(
          "stripe_coupon_id",
          action.payload.data.stripe_coupon_id || ""
        );
        localStorage.setItem("user_info", JSON.stringify(action.payload.data));
        // Save to cookies (same as loginUser)
        Cookies.set(
          "stripe_coupon_id",
          action.payload.data.stripe_coupon_id || ""
        );
        Cookies.set("promo_code", action.payload.data.promo_code || "");
        Cookies.set("user_info", JSON.stringify(action.payload.data));
        Cookies.set("user_id", String(action.payload.data.user_id));
        Cookies.set(
          "stripe_customer_id",
          String(action.payload.data.stripe_customer_id || "")
        );
        Cookies.set(
          "promo_code_assigned",
          String(action.payload.data.promo_code_assigned || false)
        );
        Cookies.set("token", action.payload.token);
      })
      .addCase(handleGoogleOAuthCallback.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        state.isAuthenticated = false;
        state.success = false;
        state.user = null;
        state.token = null;
      });
  },
});

export const { updateUserProfile, clearAuth, clearError, toggleSidebar } =
  authSlice.actions;
export default authSlice.reducer;
