import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { SmartAttribute } from '@/interface/Goal';
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 { SmartAttributeActions } from './actionTypes';

interface SmartAttributeState {
  smartAttributes: SmartAttribute[];
  currentSmartAttribute: SmartAttribute | null;
  loading: boolean;
  error: string | null;
}

const initialState: SmartAttributeState = {
  smartAttributes: [],
  currentSmartAttribute: null,
  loading: false,
  error: null,
};

export const fetchSmartAttributes = createAsyncThunk(
  SmartAttributeActions.FETCH_SMART_ATTRIBUTES_REQUEST,
  async (goalId: string) => {
    const response = (await apiGet(`/goals/${goalId}/smart-attributes`)) as AxiosResponse<{ data: SmartAttribute }>;
    return response.data.data;
  },
);

export const createSmartAttribute = createAsyncThunk(
  SmartAttributeActions.CREATE_SMART_ATTRIBUTE_REQUEST,
  async (payload: { goalId: string; data: Omit<SmartAttribute, 'id' | 'goal_id' | 'created_at' | 'updated_at'> }, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        `/goals/${payload.goalId}/smart-attributes`,
        payload.data,
      )) as AxiosResponse<{ data: SmartAttribute }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateSmartAttribute = createAsyncThunk(
  SmartAttributeActions.UPDATE_SMART_ATTRIBUTE_REQUEST,
  async (payload: Partial<SmartAttribute> & { id: string }, { rejectWithValue }) => {
    try {
      const response = (await apiPut(
        `/smart-attributes/${payload.id}`,
        payload,
      )) as AxiosResponse<{ data: SmartAttribute }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteSmartAttribute = createAsyncThunk(
  SmartAttributeActions.DELETE_SMART_ATTRIBUTE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(`/smart-attributes/${id}`)) as AxiosResponse<{ message: string }>;
      return { message: response.data.message, id };
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const SmartAttributeSlice = createSlice({
  name: 'smartAttributes',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchSmartAttributes.pending, (state: Draft<SmartAttributeState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchSmartAttributes.fulfilled,
        (state: Draft<SmartAttributeState>, action: PayloadAction<SmartAttribute>) => {
          state.currentSmartAttribute = action.payload;
          state.loading = false;
        },
      )
      .addCase(fetchSmartAttributes.rejected, (state: Draft<SmartAttributeState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createSmartAttribute.pending, (state: Draft<SmartAttributeState>) => {
        state.loading = true;
      })
      .addCase(
        createSmartAttribute.fulfilled,
        (state: Draft<SmartAttributeState>, action: PayloadAction<SmartAttribute>) => {
          state.currentSmartAttribute = action.payload;
          state.loading = false;
        },
      )
      .addCase(
        createSmartAttribute.rejected,
        (state: Draft<SmartAttributeState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateSmartAttribute.pending, (state: Draft<SmartAttributeState>) => {
        state.loading = true;
      })
      .addCase(
        updateSmartAttribute.fulfilled,
        (state: Draft<SmartAttributeState>, action: PayloadAction<SmartAttribute>) => {
          state.currentSmartAttribute = action.payload;
          state.loading = false;
          message.success('Successfully updated SMART attributes', 10);
        },
      )
      .addCase(
        updateSmartAttribute.rejected,
        (state: Draft<SmartAttributeState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteSmartAttribute.pending, (state: Draft<SmartAttributeState>) => {})
      .addCase(
        deleteSmartAttribute.fulfilled,
        (state: Draft<SmartAttributeState>, action: PayloadAction<{ message: string; id: string }>) => {
          state.currentSmartAttribute = null;
          message.success(action.payload.message, 10);
        },
      )
      .addCase(deleteSmartAttribute.rejected, (state: Draft<SmartAttributeState>, action: RejectedActionPayload) => {
        message.error(Helpers.handleServerError(action.payload), 8);
      });
  },
});

export default SmartAttributeSlice;
export type { SmartAttributeState };
