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, fetchQueryUserConversationPage } from '@/api/conversation'

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

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 createConversation = createAsyncThunk<
  { conversation: Conversation, shouldNavigate: boolean },
  Partial<Conversation>,
  { state: { conversation: ConversationState } }
>(
  'conversation/createConversation',
  async (conversationData, { dispatch }) => {
    const response = await fetchCreateConversation(conversationData)
    const newConversation = response.data

    dispatch(fetchConversations())

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

const conversationSlice = createSlice({
  name: 'conversation',
  initialState,
  reducers: {
    setCurrentConversation: (state, action: PayloadAction<string>) => {
      state.currentConversationId = action.payload
    },
    clearCurrentConversation: (state) => {
      state.currentConversationId = null
    },
    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
      })
      .addCase(createConversation.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message || 'Failed to create conversation'
      })
  },
})

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

export default conversationSlice.reducer
