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

import api from '@/lib/axios';
import { handleToastError } from '@/lib/utils';
import { toast } from 'sonner';
import messages from '../../../messages/en.json';

// Country interface
export interface Country {
    id: number;
    name: string;
}

// State interface
interface CountriesState {
    items: Country[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    dropdownItems: any;
    dropdownStatus: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    selectedCountry: Country | null;
    token: string | null;
    totalCount: number;
    filters: {
        search?: { [key: string]: string };
        limit: number;
        skip: number;
        sortBy?: string;
        sortOrder?: 'ASC' | 'DESC';
    };
}

// Initial state
const initialState: CountriesState = {
    items: [],
    status: 'idle',
    error: null,
    selectedCountry: null,
    dropdownItems: null,
    dropdownStatus: 'idle',
    token: null,
    totalCount: 0,
    filters: {
        search: {},
        limit: 10,
        skip: 0,
        sortBy: '',
        sortOrder: 'ASC',
    },
};

// Async Thunks
export const fetchCountries = createAsyncThunk('countries/fetchCountries', async (_, { getState, rejectWithValue }) => {
    try {
        const state = getState() as { countries: CountriesState };

        const { search, limit, skip, sortBy, sortOrder } = state?.countries?.filters;

        // Build query parameters object
        const params = {
            limit,
            skip,
            ...(sortBy && { sortBy }),
            ...(sortOrder && { sortOrder }),
            ...(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());
            }
        });

        // Changed /country? to /country/list?
        const response = await api.get(`/country/list?${queryParams.toString()}`);
        return response.data;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch countries');
    }
});

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

            const response = await api.get(`/country/list?${queryParams.toString()}`);
            return response.data;
        } catch (error) {
            return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch all countries');
        }
    },
);

export const fetchCountryWithPagination = createAsyncThunk(
    'countries/fetchCountriesWithFilters',
    async (param: any, { rejectWithValue }) => {
        try {
            const queryString = new URLSearchParams(param).toString();
            const response = await api.get(`/country/list?${queryString}`);

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

export const createCountry = createAsyncThunk(
    'countries/createCountry',
    async (countryData: Partial<Country>, { rejectWithValue }) => {
        try {
            const response = await api.post(`/country/create`, countryData);
            return response;
        } catch (error: any) {
            handleToastError(error?.response);

            return rejectWithValue(error?.response?.data || error.message);
        }
    },
);

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

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

export const deleteCountry = createAsyncThunk('countries/deleteCountry', async (id: number, { rejectWithValue }) => {
    try {
        const response = await api.delete(`/country/delete/${id}`);

        if (response?.data?.success === false) {
            toast.error(response.data.message || messages.toasts.error.failed_to_delete_country);
            return rejectWithValue(response.data.message || 'Deletion failed');
        }

        toast.success(messages.toasts.success.country_deleted);
        return id;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to delete country');
    }
});

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

// Create the slice
const countriesSlice = createSlice({
    name: 'countries',
    initialState,
    reducers: {
        setSelectedCountry: (state, action: PayloadAction<Country | null>) => {
            state.selectedCountry = action.payload;
        },
        updateFilters: (state, action: PayloadAction<Partial<CountriesState['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(fetchCountries.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchCountries.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action?.payload;
            })
            .addCase(fetchCountries.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(createCountry.pending, (state) => {
                state.status = 'loading';
                state.error = null;
            })
            .addCase(createCountry.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(createCountry.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(updateCountry.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(updateCountry.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(updateCountry.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(getCountryById.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(getCountryById.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.selectedCountry = action.payload;
            })
            .addCase(getCountryById.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
                state.selectedCountry = null;
            })
            .addCase(deleteCountry.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(deleteCountry.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((country) => country.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((country) => country.id !== action.payload);
                }
            })
            .addCase(deleteCountry.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchCountriesWithoutFilters.pending, (state) => {
                state.dropdownStatus = 'loading';
            })
            .addCase(fetchCountriesWithoutFilters.fulfilled, (state, action) => {
                state.dropdownStatus = 'succeeded';
                state.dropdownItems = action.payload; // Store the complete list separately
            })
            .addCase(fetchCountriesWithoutFilters.rejected, (state, action) => {
                state.dropdownStatus = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchCountryWithPagination.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchCountryWithPagination.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action?.payload;
            })
            .addCase(fetchCountryWithPagination.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchCountryDropdown.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchCountryDropdown.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action?.payload;
            })
            .addCase(fetchCountryDropdown.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });
    },
});

// Export actions
export const { setSelectedCountry, updateFilters, resetFilters, setAuthToken } = countriesSlice.actions;

export default countriesSlice.reducer;
