import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  PerformanceNote,
  PerformanceNoteResponse,
  PaginatedPerformanceNotes,
  CreatePerformanceNotePayload,
  UpdatePerformanceNotePayload,
} from '@/interface/PerformanceNote';
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 { PerformanceNoteActions } from './actionTypes';
import { PaginationLinks, PaginationMeta } from '@/interface/Paginated';
import { GetParams, toQueryString } from '@/interface/GetParams';

interface PerformanceNoteState {
  performanceNotes: PerformanceNote[];
  currentPerformanceNote: PerformanceNote | null;
  links?: PaginationLinks;
  meta?: PaginationMeta;
  loading: boolean;
  error: string | null;
}

const initialState: PerformanceNoteState = {
  performanceNotes: [],
  currentPerformanceNote: null,
  loading: false,
  error: null,
};

export const fetchPerformanceNotes = createAsyncThunk(
  PerformanceNoteActions.FETCH_PERFORMANCE_NOTES_REQUEST,
  async (params?: GetParams) => {
    const query = toQueryString(params);
    const response = (await apiGet(`/performance-notes${query}`)) as AxiosResponse<PaginatedPerformanceNotes>;
    return response.data;
  },
);

export const fetchPerformanceNote = createAsyncThunk(
  PerformanceNoteActions.FETCH_PERFORMANCE_NOTE_REQUEST,
  async (id: string) => {
    const response = (await apiGet(`/performance-notes/${id}`)) as AxiosResponse<PerformanceNoteResponse>;
    return response.data.data;
  },
);

export const createPerformanceNote = createAsyncThunk(
  PerformanceNoteActions.CREATE_PERFORMANCE_NOTE_REQUEST,
  async (payload: CreatePerformanceNotePayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost('/performance-notes', payload)) as AxiosResponse<PerformanceNoteResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updatePerformanceNote = createAsyncThunk(
  PerformanceNoteActions.UPDATE_PERFORMANCE_NOTE_REQUEST,
  async (payload: UpdatePerformanceNotePayload & { id: string }, { rejectWithValue }) => {
    try {
      const response = (await apiPut(`/performance-notes/${payload.id}`, payload)) as AxiosResponse<PerformanceNoteResponse>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deletePerformanceNote = createAsyncThunk(
  PerformanceNoteActions.DELETE_PERFORMANCE_NOTE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(`/performance-notes/${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 PerformanceNoteSlice = createSlice({
  name: 'performanceNotes',
  initialState,
  reducers: {
    clearCurrentPerformanceNote: (state: Draft<PerformanceNoteState>) => {
      state.currentPerformanceNote = null;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchPerformanceNotes.pending, (state: Draft<PerformanceNoteState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchPerformanceNotes.fulfilled,
        (state: Draft<PerformanceNoteState>, action: PayloadAction<PaginatedPerformanceNotes>) => {
          state.performanceNotes = action.payload.data;
          state.meta = action.payload.meta;
          state.links = action.payload.links;
          state.loading = false;
        },
      )
      .addCase(fetchPerformanceNotes.rejected, (state: Draft<PerformanceNoteState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(fetchPerformanceNote.pending, (state: Draft<PerformanceNoteState>) => {
        state.loading = true;
      })
      .addCase(
        fetchPerformanceNote.fulfilled,
        (state: Draft<PerformanceNoteState>, action: PayloadAction<PerformanceNote>) => {
          state.currentPerformanceNote = action.payload;
          state.loading = false;
        },
      )
      .addCase(fetchPerformanceNote.rejected, (state: Draft<PerformanceNoteState>, action: RejectedActionPayload) => {
        state.loading = false;
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createPerformanceNote.pending, (state: Draft<PerformanceNoteState>) => {
        state.loading = true;
      })
      .addCase(
        createPerformanceNote.fulfilled,
        (state: Draft<PerformanceNoteState>, action: PayloadAction<PerformanceNote>) => {
          state.performanceNotes.unshift(action.payload);
          state.loading = false;
        },
      )
      .addCase(
        createPerformanceNote.rejected,
        (state: Draft<PerformanceNoteState>, action: RejectedActionPayload) => {
          state.loading = false;
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

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

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

export const { clearCurrentPerformanceNote } = PerformanceNoteSlice.actions;
export default PerformanceNoteSlice;
export type { PerformanceNoteState };
