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

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

// This method for marking attendance if a date filter is applied
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.time,
        latitude: formData.latitude.toString(),
        longitude: formData.longitude.toString(),
        action: formData.action,
        image: null,
      };

      const response = await AttendanceRepository.markAttendance(newRecordAttendance);
      return response.data;  // Return the newly created or updated record
    } catch (error) {
      return thunkAPI.rejectWithValue(error.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
      .addCase(markAttendance.fulfilled, (state, action) => {
        const updatedRecord = action.payload;
        const index = state.data.findIndex(item => item.employeeId === updatedRecord.employeeId);

        if (index !== -1) {
          state.data[index] = { ...state.data[index], ...updatedRecord };  // Update existing record
        } else {
          state.data.push(updatedRecord);  // Add new record if not found
        }
      });
  },
});

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