import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  CoachingFeedback,
  CoachingFeedbackResponse,
  PaginatedCoachingFeedbacks,
  CreateCoachingFeedbackPayload,
  UpdateCoachingFeedbackPayload,
} from '@/interface/CoachingFeedback';
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 { CoachingFeedbackActions } from './actionTypes';
import { PaginationLinks, PaginationMeta } from '@/interface/Paginated';
import { GetParams, toQueryString } from '@/interface/GetParams';

interface CoachingFeedbackState {
  coachingFeedbacks: CoachingFeedback[];
  currentCoachingFeedback: CoachingFeedback | null;
  links?: PaginationLinks;
  meta?: PaginationMeta;
  loading: boolean;
  error: string | null;
}

const initialState: CoachingFeedbackState = {
  coachingFeedbacks: [],
  currentCoachingFeedback: null,
  loading: false,
  error: null,
};

export const fetchCoachingFeedbacks = createAsyncThunk(
  CoachingFeedbackActions.FETCH_COACHING_FEEDBACKS_REQUEST,
  async (params?: GetParams) => {
    const query = toQueryString(params);
    const response = (await apiGet(`/coaching-feedbacks${query}`)) as AxiosResponse<PaginatedCoachingFeedbacks>;
    return response.data;
  },
);

export const fetchCoachingFeedback = createAsyncThunk(
  CoachingFeedbackActions.FETCH_COACHING_FEEDBACK_REQUEST,
  async (id: string) => {
    const response = (await apiGet(`/coaching-feedbacks/${id}`)) as AxiosResponse<CoachingFeedbackResponse>;
    return response.data.data;
  },
);

export const createCoachingFeedback = createAsyncThunk(
  CoachingFeedbackActions.CREATE_COACHING_FEEDBACK_REQUEST,
  async (payload: CreateCoachingFeedbackPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost('/coaching-feedbacks', payload)) as AxiosResponse<CoachingFeedbackResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateCoachingFeedback = createAsyncThunk(
  CoachingFeedbackActions.UPDATE_COACHING_FEEDBACK_REQUEST,
  async (payload: UpdateCoachingFeedbackPayload & { id: string }, { rejectWithValue }) => {
    try {
      const response = (await apiPut(`/coaching-feedbacks/${payload.id}`, payload)) as AxiosResponse<CoachingFeedbackResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteCoachingFeedback = createAsyncThunk(
  CoachingFeedbackActions.DELETE_COACHING_FEEDBACK_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(`/coaching-feedbacks/${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 CoachingFeedbackSlice = createSlice({
  name: 'coachingFeedbacks',
  initialState,
  reducers: {
    clearCurrentCoachingFeedback: (state: Draft<CoachingFeedbackState>) => {
      state.currentCoachingFeedback = null;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchCoachingFeedbacks.pending, (state: Draft<CoachingFeedbackState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchCoachingFeedbacks.fulfilled,
        (state: Draft<CoachingFeedbackState>, action: PayloadAction<PaginatedCoachingFeedbacks>) => {
          state.coachingFeedbacks = action.payload.data;
          state.meta = action.payload.meta;
          state.links = action.payload.links;
          state.loading = false;
        },
      )
      .addCase(fetchCoachingFeedbacks.rejected, (state: Draft<CoachingFeedbackState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(fetchCoachingFeedback.pending, (state: Draft<CoachingFeedbackState>) => {
        state.loading = true;
      })
      .addCase(
        fetchCoachingFeedback.fulfilled,
        (state: Draft<CoachingFeedbackState>, action: PayloadAction<CoachingFeedback>) => {
          state.currentCoachingFeedback = action.payload;
          state.loading = false;
        },
      )
      .addCase(fetchCoachingFeedback.rejected, (state: Draft<CoachingFeedbackState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createCoachingFeedback.pending, (state: Draft<CoachingFeedbackState>) => {
        state.loading = true;
      })
      .addCase(
        createCoachingFeedback.fulfilled,
        (state: Draft<CoachingFeedbackState>, action: PayloadAction<CoachingFeedback>) => {
          state.coachingFeedbacks.unshift(action.payload);
          state.loading = false;
        },
      )
      .addCase(
        createCoachingFeedback.rejected,
        (state: Draft<CoachingFeedbackState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateCoachingFeedback.pending, (state: Draft<CoachingFeedbackState>) => {
        state.loading = true;
      })
      .addCase(
        updateCoachingFeedback.fulfilled,
        (state: Draft<CoachingFeedbackState>) => {
          state.loading = false;
          message.success('Coaching session updated successfully', 10);
        },
      )
      .addCase(
        updateCoachingFeedback.rejected,
        (state: Draft<CoachingFeedbackState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

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

export const { clearCurrentCoachingFeedback } = CoachingFeedbackSlice.actions;
export default CoachingFeedbackSlice;
export type { CoachingFeedbackState };
