import {
  CreatePensionAllocationProfilePayload,
  PensionAllocationProfile,
  UpdatePensionAllocationProfilePayload,
} from '@/interface/PensionConfig';
import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { apiDelete, apiGet, apiPost, apiPut } 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 { PensionAllocationProfilesActions } from './actionTypes';

interface PensionAllocationProfilesState {
  pensionAllocationProfiles: PensionAllocationProfile[];
  loading: boolean;
  error: string | null;
}

const initialState: PensionAllocationProfilesState = {
  pensionAllocationProfiles: [],
  loading: false,
  error: null,
};

export const fetchPensionAllocationProfiles = createAsyncThunk(
  PensionAllocationProfilesActions.FETCH_PENSION_ALLOCATION_PROFILES_REQUEST,
  async (params?: { country_code?: string; active?: boolean }, { rejectWithValue }) => {
    try {
      const queryParams = new URLSearchParams();
      if (params?.country_code) queryParams.append('country_code', params.country_code);
      if (params?.active !== undefined) queryParams.append('active', params.active ? '1' : '0');
      queryParams.append('per_page', '200');
      const query = queryParams.toString() ? `?${queryParams.toString()}` : '';

      const response = (await apiGet(
        `/payroll/pension-allocation-profiles${query}`,
      )) as AxiosResponse<PensionAllocationProfile[] | { data: PensionAllocationProfile[] }>;

      return Array.isArray(response.data) ? response.data : response.data.data || [];
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createPensionAllocationProfile = createAsyncThunk(
  PensionAllocationProfilesActions.CREATE_PENSION_ALLOCATION_PROFILE_REQUEST,
  async (payload: CreatePensionAllocationProfilePayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost('/payroll/pension-allocation-profiles', payload)) as AxiosResponse<{
        data: PensionAllocationProfile;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updatePensionAllocationProfile = createAsyncThunk(
  PensionAllocationProfilesActions.UPDATE_PENSION_ALLOCATION_PROFILE_REQUEST,
  async (payload: UpdatePensionAllocationProfilePayload, { rejectWithValue }) => {
    try {
      const { id, ...data } = payload;
      const response = (await apiPut(`/payroll/pension-allocation-profiles/${id}`, data)) as AxiosResponse<{
        data: PensionAllocationProfile;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deletePensionAllocationProfile = createAsyncThunk(
  PensionAllocationProfilesActions.DELETE_PENSION_ALLOCATION_PROFILE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      await apiDelete(`/payroll/pension-allocation-profiles/${id}`);
      return id;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const PensionAllocationProfilesSlice = createSlice({
  name: 'pensionAllocationProfiles',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchPensionAllocationProfiles.pending, (state: Draft<PensionAllocationProfilesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchPensionAllocationProfiles.fulfilled,
        (state: Draft<PensionAllocationProfilesState>, action: PayloadAction<PensionAllocationProfile[]>) => {
          state.pensionAllocationProfiles = action.payload;
          state.loading = false;
          state.error = null;
        },
      )
      .addCase(fetchPensionAllocationProfiles.rejected, (state: Draft<PensionAllocationProfilesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = Helpers.handleServerError(action.payload);
        message.error(state.error, 10);
      });

    builder
      .addCase(createPensionAllocationProfile.pending, (state: Draft<PensionAllocationProfilesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        createPensionAllocationProfile.fulfilled,
        (state: Draft<PensionAllocationProfilesState>, action: PayloadAction<PensionAllocationProfile>) => {
          state.pensionAllocationProfiles.unshift(action.payload);
          state.loading = false;
          state.error = null;
          message.success('Pension allocation profile created successfully');
        },
      )
      .addCase(createPensionAllocationProfile.rejected, (state: Draft<PensionAllocationProfilesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = Helpers.handleServerError(action.payload);
        message.error(state.error, 10);
      });

    builder
      .addCase(updatePensionAllocationProfile.pending, (state: Draft<PensionAllocationProfilesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        updatePensionAllocationProfile.fulfilled,
        (state: Draft<PensionAllocationProfilesState>, action: PayloadAction<PensionAllocationProfile>) => {
          const index = state.pensionAllocationProfiles.findIndex(
            (profile) => profile.id === action.payload.id,
          );
          if (index !== -1) {
            state.pensionAllocationProfiles[index] = action.payload;
          }
          state.loading = false;
          state.error = null;
          message.success('Pension allocation profile updated successfully');
        },
      )
      .addCase(updatePensionAllocationProfile.rejected, (state: Draft<PensionAllocationProfilesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = Helpers.handleServerError(action.payload);
        message.error(state.error, 10);
      });

    builder
      .addCase(deletePensionAllocationProfile.pending, (state: Draft<PensionAllocationProfilesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deletePensionAllocationProfile.fulfilled, (state: Draft<PensionAllocationProfilesState>, action: PayloadAction<string>) => {
        state.pensionAllocationProfiles = state.pensionAllocationProfiles.filter(
          (profile) => profile.id !== action.payload,
        );
        state.loading = false;
        state.error = null;
        message.success('Pension allocation profile deleted successfully');
      })
      .addCase(deletePensionAllocationProfile.rejected, (state: Draft<PensionAllocationProfilesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = Helpers.handleServerError(action.payload);
        message.error(state.error, 10);
      });
  },
});

export default PensionAllocationProfilesSlice;
export type { PensionAllocationProfilesState };
