import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  AppraisalRating,
  AppraisalRatingResponse,
  CreateAppraisalRatingPayload,
  DeleteAppraisalRatingPayload,
  PaginatedAppraisalRatings,
} from '@/interface/AppraisalRating';
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 { AppraisalRatingActions } from './actionTypes';
import { PaginationLinks, PaginationMeta } from '@/interface/Paginated';

interface AppraisalRatingState {
  appraisalRatings: AppraisalRating[];
  links?: PaginationLinks;
  meta?: PaginationMeta;
  loading: boolean;
  error: string | null;
}

const initialState: AppraisalRatingState = {
  appraisalRatings: [],
  loading: false,
  error: null,
};

export const fetchAppraisalRatings = createAsyncThunk(
  AppraisalRatingActions.FETCH_APPRAISAL_RATINGS_REQUEST,
  async () => {
    const response = (await apiGet('/appraisal-ratings')) as AxiosResponse<PaginatedAppraisalRatings>;
    return response.data;
  },
);

export const createAppraisalRating = createAsyncThunk(
  AppraisalRatingActions.CREATE_APPRAISAL_RATING_REQUEST,
  async (payload: CreateAppraisalRatingPayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/appraisal-ratings',
        payload,
      )) as AxiosResponse<AppraisalRatingResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateAppraisalRating = createAsyncThunk(
  AppraisalRatingActions.UPDATE_APPRAISAL_RATING_REQUEST,
  async (payload: CreateAppraisalRatingPayload & { id: string }, { rejectWithValue }) => {
    try {
      const response = (await apiPut(
        `/appraisal-ratings/${payload.id}`,
        payload,
      )) as AxiosResponse<AppraisalRatingResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteAppraisalRating = createAsyncThunk(
  AppraisalRatingActions.DELETE_APPRAISAL_RATING_REQUEST,
  async (payload: string) => {
    const response = (await apiDelete(
      `/appraisal-ratings/${payload}`,
    )) as AxiosResponse<DeleteAppraisalRatingPayload>;
    const responseData = response.data;
    responseData.id = payload;
    return responseData;
  },
);

export const AppraisalRatingSlice = createSlice({
  name: 'appraisalRatings',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(fetchAppraisalRatings.pending, (state: Draft<AppraisalRatingState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchAppraisalRatings.fulfilled,
        (state: Draft<AppraisalRatingState>, action: PayloadAction<AppraisalRating[] | PaginatedAppraisalRatings>) => {
          if (Array.isArray(action.payload)) {
            state.appraisalRatings = action.payload;
            state.meta = undefined;
            state.links = undefined;
          } else {
            state.appraisalRatings = action.payload.data;
            state.meta = action.payload.meta;
            state.links = action.payload.links;
          }
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(fetchAppraisalRatings.rejected, (state: Draft<AppraisalRatingState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createAppraisalRating.pending, (state: Draft<AppraisalRatingState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        createAppraisalRating.fulfilled,
        (state: Draft<AppraisalRatingState>, action: PayloadAction<AppraisalRating>) => {
          state.appraisalRatings.unshift(action.payload);
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(
        createAppraisalRating.rejected,
        (state: Draft<AppraisalRatingState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateAppraisalRating.pending, (state: Draft<AppraisalRatingState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        updateAppraisalRating.fulfilled,
        (state: Draft<AppraisalRatingState>, action: PayloadAction<AppraisalRating>) => {
          state.loading = false;
          state.error = null;
          message.success('Successfully updated Appraisal Rating', 10);
        },
      )
      .addCase(
        updateAppraisalRating.rejected,
        (state: Draft<AppraisalRatingState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

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

export default AppraisalRatingSlice;
export type { AppraisalRatingState };
