import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axiosInstance from "../../utils/axiosConfig";
import endpoints from "../../config/apiEndpoints";

interface Notification {
  check: boolean;
  notification_id: number;
  photo: string;
  message: string;
  time: string;
  read_at: string;
  type: string;
  notify_by: number;
  info_id: number;
  route: string;
}

interface NotificationState {
  notifications: Notification[];
  isModalOpen: boolean;
  loading: boolean;
  error: string | null;
  dataFetched: boolean;
}

const { notifications: notificationsApi} = endpoints;

  export const fetchNotificationData = createAsyncThunk(
    'notifications/fetchData',
    async (_, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.get(notificationsApi);
        return response.data.data;
      } catch (error) {
        console.error('Error fetching notification data:', error);
        return rejectWithValue((error as Error).message);
      }
    }
  );

const initialState: NotificationState = {
    notifications: [],
    isModalOpen: false,
    loading: false,
    error: null,
    dataFetched: false,
  };

const notificationSlice = createSlice({
    name: 'notifications',
    initialState,
    reducers: {
      toggleModal: (state) => {
        state.isModalOpen = !state.isModalOpen; 
      }
    },
    extraReducers: (builder) => {
        builder
          .addCase(fetchNotificationData.pending, (state) => {
            state.loading = true;
            state.error = null;
          })
          .addCase(fetchNotificationData.fulfilled, (state, action) => {
            state.loading = false;
            state.notifications = action.payload;
    
            state.dataFetched = true;
          })
          .addCase(fetchNotificationData.rejected, (state, action) => {
            state.loading = false;
            state.error = action.payload as string;
          })
      }
  });


  export const { toggleModal } = notificationSlice.actions;
  
  // Export reducer
  export default notificationSlice.reducer;