import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { sendMessage } from './thunks';
import { SaveReportRequest } from 'src/store/reportsSlice/thunks';
import { 
    getStoredMessages, 
    saveMessagesToStorage, 
    getStoredMinimizedState, 
    saveMinimizedState 
} from '../../utils/localStorage';

export const BOT_TYPE = 'bot';
export const USER_TYPE = 'user';

type Sender = 'bot' | 'user';

export interface Message {
    id: string;
    sender: Sender;
    payload: {};
    report?: SaveReportRequest;
    timestamp: number;
}

interface ChatState {
    messages: Message[];
    isLoading: boolean;
    minimized: boolean;
}

const initialState: ChatState = {
    messages: getStoredMessages(),
    isLoading: false,
    minimized: getStoredMinimizedState()
};

const aiChatSlice = createSlice({
    name: 'aiChat',
    initialState,
    reducers: {
        addMessage: (state, action: PayloadAction<Omit<Message, 'id' | 'timestamp'>>) => {
            const message: Message = {
                ...action.payload,
                id: Date.now().toString(),
                timestamp: Date.now(),
            };
            state.messages.push(message);
            saveMessagesToStorage(state.messages);
        },
        updateMessageReport: (state, action: PayloadAction<{ messageId: string; report: SaveReportRequest }>) => {
            const messageIndex = state.messages.findIndex(msg => msg.id === action.payload.messageId);
            if (messageIndex !== -1) {
                state.messages[messageIndex].report = action.payload.report;
            }
            saveMessagesToStorage(state.messages);
        },
        clearMessages: (state) => {
            state.messages = [];
            saveMessagesToStorage(state.messages);
        },
        setMinmize: (state, action: PayloadAction<boolean>) => {
            state.minimized = action.payload;
            saveMinimizedState(action.payload);
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(sendMessage.pending, (state) => {
                state.isLoading = true;
            })
            .addCase(sendMessage.fulfilled, (state, action) => {
                state.isLoading = false;
                const message: Message = {
                    id: Date.now().toString(),
                    sender: BOT_TYPE,
                    payload: action.payload,
                    timestamp: Date.now()
                };
                state.messages.push(message);
                saveMessagesToStorage(state.messages);
            })
            .addCase(sendMessage.rejected, (state, action) => {
                notify.error(action.payload?.error?.message || action.payload, { autotimeout: 10000 });
                let payload = 'Sorry, there was an error. Please try again.';
                state.isLoading = false;
                if (action.meta.aborted) {
                    payload = 'Request was cancelled.'
                }
                const errorMessage: Message = {
                    id: Date.now().toString(),
                    sender: BOT_TYPE,
                    payload,
                    timestamp: Date.now(),
                };
                state.messages.push(errorMessage);
                saveMessagesToStorage(state.messages);
            });
    },
});

export const { addMessage, updateMessageReport, clearMessages, setMinmize } = aiChatSlice.actions;

export default aiChatSlice.reducer;
