import { RejectedActionPayload, ServerErrorResponse } from '@/interface/Shared';
import { apiPost } 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 { AiQuestionsActions } from './actionTypes';

interface AiQuestion {
  question_text: string;
  type: string;
  points: number;
  explanation: string | null;
  category_id: string;
  level_id: string;
  options: { option_text: string; is_correct: boolean }[];
  matches: { left_text: string; right_text: string }[];
}

interface AiQuestionsState {
  generatedQuestions: AiQuestion[];
  generating: boolean;
  saving: boolean;
  error: string | null;
}

const initialState: AiQuestionsState = {
  generatedQuestions: [],
  generating: false,
  saving: false,
  error: null,
};

export const generateAiQuestions = createAsyncThunk(
  AiQuestionsActions.GENERATE_AI_QUESTIONS,
  async (
    payload: {
      content: string;
      count: number;
      types: string[];
      category_id: string;
      level_id: string;
    },
    { rejectWithValue },
  ) => {
    try {
      const response = (await apiPost(
        '/assessment/questions/generate-ai',
        payload,
      )) as AxiosResponse<{ data: { questions: AiQuestion[] }; message: string }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const saveAiGeneratedQuestions = createAsyncThunk(
  AiQuestionsActions.SAVE_AI_GENERATED,
  async (payload: { questions: AiQuestion[] }, { rejectWithValue }) => {
    try {
      const response = (await apiPost(
        '/assessment/questions/save-ai-generated',
        payload,
      )) as AxiosResponse<{ data: unknown[]; message: string }>;
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return rejectWithValue(error.response.data as ServerErrorResponse);
      }
      throw error;
    }
  },
);

export const AiQuestionsSlice = createSlice({
  name: 'assessmentAiQuestions',
  initialState,
  reducers: {
    clearGeneratedQuestions: (state: Draft<AiQuestionsState>) => {
      state.generatedQuestions = [];
      state.error = null;
    },
  },
  extraReducers(builder) {
    builder
      .addCase(generateAiQuestions.pending, (state: Draft<AiQuestionsState>) => {
        state.generating = true;
        state.error = null;
      })
      .addCase(
        generateAiQuestions.fulfilled,
        (state: Draft<AiQuestionsState>, action: PayloadAction<{ data: { questions: AiQuestion[] }; message: string }>) => {
          state.generating = false;
          state.generatedQuestions = action.payload.data.questions;
          message.success(action.payload.message);
        },
      )
      .addCase(
        generateAiQuestions.rejected,
        (state: Draft<AiQuestionsState>, action: RejectedActionPayload) => {
          state.generating = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      )

      .addCase(saveAiGeneratedQuestions.pending, (state: Draft<AiQuestionsState>) => {
        state.saving = true;
        state.error = null;
      })
      .addCase(
        saveAiGeneratedQuestions.fulfilled,
        (state: Draft<AiQuestionsState>, action: PayloadAction<{ data: unknown[]; message: string }>) => {
          state.saving = false;
          state.generatedQuestions = [];
          message.success(action.payload.message);
        },
      )
      .addCase(
        saveAiGeneratedQuestions.rejected,
        (state: Draft<AiQuestionsState>, action: RejectedActionPayload) => {
          state.saving = false;
          state.error = Helpers.handleServerError(action.payload);
          message.error(state.error, 10);
        },
      );
  },
});

export const { clearGeneratedQuestions } = AiQuestionsSlice.actions;
export default AiQuestionsSlice;
export type { AiQuestion };
