import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  CreateStatutoryConfigurationPayload,
  StatutoryConfiguration,
  DeleteStatutoryConfigurationPayload,
  UpdateStatutoryConfigurationPayload,
} from '@/interface/StatutoryConfiguration';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import { StatutoryConfigurationsActions } from './actionTypes';
import { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import axios, { AxiosResponse } from 'axios';

interface StatutoryConfigurationState {
  statutoryConfigurations: StatutoryConfiguration[];
  loading: boolean;
  error: string | null;
}

const initialState: StatutoryConfigurationState = {
  statutoryConfigurations: [],
  loading: false,
  error: null,
};

export const fetchStatutoryConfigurations = createAsyncThunk(
  StatutoryConfigurationsActions.FETCH_STATUTORY_CONFIGURATIONS_REQUEST,
  async (params?: { country_code?: string; active?: boolean; type?: string }) => {
    const queryParams = new URLSearchParams();
    if (params?.country_code) queryParams.append('country_code', params.country_code);
    if (params?.active !== undefined) queryParams.append('active', String(params.active));
    if (params?.type) queryParams.append('type', params.type);
    const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
    const response = (await apiGet(
      `/payroll/statutory-configurations${query}`,
    )) as AxiosResponse<StatutoryConfiguration[]>;
    return response.data;
  },
);

export const createStatutoryConfiguration = createAsyncThunk(
  StatutoryConfigurationsActions.CREATE_STATUTORY_CONFIGURATION_REQUEST,
  async (payload: CreateStatutoryConfigurationPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/payroll/statutory-configurations',
        payload,
      )) as AxiosResponse<{ data: StatutoryConfiguration }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateStatutoryConfiguration = createAsyncThunk(
  StatutoryConfigurationsActions.UPDATE_STATUTORY_CONFIGURATION_REQUEST,
  async (payload: UpdateStatutoryConfigurationPayload, { rejectWithValue }) => {
    try {
      const { id, ...data } = payload;
      const response = (await apiPut(
        `/payroll/statutory-configurations/${id}`,
        data,
      )) as AxiosResponse<{ data: StatutoryConfiguration }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteStatutoryConfiguration = createAsyncThunk(
  StatutoryConfigurationsActions.DELETE_STATUTORY_CONFIGURATION_REQUEST,
  async (id: string) => {
    const response = (await apiDelete(
      `/payroll/statutory-configurations/${id}`,
    )) as AxiosResponse<DeleteStatutoryConfigurationPayload>;
    const responseData = response.data;
    responseData.id = id;
    return responseData;
  },
);

export const StatutoryConfigurationsSlice = createSlice({
  name: 'statutoryConfigurations',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(
        fetchStatutoryConfigurations.pending,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        fetchStatutoryConfigurations.fulfilled,
        (
          state: Draft<StatutoryConfigurationState>,
          action: PayloadAction<StatutoryConfiguration[]>,
        ) => {
          state.statutoryConfigurations = action.payload;
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(
        fetchStatutoryConfigurations.rejected,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = false;
          state.error =
            'Failed to load statutory configurations. Please try again or contact support';
          message.error(
            'Failed to load statutory configurations. Please try again or contact support',
          );
        },
      );

    builder
      .addCase(
        createStatutoryConfiguration.pending,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        createStatutoryConfiguration.fulfilled,
        (
          state: Draft<StatutoryConfigurationState>,
          action: PayloadAction<StatutoryConfiguration>,
        ) => {
          state.statutoryConfigurations.unshift(action.payload);
          state.error = null;
          state.loading = false;
          message.success('Statutory configuration created successfully');
        },
      )
      .addCase(
        createStatutoryConfiguration.rejected,
        (state: Draft<StatutoryConfigurationState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        updateStatutoryConfiguration.pending,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = true;
          state.error = null;
        },
      )
      .addCase(
        updateStatutoryConfiguration.fulfilled,
        (
          state: Draft<StatutoryConfigurationState>,
          action: PayloadAction<StatutoryConfiguration>,
        ) => {
          const index = state.statutoryConfigurations.findIndex(
            (t) => t.id === action.payload.id,
          );
          if (index !== -1) {
            state.statutoryConfigurations[index] = action.payload;
          }
          state.loading = false;
          state.error = null;
          message.success('Statutory configuration updated successfully');
        },
      )
      .addCase(
        updateStatutoryConfiguration.rejected,
        (state: Draft<StatutoryConfigurationState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(
        deleteStatutoryConfiguration.pending,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = true;
        },
      )
      .addCase(
        deleteStatutoryConfiguration.fulfilled,
        (
          state: Draft<StatutoryConfigurationState>,
          action: PayloadAction<DeleteStatutoryConfigurationPayload>,
        ) => {
          state.statutoryConfigurations = state.statutoryConfigurations.filter(
            (t) => t.id !== action.payload.id,
          );
          state.loading = false;
          message.success(action.payload.message);
        },
      )
      .addCase(
        deleteStatutoryConfiguration.rejected,
        (state: Draft<StatutoryConfigurationState>) => {
          state.loading = false;
          state.error =
            'Failed to delete statutory configuration. Please try again or contact support';
          message.error(
            'Failed to delete statutory configuration. Please try again or contact support',
          );
        },
      );
  },
});

export default StatutoryConfigurationsSlice;
export type { StatutoryConfigurationState };
