import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { ContractType } 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 { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import { ContractTypesActions } from './actionTypes';

interface ContractTypesState {
  contractTypes: ContractType[];
  activeContractTypes: ContractType[];
  loading: boolean;
  actionLoading: boolean;
  error: string | null;
}

const initialState: ContractTypesState = {
  contractTypes: [],
  activeContractTypes: [],
  loading: false,
  actionLoading: false,
  error: null,
};

export const fetchContractTypes = createAsyncThunk(
  ContractTypesActions.FETCH_CONTRACT_TYPES,
  async (_: void, { rejectWithValue }) => {
    try {
      const response = (await apiGet('/recruitment/contract-types')) as AxiosResponse<{
        data: ContractType[];
      }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const fetchActiveContractTypes = createAsyncThunk(
  ContractTypesActions.FETCH_ACTIVE_CONTRACT_TYPES,
  async (_: void, { rejectWithValue }) => {
    try {
      const response = (await apiGet('/recruitment/contract-types/active')) as AxiosResponse<{
        data: ContractType[];
      }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const createContractType = createAsyncThunk(
  ContractTypesActions.CREATE_CONTRACT_TYPE,
  async (payload: any, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/recruitment/contract-types',
        payload,
      )) as AxiosResponse<{ data: ContractType }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateContractType = createAsyncThunk(
  ContractTypesActions.UPDATE_CONTRACT_TYPE,
  async ({ id, ...rest }: { id: string } & any, { rejectWithValue }) => {
    try {
      const response = (await apiPut(
        `/recruitment/contract-types/${id}`,
        rest,
      )) as AxiosResponse<{ data: ContractType }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteContractType = createAsyncThunk(
  ContractTypesActions.DELETE_CONTRACT_TYPE,
  async (id: string, { rejectWithValue }) => {
    try {
      await apiDelete(`/recruitment/contract-types/${id}`);
      return id;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const ContractTypesSlice = createSlice({
  name: 'contractTypes',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchContractTypes.pending, (state: Draft<ContractTypesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchContractTypes.fulfilled,
        (state: Draft<ContractTypesState>, action: PayloadAction<{ data: ContractType[] }>) => {
          state.contractTypes = action.payload.data;
          state.loading = false;
          state.error = null;
        },
      )
      .addCase(
        fetchContractTypes.rejected,
        (state: Draft<ContractTypesState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(fetchActiveContractTypes.pending, (state: Draft<ContractTypesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchActiveContractTypes.fulfilled,
        (state: Draft<ContractTypesState>, action: PayloadAction<{ data: ContractType[] }>) => {
          state.activeContractTypes = action.payload.data;
          state.loading = false;
          state.error = null;
        },
      )
      .addCase(fetchActiveContractTypes.rejected, (state: Draft<ContractTypesState>) => {
        state.loading = false;
      });

    builder
      .addCase(createContractType.pending, (state: Draft<ContractTypesState>) => {
        state.actionLoading = true;
        state.error = null;
      })
      .addCase(
        createContractType.fulfilled,
        (state: Draft<ContractTypesState>, action: PayloadAction<{ data: ContractType }>) => {
          state.contractTypes.unshift(action.payload.data);
          state.actionLoading = false;
          state.error = null;
        },
      )
      .addCase(
        createContractType.rejected,
        (state: Draft<ContractTypesState>, action: RejectedActionPayload) => {
          state.actionLoading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateContractType.pending, (state: Draft<ContractTypesState>) => {
        state.actionLoading = true;
        state.error = null;
      })
      .addCase(
        updateContractType.fulfilled,
        (state: Draft<ContractTypesState>, action: PayloadAction<{ data: ContractType }>) => {
          const updated = action.payload.data;
          const index = state.contractTypes.findIndex((c) => c.id === updated.id);
          if (index !== -1) {
            state.contractTypes[index] = updated;
          }
          const activeIndex = state.activeContractTypes.findIndex((c) => c.id === updated.id);
          if (activeIndex !== -1) {
            state.activeContractTypes[activeIndex] = updated;
          }
          state.actionLoading = false;
          state.error = null;
        },
      )
      .addCase(
        updateContractType.rejected,
        (state: Draft<ContractTypesState>, action: RejectedActionPayload) => {
          state.actionLoading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteContractType.pending, (state: Draft<ContractTypesState>) => {
        state.actionLoading = true;
        state.error = null;
      })
      .addCase(
        deleteContractType.fulfilled,
        (state: Draft<ContractTypesState>, action: PayloadAction<string>) => {
          state.contractTypes = state.contractTypes.filter((c) => c.id !== action.payload);
          state.activeContractTypes = state.activeContractTypes.filter(
            (c) => c.id !== action.payload,
          );
          state.actionLoading = false;
          state.error = null;
        },
      )
      .addCase(
        deleteContractType.rejected,
        (state: Draft<ContractTypesState>, action: RejectedActionPayload) => {
          state.actionLoading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );
  },
});

export default ContractTypesSlice;
export type { ContractTypesState };
