import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import {
  Course,
  CourseDetail,
  CreateCoursePayload,
  UpdateCoursePayload,
  DeleteCoursePayload,
} from '@/interface/Lms';
import { PaginationMeta } from '@/interface/Assessment';
import Helpers from '@/utilities/Helpers';
import { createAsyncThunk, createSlice, Draft, PayloadAction } from '@reduxjs/toolkit';
import { message } from 'antd';
import { CoursesActions } from './actionTypes';
import { apiDelete, apiGet, apiPost, apiPut } from '@/services/api/api';
import axios, { AxiosResponse } from 'axios';

interface CoursesState {
  courses: Course[];
  selectedCourse: CourseDetail | null;
  meta: PaginationMeta | null;
  loading: boolean;
  error: string | null;
}

const initialState: CoursesState = {
  courses: [],
  selectedCourse: null,
  meta: null,
  loading: false,
  error: null,
};

export const fetchCourses = createAsyncThunk(
  CoursesActions.FETCH_COURSES_REQUEST,
  async (params?: { status?: string; search?: string; page?: number }) => {
    const queryParams = new URLSearchParams();
    if (params?.status) queryParams.append('status', params.status);
    if (params?.search) queryParams.append('search', params.search);
    if (params?.page) queryParams.append('page', params.page.toString());
    const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
    const response = (await apiGet(`/lms/courses${query}`)) as AxiosResponse<{
      data: Course[];
      meta: PaginationMeta;
    }>;
    return response.data;
  },
);

export const fetchCourse = createAsyncThunk(
  CoursesActions.FETCH_COURSE_REQUEST,
  async (id: string) => {
    const response = (await apiGet(`/lms/courses/${id}`)) as AxiosResponse<CourseDetail>;
    return response.data;
  },
);

export const createCourse = createAsyncThunk(
  CoursesActions.CREATE_COURSE_REQUEST,
  async (payload: CreateCoursePayload, { rejectWithValue }) => {
    try {
      const response = (await apiPost('/lms/courses', payload)) as AxiosResponse<{
        data: CourseDetail;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const updateCourse = createAsyncThunk(
  CoursesActions.UPDATE_COURSE_REQUEST,
  async (payload: UpdateCoursePayload, { rejectWithValue }) => {
    try {
      const { id, ...data } = payload;
      const response = (await apiPut(`/lms/courses/${id}`, data)) as AxiosResponse<{
        data: CourseDetail;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const deleteCourse = createAsyncThunk(
  CoursesActions.DELETE_COURSE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiDelete(`/lms/courses/${id}`)) as AxiosResponse<DeleteCoursePayload>;
      const responseData = response.data;
      responseData.id = id;
      return responseData;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const publishCourse = createAsyncThunk(
  CoursesActions.PUBLISH_COURSE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiPost(`/lms/courses/${id}/publish`, {})) as AxiosResponse<{
        data: CourseDetail;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const archiveCourse = createAsyncThunk(
  CoursesActions.ARCHIVE_COURSE_REQUEST,
  async (id: string, { rejectWithValue }) => {
    try {
      const response = (await apiPost(`/lms/courses/${id}/archive`, {})) as AxiosResponse<{
        data: CourseDetail;
      }>;
      return response.data.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

interface GenerateQuizPayload {
  courseId: string;
  category_id: string;
  level_id: string;
  count?: number;
}

interface GenerateQuizResponse {
  quiz_id: string;
  quiz_name: string;
  questions_count: number;
}

export const generateQuizFromCourse = createAsyncThunk(
  CoursesActions.GENERATE_QUIZ_FROM_COURSE,
  async (payload: GenerateQuizPayload, { rejectWithValue }) => {
    try {
      const { courseId, ...data } = payload;
      const response = (await apiPost(
        `/lms/courses/${courseId}/generate-quiz`,
        data,
      )) as AxiosResponse<{ data: GenerateQuizResponse; message: string }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const CoursesSlice = createSlice({
  name: 'lmsCourses',
  initialState,
  reducers: {
    clearSelectedCourse: (state: Draft<CoursesState>) => {
      state.selectedCourse = null;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(fetchCourses.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchCourses.fulfilled,
        (
          state: Draft<CoursesState>,
          action: PayloadAction<{ data: Course[]; meta: PaginationMeta }>,
        ) => {
          state.courses = action.payload.data;
          state.meta = action.payload.meta;
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(fetchCourses.rejected, (state: Draft<CoursesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = 'Failed to load courses';
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(fetchCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        fetchCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<CourseDetail>) => {
          state.selectedCourse = action.payload;
          state.error = null;
          state.loading = false;
        },
      )
      .addCase(fetchCourse.rejected, (state: Draft<CoursesState>, action: RejectedActionPayload) => {
        state.loading = false;
        state.error = 'Failed to load course';
        message.error(Helpers.handleServerError(action.payload), 8);
      });

    builder
      .addCase(createCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        createCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<CourseDetail>) => {
          state.selectedCourse = action.payload;
          state.error = null;
          state.loading = false;
          message.success('Course created successfully');
        },
      )
      .addCase(
        createCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(updateCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        updateCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<CourseDetail>) => {
          state.selectedCourse = action.payload;
          const index = state.courses.findIndex((c) => c.id === action.payload.id);
          if (index !== -1) {
            state.courses[index] = {
              ...state.courses[index],
              title: action.payload.title,
              status: action.payload.status,
            };
          }
          state.loading = false;
          state.error = null;
          message.success('Course updated successfully');
        },
      )
      .addCase(
        updateCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(deleteCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        deleteCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<DeleteCoursePayload>) => {
          state.courses = state.courses.filter((c) => c.id !== action.payload.id);
          state.loading = false;
          message.success(action.payload.message);
        },
      )
      .addCase(
        deleteCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(publishCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        publishCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<CourseDetail>) => {
          state.selectedCourse = action.payload;
          const index = state.courses.findIndex((c) => c.id === action.payload.id);
          if (index !== -1) {
            state.courses[index] = {
              ...state.courses[index],
              status: action.payload.status,
            };
          }
          state.loading = false;
          state.error = null;
          message.success('Course published successfully');
        },
      )
      .addCase(
        publishCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(archiveCourse.pending, (state: Draft<CoursesState>) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        archiveCourse.fulfilled,
        (state: Draft<CoursesState>, action: PayloadAction<CourseDetail>) => {
          state.selectedCourse = action.payload;
          const index = state.courses.findIndex((c) => c.id === action.payload.id);
          if (index !== -1) {
            state.courses[index] = {
              ...state.courses[index],
              status: action.payload.status,
            };
          }
          state.loading = false;
          state.error = null;
          message.success('Course archived successfully');
        },
      )
      .addCase(
        archiveCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.loading = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );

    builder
      .addCase(generateQuizFromCourse.pending, (state: Draft<CoursesState>) => {
        state.error = null;
      })
      .addCase(
        generateQuizFromCourse.fulfilled,
        (
          state: Draft<CoursesState>,
          action: PayloadAction<{ data: GenerateQuizResponse; message: string }>,
        ) => {
          if (state.selectedCourse) {
            state.selectedCourse.linked_quiz = {
              id: action.payload.data.quiz_id,
              name: action.payload.data.quiz_name,
            };
          }
          state.error = null;
          message.success(action.payload.message);
        },
      )
      .addCase(
        generateQuizFromCourse.rejected,
        (state: Draft<CoursesState>, action: RejectedActionPayload) => {
          state.error = Helpers.handleServerError(action.payload);
          message.error(Helpers.handleServerError(action.payload), 10);
        },
      );
  },
});

export const { clearSelectedCourse } = CoursesSlice.actions;
export default CoursesSlice;
export type { CoursesState };
