import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  CreateDeductionTypePayload,
  DeductionType,
  DeleteDeductionTypePayload,
  UpdateDeductionTypePayload,
} from '@/interface/DeductionType';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import { DeductionTypesActions } from './actionTypes';
import { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import axios, { AxiosResponse } from 'axios';

interface DeductionTypeState {
  deductionTypes: DeductionType[];
  loading: boolean;
  error: string | null;
}

const initialState: DeductionTypeState = {
  deductionTypes: [],
  loading: false,
  error: null,
};

export const fetchDeductionTypes = createAsyncThunk(
  DeductionTypesActions.FETCH_DEDUCTION_TYPES_REQUEST,
  async (params?: { active?: boolean; search?: string }) => {
    const queryParams = new URLSearchParams();
    if (params?.active !== undefined) queryParams.append('active', String(params.active));
    if (params?.search) queryParams.append('search', params.search);
    const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
    const response = (await apiGet(`/payroll/deduction-types${query}`)) as AxiosResponse<
      DeductionType[]
    >;
    return response.data;
  },
);

export const createDeductionType = createAsyncThunk(
  DeductionTypesActions.CREATE_DEDUCTION_TYPE_REQUEST,
  async (payload: CreateDeductionTypePayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/payroll/deduction-types',
        payload,
      )) as AxiosResponse<{ data: DeductionType }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateDeductionType = createAsyncThunk(
  DeductionTypesActions.UPDATE_DEDUCTION_TYPE_REQUEST,
  async (payload: UpdateDeductionTypePayload, { rejectWithValue }) => {
    try {
      const { id, ...data } = payload;
      const response = (await apiPut(
        `/payroll/deduction-types/${id}`,
        data,
      )) as AxiosResponse<{ data: DeductionType }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteDeductionType = createAsyncThunk(
  DeductionTypesActions.DELETE_DEDUCTION_TYPE_REQUEST,
  async (id: string) => {
    const response = (await apiDelete(
      `/payroll/deduction-types/${id}`,
    )) as AxiosResponse<DeleteDeductionTypePayload>;
    const responseData = response.data;
    responseData.id = id;
    return responseData;
  },
);

export const DeductionTypesSlice = createSlice({
  name: 'deductionTypes',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchDeductionTypes.pending, (state: Draft<DeductionTypeState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchDeductionTypes.fulfilled,
        (state: Draft<DeductionTypeState>, action: PayloadAction<DeductionType[]>) => {
          state.deductionTypes = action.payload;
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(fetchDeductionTypes.rejected, (state: Draft<DeductionTypeState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = 'Failed to load deduction types. Please try again or contact support';
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createDeductionType.pending, (state: Draft<DeductionTypeState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        createDeductionType.fulfilled,
        (state: Draft<DeductionTypeState>, action: PayloadAction<DeductionType>) => {
          state.deductionTypes.unshift(action.payload);
          state.error = null;
          state.loading = false;
          message.success('Deduction type created successfully');
        },
      )
      .addCase(
        createDeductionType.rejected,
        (state: Draft<DeductionTypeState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateDeductionType.pending, (state: Draft<DeductionTypeState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        updateDeductionType.fulfilled,
        (state: Draft<DeductionTypeState>, action: PayloadAction<DeductionType>) => {
          const index = state.deductionTypes.findIndex((t) => t.id === action.payload.id);
          if (index !== -1) {
            state.deductionTypes[index] = action.payload;
          }
          state.loading = false;
          state.error = null;
          message.success('Deduction type updated successfully');
        },
      )
      .addCase(
        updateDeductionType.rejected,
        (state: Draft<DeductionTypeState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteDeductionType.pending, (state: Draft<DeductionTypeState>) => {
        state.loading = true;
      })
      .addCase(
        deleteDeductionType.fulfilled,
        (
          state: Draft<DeductionTypeState>,
          action: PayloadAction<DeleteDeductionTypePayload>,
        ) => {
          state.deductionTypes = state.deductionTypes.filter((t) => t.id !== action.payload.id);
          state.loading = false;
          message.success(action.payload.message);
        },
      )
      .addCase(deleteDeductionType.rejected, (state: Draft<DeductionTypeState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = 'Failed to delete deduction type. Please try again or contact support';
        message.error(Helpers.handleServerError(action.payload), 8);
      });
  },
});

export default DeductionTypesSlice;
export type { DeductionTypeState };
