import type { PayloadAction } from '@reduxjs/toolkit'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { processConversationData } from './conversationSlice.helper'
import type { Conversation, ConversationState } from '@/types/conversation'
import { fetchCreateConversation, fetchDeleteUserConversation, fetchQueryUserConversationPage } from '@/api/conversation'

const initialState: ConversationState = {
  conversations: [],
  currentConversationId: null,
  isLoading: false,
  error: null,
  shouldNavigateToNewConversation: false,
  shouldSendQuestion: '',
}

export const fetchConversations = createAsyncThunk(
  'conversation/fetchConversations',
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetchQueryUserConversationPage({
        keyword: '',
        pageNum: 0,
        pageSize: 100,
      })
      const processedData = processConversationData(response.data.records)
      return processedData
    }
    // eslint-disable-next-line unused-imports/no-unused-vars
    catch (error) {
      return rejectWithValue('Failed to fetch conversations')
    }
  },
)

export const deleteConversations = createAsyncThunk<
  boolean,
  string[],
  { rejectValue: boolean }
>(
  'conversation/deleteConversations',
  async (conversationIds, { dispatch, rejectWithValue }) => {
    try {
      // 调用删除会话的 API，传入 ID 集合
      await fetchDeleteUserConversation(conversationIds)

      // 删除成功后，重新获取会话列表
      await dispatch(fetchConversations())

      return true // 删除成功
    }
    catch (error) {
      console.error('Failed to delete conversations:', error)
      return rejectWithValue(false) // 删除失败
    }
  },
)

export const createConversation = createAsyncThunk<
  { conversation: Conversation, shouldNavigate: boolean, shouldSendQuestion: string },
  { conversationData: Partial<Conversation>, shouldNavigate: boolean, shouldSendQuestion: string },
  { state: { conversation: ConversationState } }
>(
  'conversation/createConversation',
  async ({ conversationData, shouldNavigate, shouldSendQuestion }, { dispatch }) => {
    const response = await fetchCreateConversation(conversationData)
    const newConversation = response.data

    dispatch(fetchConversations())

    return { conversation: newConversation, shouldNavigate, shouldSendQuestion }
  },
)

const conversationSlice = createSlice({
  name: 'conversation',
  initialState,
  reducers: {
    setCurrentConversation: (state, action: PayloadAction<string>) => {
      state.currentConversationId = action.payload
    },
    clearCurrentConversation: (state) => {
      state.currentConversationId = null
    },
    clearShouldSendQuestion: (state) => {
      state.shouldSendQuestion = ''
    },
    addConversation: (state, action: PayloadAction<Conversation>) => {
      state.conversations.unshift(action.payload)
    },
    clearNavigationFlag: (state) => {
      state.shouldNavigateToNewConversation = false
    },
    removeConversation: (state, action: PayloadAction<string>) => {
      state.conversations = state.conversations.filter(conv => conv.conversationId !== action.payload)
      if (state.currentConversationId === action.payload) {
        state.currentConversationId = state.conversations[0]?.conversationId || null
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchConversations.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(fetchConversations.fulfilled, (state, action) => {
        state.isLoading = false
        state.conversations = action.payload
      })
      .addCase(fetchConversations.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.payload as string
      })
      .addCase(createConversation.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(createConversation.fulfilled, (state, action) => {
        state.isLoading = false
        state.currentConversationId = action.payload.conversation.conversationId
        state.shouldNavigateToNewConversation = action.payload.shouldNavigate
        state.shouldSendQuestion = action.payload.shouldSendQuestion
      })
      .addCase(createConversation.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message || 'Failed to create conversation'
      })
      .addCase(deleteConversations.fulfilled, () => {
      })
      .addCase(deleteConversations.rejected, () => {
      })
  },
})

export const { setCurrentConversation, clearCurrentConversation, clearNavigationFlag, clearShouldSendQuestion } = conversationSlice.actions

export default conversationSlice.reducer
