import type { Token } from "@/types/index";
import { type PayloadAction, createSlice } from "@reduxjs/toolkit";

const initialState: QuoteParams = {
	// mandatory
	amounts: [],
	fromChainId: null,
	fromTokens: [],
	toChainId: null,
	toTokens: [],
	outputRatio: [1],
	sender: null,
	receiver: null,
	addOnRefuel: false,
	isFetchingDisabled: false,
};

const quoteParams = createSlice({
	name: "quoteParams",
	initialState,
	reducers: {
		setAmount: (state, action) => {
			state.amounts = action.payload ? [action.payload] : []; // overriding index 0 as bungee doesn't support multi-input
		},
		setFromChainId: (state, action: PayloadAction<QuoteParams["fromChainId"]>) => {
			state.fromChainId = action.payload;
		},
		setFromTokens: (state, action: { payload: Token }) => {
			state.fromTokens = [action.payload]; // overriding index 0. Not optimized for multi input
		},
		setToChainId: (state, action: PayloadAction<QuoteParams["toChainId"]>) => {
			state.toChainId = action.payload;
		},
		addOutputToken: (state, action: { payload: { id: number; token: Token } }) => {
			state.toTokens[action.payload.id] = action.payload.token;
		},
		removeOutputToken: (state, action) => {
			state.toTokens.splice(action.payload.id, 1); // need change here
		},
		resetOutputTokens: (state) => {
			state.toTokens = [];
		},
		// for destination token ratio
		setOutputTokenRatios: (state, action: { payload: number[] }) => {
			state.outputRatio = action.payload; // expecting an array here
		},
		removeOutputTokenRatio: (state, action) => {
			state.outputRatio.splice(action.payload.id, 1);
		},
		resetOutputTokenRatios: (state) => {
			state.outputRatio = [1];
		},
		setSenderAddress: (state, action) => {
			state.sender = action.payload;
		},
		setReceiverAddress: (state, action) => {
			state.receiver = action.payload;
		},
		setReceiverENS: (state, action) => {
			state.receiverENS = action.payload;
		},
		toggleAddOnRefuel: (state, action) => {
			state.addOnRefuel = action.payload;
		},
		setIsFetchingDisabled: (state, action) => {
			state.isFetchingDisabled = action.payload;
		},
	},
});

export default quoteParams.reducer;
export const {
	setAmount,
	setFromChainId,
	setFromTokens,
	setToChainId,
	addOutputToken,
	removeOutputToken,
	resetOutputTokens,
	setOutputTokenRatios,
	removeOutputTokenRatio,
	resetOutputTokenRatios,
	setSenderAddress,
	setReceiverAddress,
	setReceiverENS,
	toggleAddOnRefuel,
	setIsFetchingDisabled,
} = quoteParams.actions;

export interface QuoteParams {
	amounts: string[];
	fromChainId: number | null;
	fromTokens: Token[];
	toChainId: number | null;
	toTokens: Token[];
	outputRatio: number[];
	sender: string | null;
	receiver: string | null;
	receiverENS?: string;
	addOnRefuel?: boolean;
	isFetchingDisabled?: boolean;
}
