import { RejectedActionPayload } from '@/interface/Shared';
import { apiGet } from '@/services/api/api';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft } from '@reduxjs/toolkit';

interface TeamAttendanceRecord {
  id: string;
  employee_id: string;
  employee: { employee_id: string; firstname: string; lastname: string; staff_id: string };
  date: string;
  clock_in: string | null;
  clock_out: string | null;
  status: string;
  [key: string]: any;
}

interface PaginationMeta {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

interface TeamAttendanceState {
  records: TeamAttendanceRecord[];
  meta: PaginationMeta | null;
  loading: boolean;
  error: string | null;
}

const initialState: TeamAttendanceState = {
  records: [],
  meta: null,
  loading: false,
  error: null,
};

export const fetchTeamAttendance = createAsyncThunk(
  'teamAttendance/fetchTeamAttendance',
  async (params: { from?: string; to?: string; page?: number; per_page?: number } = {}, { rejectWithValue }) => {
    try {
      const response = await apiGet('/hr/my-team/attendance', { params });
      return response.data;
    } catch (error: any) {
      return rejectWithValue(Helpers.handleServerError(error));
    }
  },
);

const TeamAttendanceSlice = createSlice({
  name: 'teamAttendance',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchTeamAttendance.pending, (state: Draft<TeamAttendanceState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchTeamAttendance.fulfilled, (state: Draft<TeamAttendanceState>, action) => {
        state.loading = false;
        state.records = action.payload.data ?? action.payload;
        if (action.payload.meta) {
          state.meta = action.payload.meta;
        }
      })
      .addCase(fetchTeamAttendance.rejected, (state: Draft<TeamAttendanceState>, action) => {
        state.loading = false;
        state.error = (action.payload as RejectedActionPayload)?.message ?? 'Failed to fetch team attendance';
      });
  },
});

export default TeamAttendanceSlice;
