import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { GoalUpdate, GoalUpdateResponse, PaginatedGoalUpdates } 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 { GoalUpdateActions } from './actionTypes';
import { PaginationLinks, PaginationMeta } from '@/interface/Paginated';
import { GetParams, toQueryString } from '@/interface/GetParams';

interface GoalUpdateState {
  goalUpdates: GoalUpdate[];
  links?: PaginationLinks;
  meta?: PaginationMeta;
  loading: boolean;
  error: string | null;
}

const initialState: GoalUpdateState = {
  goalUpdates: [],
  loading: false,
  error: null,
};

export const fetchGoalUpdates = createAsyncThunk(
  GoalUpdateActions.FETCH_GOAL_UPDATES_REQUEST,
  async ({ goalId, ...params }: { goalId: string } & GetParams) => {
    const query = toQueryString(params);
    const response = (await apiGet(`/goals/${goalId}/updates${query}`)) as AxiosResponse<PaginatedGoalUpdates>;
    return response.data;
  },
);

export const createGoalUpdate = createAsyncThunk(
  GoalUpdateActions.CREATE_GOAL_UPDATE_REQUEST,
  async (payload: { goalId: string; data: Record<string, unknown> }, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        `/goals/${payload.goalId}/submit-update`,
        payload.data,
      )) as AxiosResponse<GoalUpdateResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateGoalUpdate = createAsyncThunk(
  GoalUpdateActions.UPDATE_GOAL_UPDATE_REQUEST,
  async (payload: { id: string; data: Record<string, unknown> }, { rejectWithValue }) => {
    try {
      const response = (await apiPut(
        `/goal-updates/${payload.id}`,
        payload.data,
      )) as AxiosResponse<GoalUpdateResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteGoalUpdate = createAsyncThunk(
  GoalUpdateActions.DELETE_GOAL_UPDATE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(`/goal-updates/${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 GoalUpdateSlice = createSlice({
  name: 'goalUpdates',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchGoalUpdates.pending, (state: Draft<GoalUpdateState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchGoalUpdates.fulfilled,
        (state: Draft<GoalUpdateState>, action: PayloadAction<PaginatedGoalUpdates>) => {
          state.goalUpdates = action.payload.data;
          state.meta = action.payload.meta;
          state.links = action.payload.links;
          state.loading = false;
        },
      )
      .addCase(fetchGoalUpdates.rejected, (state: Draft<GoalUpdateState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createGoalUpdate.pending, (state: Draft<GoalUpdateState>) => {
        state.loading = true;
      })
      .addCase(
        createGoalUpdate.fulfilled,
        (state: Draft<GoalUpdateState>, action: PayloadAction<GoalUpdate>) => {
          state.goalUpdates.unshift(action.payload);
          state.loading = false;
        },
      )
      .addCase(
        createGoalUpdate.rejected,
        (state: Draft<GoalUpdateState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateGoalUpdate.pending, (state: Draft<GoalUpdateState>) => {
        state.loading = true;
      })
      .addCase(
        updateGoalUpdate.fulfilled,
        (state: Draft<GoalUpdateState>, action: PayloadAction<GoalUpdate>) => {
          const idx = state.goalUpdates.findIndex((u) => u.id === action.payload.id);
          if (idx !== -1) {
            state.goalUpdates[idx] = action.payload;
          }
          state.loading = false;
          message.success('Successfully updated goal update', 10);
        },
      )
      .addCase(
        updateGoalUpdate.rejected,
        (state: Draft<GoalUpdateState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteGoalUpdate.pending, (state: Draft<GoalUpdateState>) => {})
      .addCase(
        deleteGoalUpdate.fulfilled,
        (state: Draft<GoalUpdateState>, action: PayloadAction<{ message: string; id: string }>) => {
          state.goalUpdates = state.goalUpdates.filter((item) => item.id !== action.payload.id);
          message.success(action.payload.message, 10);
        },
      )
      .addCase(deleteGoalUpdate.rejected, (state: Draft<GoalUpdateState>, action: RejectedActionPayload) => {
        message.error(Helpers.handleServerError(action.payload), 8);
      });
  },
});

export default GoalUpdateSlice;
export type { GoalUpdateState };
