import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { TalentMatch } from '@/interface/Recruitment';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import axios, { AxiosResponse } from 'axios';
import { apiGet, apiPost } from '@/services/api/api';
import { TalentPoolActions } from './actionTypes';

interface TalentPoolState {
  silverMedalists: TalentMatch[];
  loading: boolean;
  reEngaging: boolean;
}

const initialState: TalentPoolState = {
  silverMedalists: [],
  loading: false,
  reEngaging: false,
};

export const fetchSilverMedalists = createAsyncThunk(
  TalentPoolActions.FETCH_SILVER_MEDALISTS,
  async (jobOpeningId: string, { rejectWithValue }) => {
    try {
      const response = (await apiGet(
        `/recruitment/job-openings/${jobOpeningId}/silver-medalists`,
      )) as AxiosResponse<{ data: TalentMatch[] }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const reEngageCandidate = createAsyncThunk(
  TalentPoolActions.RE_ENGAGE_CANDIDATE,
  async (
    {
      applicantId,
      jobOpeningId,
      message: msg,
    }: { applicantId: string; jobOpeningId: string; message?: string },
    { rejectWithValue },
  ) => {
    try {
      const response = (await apiPost(`/recruitment/applicants/${applicantId}/re-engage`, {
        job_opening_id: jobOpeningId,
        message: msg,
      })) as AxiosResponse<{ data: any }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const TalentPoolSlice = createSlice({
  name: 'talentPool',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchSilverMedalists.pending, (state: Draft<TalentPoolState>) => {
        state.loading = true;
      })
      .addCase(
        fetchSilverMedalists.fulfilled,
        (state: Draft<TalentPoolState>, action: PayloadAction<{ data: TalentMatch[] }>) => {
          state.silverMedalists = action.payload.data;
          state.loading = false;
        },
      )
      .addCase(
        fetchSilverMedalists.rejected,
        (state: Draft<TalentPoolState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(reEngageCandidate.pending, (state: Draft<TalentPoolState>) => {
        state.reEngaging = true;
      })
      .addCase(reEngageCandidate.fulfilled, (state: Draft<TalentPoolState>) => {
        state.reEngaging = false;
      })
      .addCase(
        reEngageCandidate.rejected,
        (state: Draft<TalentPoolState>, action: RejectedActionPayload) => {
          state.reEngaging = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );
  },
});

export default TalentPoolSlice;
export type { TalentPoolState };
