// 问答功能独立的状态管理
import type { PayloadAction } from '@reduxjs/toolkit'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import type { TacticsConversation, TacticsConversationState } from '@/types/tactics'
import { fetchCreateTacticsConversation, fetchDeleteTacticsConversation, fetchTacticsConversationPage } from '@/api/tactics'

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

// 处理会话数据（简化版，可根据实际需求调整）
function processTacticsConversationData(records: any[]): TacticsConversation[] {
  return records.map(record => ({
    id: record.conversationId || record.id,
    title: record.title || record.conversationTitle,
    createdAt: record.createTime || record.createdAt,
    updatedAt: record.updateTime || record.updatedAt,
  }))
}

export const fetchTacticsConversations = createAsyncThunk(
  'tactics/fetchTacticsConversations',
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetchTacticsConversationPage({
        pageNum: 1,
        pageSize: 100,
      })
      const records = response.data?.records || []
      return processTacticsConversationData(records)
    }
    catch (error) {
      console.error('Failed to fetch tactics conversations:', error)
      return rejectWithValue('Failed to fetch tactics conversations')
    }
  },
)

export const deleteTacticsConversations = createAsyncThunk<
  boolean,
  string[],
  { rejectValue: boolean }
>(
  'tactics/deleteTacticsConversations',
  async (conversationIds, { dispatch, rejectWithValue }) => {
    try {
      await fetchDeleteTacticsConversation(conversationIds)
      await dispatch(fetchTacticsConversations())
      return true
    }
    catch (error) {
      console.error('Failed to delete tactics conversations:', error)
      return rejectWithValue(false)
    }
  },
)

export const createTacticsConversation = createAsyncThunk<
  { conversation: TacticsConversation, shouldNavigate: boolean, shouldSendQuestion: string },
  { conversationData: Partial<TacticsConversation>, shouldNavigate: boolean, shouldSendQuestion: string }
>(
  'tactics/createTacticsConversation',
  async ({ conversationData, shouldNavigate, shouldSendQuestion }, { dispatch }) => {
    const response = await fetchCreateTacticsConversation(conversationData)
    const newConversation = response.data

    await dispatch(fetchTacticsConversations())

    return {
      conversation: {
        id: newConversation.conversationId || newConversation.id,
        title: newConversation.title || newConversation.conversationTitle,
        createdAt: newConversation.createTime || newConversation.createdAt,
        updatedAt: newConversation.updateTime || newConversation.updatedAt,
      },
      shouldNavigate,
      shouldSendQuestion,
    }
  },
)

const tacticsSlice = createSlice({
  name: 'tactics',
  initialState,
  reducers: {
    setCurrentTacticsConversation: (state, action: PayloadAction<string>) => {
      state.currentConversationId = action.payload
    },
    clearCurrentTacticsConversation: (state) => {
      state.currentConversationId = null
    },
    clearTacticsShouldSendQuestion: (state) => {
      state.shouldSendQuestion = ''
    },
    setTacticsShouldSendQuestion: (state, action: PayloadAction<string>) => {
      state.shouldSendQuestion = action.payload
    },
    addTacticsConversation: (state, action: PayloadAction<TacticsConversation>) => {
      state.conversations.unshift(action.payload)
    },
    clearTacticsNavigationFlag: (state) => {
      state.shouldNavigateToNewConversation = false
    },
    removeTacticsConversation: (state, action: PayloadAction<string>) => {
      state.conversations = state.conversations.filter(conv => conv.id !== action.payload)
      if (state.currentConversationId === action.payload) {
        state.currentConversationId = state.conversations[0]?.id || null
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchTacticsConversations.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(fetchTacticsConversations.fulfilled, (state, action) => {
        state.isLoading = false
        state.conversations = action.payload
      })
      .addCase(fetchTacticsConversations.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.payload as string
      })
      .addCase(createTacticsConversation.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(createTacticsConversation.fulfilled, (state, action) => {
        state.isLoading = false
        if (action.payload.shouldNavigate) {
          state.currentConversationId = action.payload.conversation.id
        }
        state.shouldNavigateToNewConversation = action.payload.shouldNavigate
        state.shouldSendQuestion = action.payload.shouldSendQuestion
      })
      .addCase(createTacticsConversation.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message || 'Failed to create tactics conversation'
      })
      .addCase(deleteTacticsConversations.fulfilled, () => {
      })
      .addCase(deleteTacticsConversations.rejected, () => {
      })
  },
})

export const {
  setCurrentTacticsConversation,
  clearCurrentTacticsConversation,
  clearTacticsNavigationFlag,
  clearTacticsShouldSendQuestion,
  setTacticsShouldSendQuestion,
} = tacticsSlice.actions

export default tacticsSlice.reducer
