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'
import { waitForToken } from '@/lib/utils'

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

export const fetchConversations = createAsyncThunk(
  'conversation/fetchConversations',
  async (_, { rejectWithValue }) => {
    try {
      await waitForToken()
      // 调用真实接口获取会话列表
      const response = await fetchQueryUserConversationPage({
        pageNum: 1,
        pageSize: 100,
      })
      const records = response.data?.records || []
      return processConversationData(records)
    }
    // 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 {
      await waitForToken()
      // 调用删除会话的 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 }) => {
    await waitForToken()
    // 从缓存中获取 toolId 作为 busiId
    const cachedToolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
    const busiId = cachedToolId || ''
    // 排除 toolId 字段，只传递 busiId 和 busiType
    const { toolId, ...restConversationData } = conversationData
    const requestPayload = {
      ...restConversationData,
      busiId,
      busiType: '01',
    }
    const response = await fetchCreateConversation(requestPayload)
    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 = ''
    },
    setShouldSendQuestion: (state, action: PayloadAction<string>) => {
      state.shouldSendQuestion = action.payload
    },
    addConversation: (state, action: PayloadAction<Conversation>) => {
      state.conversations.unshift(action.payload)
    },
    clearNavigationFlag: (state) => {
      state.shouldNavigateToNewConversation = false
    },
    setNavigationFlag: (state, action: PayloadAction<boolean>) => {
      state.shouldNavigateToNewConversation = action.payload
    },
    setCurrentToolId: (state, action: PayloadAction<string | undefined>) => {
      state.currentToolId = action.payload
    },
    clearCurrentToolId: (state) => {
      state.currentToolId = undefined
    },
    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
        // 只有在需要导航到新对话时才更新currentConversationId
        if (action.payload.shouldNavigate) {
          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, setNavigationFlag, clearShouldSendQuestion, setShouldSendQuestion, setCurrentToolId, clearCurrentToolId } = conversationSlice.actions

export default conversationSlice.reducer
