import {
  DeleteGuarantorPayload,
  DeleteGuarantorResponse,
  Guarantor,
  UpdateGuarantorPayload,
} from '@/interface/Guarantor';
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 { GuarantorActions } from './actionTypes';

interface GuarantorState {
  guarantors: Guarantor[];
  loading: boolean;
  deleting: boolean;
  error: string | null;
}

const initialState: GuarantorState = {
  guarantors: [],
  loading: false,
  deleting: false,
  error: null,
};

export const fetchGuarantors = createAsyncThunk(
  GuarantorActions.FETCH_GUARANTORS_REQUEST,
  async (payload: string) => {
    const response = (await apiGet(`/hr/employees/${payload}/guarantors`)) as AxiosResponse<
      Guarantor[]
    >;
    return response.data;
  },
);

export const createGuarantor = createAsyncThunk(
  GuarantorActions.CREATE_GUARANTOR_REQUEST,
  async (
    payload: { employee_id: string } & Record<string, any>,
    { rejectWithValue },
  ) => {
    try {
      const response = (await apiPost(
        `/hr/employees/${payload.employee_id}/guarantors`,
        payload,
      )) as AxiosResponse<Guarantor>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateGuarantor = createAsyncThunk(
  GuarantorActions.UPDATE_GUARANTOR_REQUEST,
  async (payload: UpdateGuarantorPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPut(
        `/hr/employees/${payload.employee_id}/guarantors/${payload.id}`,
        payload,
      )) as AxiosResponse<Guarantor>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteGuarantor = createAsyncThunk(
  GuarantorActions.DELETE_GUARANTOR_REQUEST,
  async (payload: DeleteGuarantorPayload) => {
    const response = (await apiDelete(
      `/hr/employees/${payload.employee_id}/guarantors/${payload.guarantor_id}`,
    )) as AxiosResponse<DeleteGuarantorResponse>;
    const responseData = response.data;
    responseData.id = payload.guarantor_id;
    return responseData;
  },
);

export const GuarantorSlice = createSlice({
  name: 'guarantors',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchGuarantors.pending, (state: Draft<GuarantorState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchGuarantors.fulfilled,
        (state: Draft<GuarantorState>, action: PayloadAction<Guarantor[]>) => {
          state.loading = false;
          state.error = null;
          state.guarantors = action.payload;
        },
      )
      .addCase(fetchGuarantors.rejected, (state: Draft<GuarantorState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createGuarantor.pending, (state: Draft<GuarantorState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        createGuarantor.fulfilled,
        (state: Draft<GuarantorState>, action: PayloadAction<Guarantor>) => {
          state.loading = false;
          state.error = null;
          state.guarantors.unshift(action.payload);
        },
      )
      .addCase(
        createGuarantor.rejected,
        (state: Draft<GuarantorState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateGuarantor.pending, (state: Draft<GuarantorState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        updateGuarantor.fulfilled,
        (state: Draft<GuarantorState>, action: PayloadAction<Guarantor>) => {
          state.loading = false;
          state.error = null;
          const index = state.guarantors.findIndex((item) => item.id === action.payload.id);
          if (index > -1) {
            state.guarantors[index] = action.payload;
          }
          message.success('Successfully updated Guarantor', 8);
        },
      )
      .addCase(
        updateGuarantor.rejected,
        (state: Draft<GuarantorState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteGuarantor.pending, (state: Draft<GuarantorState>) => {
        state.deleting = true;
        state.error = null;
      })
      .addCase(
        deleteGuarantor.fulfilled,
        (state: Draft<GuarantorState>, action: PayloadAction<DeleteGuarantorResponse>) => {
          state.deleting = false;
          state.error = null;
          state.guarantors = state.guarantors.filter((item) => item.id !== action.payload.id);
          message.success(action.payload.message, 10);
        },
      )
      .addCase(deleteGuarantor.rejected, (state: Draft<GuarantorState>, action: RejectedActionPayload) => {
        state.deleting = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });
  },
});

export default GuarantorSlice;
export type { GuarantorState };
