import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import AttendanceRepository from '../../repositories/AttendanceRepository';
import {clearCacheKey} from '../apiDataManager';

// Fetch attendance data
export const fetchAttendanceData = createAsyncThunk(
  'attendanceLogs/fetchAttendanceData',
  async ( {projectId, fromDate, toDate}, thunkAPI ) =>
  {
    try {
      const response = await AttendanceRepository.getAttendanceFilteredByDate(projectId, fromDate, toDate);
      return response?.data?.filter((log) => log.checkInTime !== null && log.activity !== 0);
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);


export const markAttendance = createAsyncThunk(
  'attendanceLogs/markAttendance',  // Updated action type prefix
  async ( formData, thunkAPI ) =>
  
  {
    try {
      let newRecordAttendance = {
        Id: formData.id || null,
        comment: formData.description,
        employeeID: formData.employeeId,
        projectID: formData.projectId,
        date: new Date().toISOString(),
        markTime: formData.markTime,
        latitude: formData.latitude.toString(),
        longitude: formData.longitude.toString(),
        action: formData.action,
        image: null,
      };

      const response = await AttendanceRepository.markAttendance( newRecordAttendance );
      return response.data;  
    } catch ( error )
    {
      const message = error?.response?.data?.message || error.message || "Error Occured During Api Call";
      return thunkAPI.rejectWithValue(message);
    }
  }
);

// Attendance Logs Slice
const attendanceLogsSlice = createSlice({
  name: 'attendanceLogs',  // Updated slice name
  initialState: {
    data: [],
    loading: false,
    error: null,
  },
  reducers: {
    setAttendanceData: (state, action) => {
      state.data = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      // Fetch attendance data
      .addCase(fetchAttendanceData.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchAttendanceData.fulfilled, (state, action) => {
        state.loading = false;
        state.data = action.payload;
      })
      .addCase(fetchAttendanceData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })

      // Mark attendance - log attenace data
      .addCase(markAttendance.fulfilled, (state, action) => {
        const updatedRecord = action.payload;
        const index = state.data.findIndex(item => item.id === updatedRecord.id);
      
        if (index !== -1) {
          state.data[index] = { ...state.data[index], ...updatedRecord };  
        } else {
          state.data.push(updatedRecord); 
        }
      });
      
  },
});

export const { setAttendanceData } = attendanceLogsSlice.actions;
export default attendanceLogsSlice.reducer;
