import { LmsDashboardData } from '@/interface/Lms';
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 { LmsDashboardActions } from './actionTypes';

interface LmsDashboardState {
  data: LmsDashboardData | null;
  loading: boolean;
  error: string | null;
}

const initialState: LmsDashboardState = {
  data: null,
  loading: false,
  error: null,
};

export const fetchLmsDashboard = createAsyncThunk(
  LmsDashboardActions.FETCH_LMS_DASHBOARD,
  async (year: number, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/lms/dashboard?year=${year}`,
      )) as AxiosResponse<{ data: LmsDashboardData }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const LmsDashboardSlice = createSlice({
  name: 'lmsDashboard',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchLmsDashboard.pending, (state: Draft<LmsDashboardState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchLmsDashboard.fulfilled,
        (state: Draft<LmsDashboardState>, action: PayloadAction<LmsDashboardData>) => {
          state.loading = false;
          state.data = action.payload;
          state.error = null;
        },
      )
      .addCase(
        fetchLmsDashboard.rejected,
        (state: Draft<LmsDashboardState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      );
  },
});

export default LmsDashboardSlice;
