import { LeaveDashboardData } from '@/interface/LeaveDashboard';
import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { apiGet } from '@/services/api/api';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import axios, { AxiosResponse } from 'axios';
import { LeaveDashboardActions } from './actionTypes';

interface LeaveDashboardState {
  dashboard: LeaveDashboardData | null;
  loading: boolean;
  error: string | null;
}

const initialState: LeaveDashboardState = {
  dashboard: null,
  loading: false,
  error: null,
};

export const fetchLeaveDashboard = createAsyncThunk(
  LeaveDashboardActions.FETCH_LEAVE_DASHBOARD_REQUEST,
  async (_, { rejectWithValue }) => {
    try {
      const response = (await apiGet('/leave/dashboard')) as AxiosResponse<LeaveDashboardData>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const LeaveDashboardSlice = createSlice({
  name: 'leaveDashboard',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchLeaveDashboard.pending, (state: Draft<LeaveDashboardState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchLeaveDashboard.fulfilled,
        (state: Draft<LeaveDashboardState>, action: PayloadAction<LeaveDashboardData>) => {
          state.loading = false;
          state.error = null;
          state.dashboard = action.payload;
        },
      )
      .addCase(fetchLeaveDashboard.rejected, (state: Draft<LeaveDashboardState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = Helpers.handleServerError(action.payload);
        message.error(state.error, 10);
      });
  },
});

export default LeaveDashboardSlice;
export type { LeaveDashboardState };
