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

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

export const fetchTacticsConversations = createAsyncThunk(
  'tactics/fetchTacticsConversations',
  async () => {
    // 该页面内无需调用远程接口，保持 thunk 以兼容现有调用
    return [] as TacticsConversation[]
  },
)

export const deleteTacticsConversations = createAsyncThunk<
  boolean,
  string[],
  { rejectValue: boolean }
>(
  'tactics/deleteTacticsConversations',
  async (conversationIds, { dispatch, rejectWithValue }) => {
    try {
      await waitForToken()
      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 }) => {
    await waitForToken()
    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
