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,
  businessInsightWorkflow: {
    mainWorkflowSessionId: null,
    subWorkflowSessionId: null,
    subWorkflowRecordType: null,
    paramMap: {},
    isInSubWorkflow: false,
    pendingQuestion: null,
  },
}

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 || ''
    const toolId = cachedToolId || ''
    // 排除 toolId 字段，只传递 busiId 和 busiType
    const { toolId: _, ...restConversationData } = conversationData
    const requestPayload = {
      ...restConversationData,
      busiId,
      busiType: '01',
      toolId,
    }
    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
    },
    setBusinessInsightMainWorkflow: (state, action: PayloadAction<string>) => {
      state.businessInsightWorkflow.mainWorkflowSessionId = action.payload
      state.businessInsightWorkflow.isInSubWorkflow = false
    },
    setBusinessInsightSubWorkflow: (state, action: PayloadAction<{ sessionId: string, recordType: string }>) => {
      state.businessInsightWorkflow.subWorkflowSessionId = action.payload.sessionId
      state.businessInsightWorkflow.subWorkflowRecordType = action.payload.recordType
      state.businessInsightWorkflow.isInSubWorkflow = true
      state.businessInsightWorkflow.paramMap = {}
    },
    updateBusinessInsightParamMap: (state, action: PayloadAction<Record<string, string>>) => {
      state.businessInsightWorkflow.paramMap = {
        ...state.businessInsightWorkflow.paramMap,
        ...action.payload,
      }
    },
    clearBusinessInsightSubWorkflow: (state) => {
      state.businessInsightWorkflow.subWorkflowSessionId = null
      state.businessInsightWorkflow.subWorkflowRecordType = null
      state.businessInsightWorkflow.isInSubWorkflow = false
      state.businessInsightWorkflow.paramMap = {}
    },
    exitBusinessInsightSubWorkflow: (state) => {
      state.businessInsightWorkflow.isInSubWorkflow = false
      state.businessInsightWorkflow.subWorkflowSessionId = null
      state.businessInsightWorkflow.subWorkflowRecordType = null
      state.businessInsightWorkflow.paramMap = {}
    },
    setBusinessInsightPendingQuestion: (state, action: PayloadAction<string | null>) => {
      state.businessInsightWorkflow.pendingQuestion = action.payload
    },
    clearBusinessInsightWorkflow: (state) => {
      state.businessInsightWorkflow = {
        mainWorkflowSessionId: null,
        subWorkflowSessionId: null,
        subWorkflowRecordType: null,
        paramMap: {},
        isInSubWorkflow: false,
        pendingQuestion: null,
      }
    },
    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, setBusinessInsightMainWorkflow, setBusinessInsightSubWorkflow, updateBusinessInsightParamMap, clearBusinessInsightSubWorkflow, exitBusinessInsightSubWorkflow, setBusinessInsightPendingQuestion, clearBusinessInsightWorkflow } = conversationSlice.actions

export default conversationSlice.reducer
