"use client";
import Cookies from "js-cookie";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { registerUser, loginUser } from "@/lib/actions/authActions";

// Define types for user data
interface User {
  id: any;
  name: any;
  email: any;
}

interface AuthResponse {
  success: any;
  message?: any;
  errors?: any;
  authData?: User;
}

interface AuthState {
  user: any ;
  isLoading: boolean;
  error: any;
  successMessage: any;
}

// Initial state with type
const initialState: AuthState = {
  user: null,
  isLoading: false,
  error: null,
  successMessage: null,
};

const loadUserFromStorage = (): any => {
  if (typeof window !== "undefined") {
    const storedUser = Cookies.get("user");
    return storedUser ? JSON.parse(storedUser) : null;
  }
  return null;
};

// Update initial state with loaded user
const updatedInitialState: AuthState = {
  ...initialState,
  user: loadUserFromStorage(),
};

export const registerUserThunk = createAsyncThunk<
  AuthResponse,
  any,
  { rejectValue: AuthResponse }
>("auth/register", async (userData, { rejectWithValue }) => {
  const response = await registerUser(userData);
  if (!response.success) return rejectWithValue(response);
  return response;
});

export const loginUserThunk = createAsyncThunk<
  AuthResponse,
  any,
  { rejectValue: AuthResponse }
>("auth/login", async (userData: any, { rejectWithValue }) => {
  const response = await loginUser(userData);
  if (!response.success) return rejectWithValue(response);
  return response;
});

const authSlice = createSlice({
  name: "auth",
  initialState: updatedInitialState,
  reducers: {
    clearMessages: (state) => {
      state.error = null;
      state.successMessage = null;
    },
    setVolgeur: (state) => {
      state.error = null;
      state.successMessage = null;
    },
    logout: (state) => {
      state.user = null;
      Cookies.remove("user");
    },
    setUser: (state, action) => {
      // state.user = action.payload;
      //  state.user = {
      //   ...state.user, 
      //   ...action.payload, 
      // };
      // Cookies.set("user", JSON.stringify(action.payload), {
      //   expires: 7,
      // });
       const updatedUser = {
        ...state.user,      // keep existing fields
        ...action.payload,  // override with incoming fields
      };
      state.user = updatedUser;
      Cookies.set("user", JSON.stringify(updatedUser), {
        expires: 7,
      });
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(registerUserThunk.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(registerUserThunk.fulfilled, (state, action) => {
        state.isLoading = false;
        state.successMessage = action.payload.message || null;
      })
      .addCase(registerUserThunk.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload?.errors || action.payload?.message || "Registration failed";
      })
      .addCase(loginUserThunk.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loginUserThunk.fulfilled, (state, action) => {
        state.isLoading = false;
        state.user = action.payload?.authData || null;
        state.successMessage = action.payload?.message || null;
        if (action.payload?.authData) {
          Cookies.set("user", JSON.stringify(action.payload.authData), {
            expires: 7,
          });
        }
      })
      .addCase(loginUserThunk.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload?.errors || action.payload?.message || "Login failed";
      });
  },
});

export const { clearMessages, setVolgeur, logout, setUser } = authSlice.actions;
export default authSlice.reducer;