import {
  TrainingOverviewData,
  DepartmentTrainingReportData,
  BranchTrainingReportData,
} from '@/interface/TrainingDashboard';
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 { TrainingDashboardActions } from './actionTypes';

interface TrainingDashboardState {
  overview: TrainingOverviewData | null;
  departmentReport: DepartmentTrainingReportData | null;
  branchReport: BranchTrainingReportData | null;
  loading: boolean;
  error: string | null;
}

const initialState: TrainingDashboardState = {
  overview: null,
  departmentReport: null,
  branchReport: null,
  loading: false,
  error: null,
};

export const fetchTrainingOverview = createAsyncThunk(
  TrainingDashboardActions.FETCH_TRAINING_OVERVIEW,
  async (year: number, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/training/dashboard/overview?year=${year}`,
      )) as AxiosResponse<{ data: TrainingOverviewData }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchDepartmentTrainingReport = createAsyncThunk(
  TrainingDashboardActions.FETCH_DEPARTMENT_REPORT,
  async (params: { departmentId: string; year: number }, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/training/dashboard/department/${params.departmentId}?year=${params.year}`,
      )) as AxiosResponse<DepartmentTrainingReportData>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchBranchTrainingReport = createAsyncThunk(
  TrainingDashboardActions.FETCH_BRANCH_REPORT,
  async (params: { branchId: string; year: number }, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/training/dashboard/branch/${params.branchId}?year=${params.year}`,
      )) as AxiosResponse<BranchTrainingReportData>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const TrainingDashboardSlice = createSlice({
  name: 'trainingDashboard',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchTrainingOverview.pending, (state: Draft<TrainingDashboardState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchTrainingOverview.fulfilled,
        (state: Draft<TrainingDashboardState>, action: PayloadAction<TrainingOverviewData>) => {
          state.loading = false;
          state.overview = action.payload;
          state.error = null;
        },
      )
      .addCase(
        fetchTrainingOverview.rejected,
        (state: Draft<TrainingDashboardState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      )

      .addCase(fetchDepartmentTrainingReport.pending, (state: Draft<TrainingDashboardState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchDepartmentTrainingReport.fulfilled,
        (
          state: Draft<TrainingDashboardState>,
          action: PayloadAction<DepartmentTrainingReportData>,
        ) => {
          state.loading = false;
          state.departmentReport = action.payload;
          state.error = null;
        },
      )
      .addCase(
        fetchDepartmentTrainingReport.rejected,
        (state: Draft<TrainingDashboardState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      )

      .addCase(fetchBranchTrainingReport.pending, (state: Draft<TrainingDashboardState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchBranchTrainingReport.fulfilled,
        (
          state: Draft<TrainingDashboardState>,
          action: PayloadAction<BranchTrainingReportData>,
        ) => {
          state.loading = false;
          state.branchReport = action.payload;
          state.error = null;
        },
      )
      .addCase(
        fetchBranchTrainingReport.rejected,
        (state: Draft<TrainingDashboardState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      );
  },
});

export default TrainingDashboardSlice;
