import { PayloadAction } from '@reduxjs/toolkit/react';
import { createSlice } from '@reduxjs/toolkit';
import { defaultCurrency } from '@/constants/common';
import { sliceNames } from '@/src/constants/redux/redux';
import { CurrencyState } from '@/src/constants/redux/currency';

export const initialState: CurrencyState = {
    fromCurrency: defaultCurrency,
    toCurrency: defaultCurrency,
    amount: 1,
    date: '',
    from: defaultCurrency,
    to: defaultCurrency,
    value: 1,
    data: null,
    loading: false,
};

const currenciesSlice = createSlice({
    name: sliceNames.currencies,
    initialState,
    reducers: {
        setCurrencyData: (state, action: PayloadAction<CurrencyState>) => {
            if (action.payload && action.payload.toCurrency) {
                state.toCurrency = action.payload.toCurrency;
                state.fromCurrency = action.payload.fromCurrency;
                state.amount = action.payload.amount;
                state.date = action.payload.date;
                state.from = action.payload.from;
                state.to = action.payload.to;
                state.value = action.payload.value;
                state.data = action.payload;
            }
        },
        setToCurrency: (state, action: PayloadAction<string>) => {
            if (action.payload) {
                state.toCurrency = action.payload;
            }
        },
        setFromCurrency: (state, action: PayloadAction<string>) => {
            state.fromCurrency = action.payload;
        },
        setLoading: (state, action: PayloadAction<boolean>) => {
            state.loading = action.payload;
        },
    },
});

export const { setCurrencyData, setLoading, setToCurrency, setFromCurrency } = currenciesSlice.actions;

export default currenciesSlice.reducer;