import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';

import api from '@/lib/axios';
import { handleAuthentication, handleToastError } from '@/lib/utils';

// Currency interface
export interface Currency {
    id: number;
    name: string;
    code: string;
    symbol: string;
    is_active: boolean;
}

// CurrenciesState interface
interface CurrenciesState {
    items: Currency[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    dropdownItems: any;
    dropdownStatus: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    selectedCurrency: Currency | null;
    token: string | null;
    totalCount: number;
    filters: {
        search?: { [key: string]: string };
        sortBy?: string;
        sortOrder?: 'ASC' | 'DESC';
        isActive?: boolean;
        countryId?: number;
    };
}

// Initial state
const initialState: CurrenciesState = {
    items: [],
    status: 'idle',
    error: null,
    selectedCurrency: null,
    dropdownItems: null,
    dropdownStatus: 'idle',
    token: null,
    totalCount: 0,
    filters: {
        search: {},
        sortBy: '',
        sortOrder: 'ASC',
        countryId: undefined,
    },
};

// Async Thunks
export const fetchCurrencies = createAsyncThunk(
    'currencies/fetchCurrencies',
    async (payload: { countryIds?: string; skip?: number; limit?: number } | undefined, { getState, rejectWithValue }) => {
        try {
            const state = getState() as { currencies: CurrenciesState };
            const { search, sortBy, sortOrder, isActive, countryId } = state?.currencies?.filters;
            const limit = payload?.limit || 10;
            const skip = payload?.skip || 0;

            // Build query parameters object
            const params = {
                limit,
                skip,
                ...(sortBy && { sortBy }),
                ...(sortOrder && { sortOrder }),
                ...(isActive !== undefined && { isActive }),
                ...(payload?.countryIds && { country_id: payload.countryIds }),
                ...(countryId && !payload?.countryIds && { country_id: countryId }),
                ...(search && typeof search === 'object' && search.name ? { search: search.name } : {}),
                ...(search && typeof search === 'string' ? { search } : {}),
            };

            // Convert params object to URL query string
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined) {
                    queryParams.append(key, value.toString());
                }
            });

            const response = await api.get(`/currency?${queryParams.toString()}`);
            return response.data;
        } catch (error: any) {
            handleToastError(error?.response);

            return rejectWithValue(error);
        }
    },
);

export const fetchCurrenciesWithoutFilters = createAsyncThunk(
    'countries/fetchCurrenciesWithoutFilters',
    async (_, { rejectWithValue }) => {
        try {
            const queryParams = new URLSearchParams({
                limit: '100', // Large number to get all countries
                skip: '0',
            });

            const response = await api.get(`/currency?${queryParams.toString()}`);

            return response;
        } catch (error) {
            return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch all states');
        }
    },
);

export const createCurrency = createAsyncThunk(
    'currencies/createCurrency',
    async (currencyData: Partial<Currency>, { rejectWithValue }) => {
        try {
            const response = await api.post(`/currency`, currencyData);
            return response;
        } catch (error) {
            return rejectWithValue(error instanceof Error ? error.message : 'Failed to create currency');
        }
    },
);

export const getCurrencyById = createAsyncThunk('currencies/getCurrencyById', async (id: number, { rejectWithValue }) => {
    try {
        const response = await api.get(`/currency/${id}`);
        return response.data;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch currency details');
    }
});

export const updateCurrency = createAsyncThunk(
    'currencies/updateCurrency',
    async ({ id, ...currencyData }: { id: number } & Partial<Currency>, { rejectWithValue }) => {
        try {
            const response = await api.patch(`/currency/${id}`, currencyData, {});
            return response.data;
        } catch (error) {
            return rejectWithValue(error instanceof Error ? error.message : 'Failed to update currency');
        }
    },
);

export const deleteCurrency = createAsyncThunk('currencies/deleteCurrency', async (id: number, { rejectWithValue }) => {
    try {
        await api.delete(`/currency/${id}`);
        return id;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to delete currency');
    }
});

export const fetchActiveCurrencies = createAsyncThunk('currencies/fetchActiveCurrencies', async (_, { rejectWithValue }) => {
    try {
        const response = await api.get(`/currency/active`, {});
        return response.data;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch active currencies');
    }
});

// Create the slice
const currenciesSlice = createSlice({
    name: 'currencies',
    initialState,
    reducers: {
        setSelectedCurrency: (state, action: PayloadAction<Currency | null>) => {
            state.selectedCurrency = action.payload;
        },
        updateFilters: (state, action: PayloadAction<Partial<CurrenciesState['filters']>>) => {
            state.filters = { ...state.filters, ...action.payload };
        },
        resetFilters: (state) => {
            state.filters = initialState.filters;
        },
        setAuthToken: (state, action: PayloadAction<string | null>) => {
            state.token = action.payload;

            // Only interact with localStorage on the client side
            if (typeof window !== 'undefined') {
                if (action.payload) {
                    localStorage.setItem('token', action.payload);
                } else {
                    localStorage.removeItem('token');
                }
            }
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchCurrencies.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchCurrencies.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action?.payload;
            })
            .addCase(fetchCurrencies.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(createCurrency.pending, (state) => {
                state.status = 'loading';
                state.error = null;
            })
            .addCase(createCurrency.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(createCurrency.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(updateCurrency.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(updateCurrency.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(updateCurrency.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(getCurrencyById.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(getCurrencyById.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.selectedCurrency = action.payload;
            })
            .addCase(getCurrencyById.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
                state.selectedCurrency = null;
            })
            .addCase(deleteCurrency.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(deleteCurrency.fulfilled, (state, action) => {
                state.status = 'succeeded';

                // Safely handle different data structures
                if (state.items?.data?.data) {
                    state.items.data.data = state.items.data.data.filter((currency) => currency.id !== action.payload);

                    // Optionally, update the total count
                    if (state.items.data.count > 0) {
                        state.items.data.count -= 1;
                    }
                } else if (Array.isArray(state.items)) {
                    // Fallback if items is a direct array
                    state.items = state.items.filter((currency) => currency.id !== action.payload);
                }
            })
            .addCase(deleteCurrency.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchActiveCurrencies.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchActiveCurrencies.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload;
            })
            .addCase(fetchActiveCurrencies.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchCurrenciesWithoutFilters.pending, (state) => {
                state.dropdownStatus = 'loading';
            })
            .addCase(fetchCurrenciesWithoutFilters.fulfilled, (state, action) => {
                state.dropdownStatus = 'succeeded';
                state.dropdownItems = action.payload; // Store the complete list separately
            })
            .addCase(fetchCurrenciesWithoutFilters.rejected, (state, action) => {
                state.dropdownStatus = 'failed';
                state.error = action.payload as string;
            });
    },
});

// Export actions
export const { setSelectedCurrency, updateFilters, resetFilters, setAuthToken } = currenciesSlice.actions;

export default currenciesSlice.reducer;
