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';

// Define types
export interface State {
    id: number;
    name: string;
    country_id: number;
    deleted_at: string | null;
    created_at: string;
    updated_at: string;
    country: {
        id: number;
        name: string;
    };
}

interface ApiResponse<T> {
    success: boolean;
    code: number;
    message: string;
    data: {
        count: number;
        data: T[];
    };
}

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

// Initial state
const initialState: StatesState = {
    items: [],
    status: 'idle',
    error: null,
    selectedState: null,
    dropdownItems: null,
    dropdownStatus: 'idle',
    token: null,
    totalCount: 0,
    filters: {
        search: {},
        limit: 10,
        skip: 0,
        sortBy: '',
        sortOrder: 'DESC',
        countryId: undefined,
    },
};

// Async Thunks
export const fetchStates = createAsyncThunk(
    'states/fetchStates',
    async (payload: { countryIds?: string } | undefined, { getState, rejectWithValue }) => {
        try {
            const state = getState() as { states: StatesState };
            const { search, limit, skip, sortBy, sortOrder, countryId } = state?.states?.filters;

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

            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined) {
                    queryParams.append(key, value.toString());
                }
            });

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

export const fetchStatesWithoutFilters = createAsyncThunk(
    'countries/fetchStatesWithoutFilters',
    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(`state?${queryParams.toString()}`);
            return response;
        } catch (error) {
            return rejectWithValue(error instanceof Error ? error.message : 'Failed to fetch all states');
        }
    },
);

export const createState = createAsyncThunk('states/createState', async (stateData: Partial<State>, { rejectWithValue }) => {
    try {
        const response = await api.post(`/state`, stateData);
        return response;
    } catch (error: any) {
        handleToastError(error?.response);

        return rejectWithValue(error);
    }
});

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

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

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

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

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

export const fetchStatesByCountry = createAsyncThunk(
    'states/fetchStatesByCountry',
    async (countryId: number, { rejectWithValue }) => {
        try {
            const response = await api.get(`/state/country-states/${countryId}`);

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

// Create the slice
const statesSlice = createSlice({
    name: 'states',
    initialState,
    reducers: {
        setSelectedState: (state, action: PayloadAction<State | null>) => {
            state.selectedState = action.payload;
        },
        updateFilters: (state, action: PayloadAction<Partial<StatesState['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(fetchStates.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchStates.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action?.payload;
            })
            .addCase(fetchStates.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(createState.pending, (state) => {
                state.status = 'loading';
                state.error = null;
            })
            .addCase(createState.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(createState.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(updateState.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(updateState.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(updateState.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(getStateById.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(getStateById.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.selectedState = action.payload;
            })
            .addCase(getStateById.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
                state.selectedState = null;
            })
            .addCase(deleteState.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(deleteState.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((state) => state.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((state) => state.id !== action.payload);
                }
            })
            .addCase(deleteState.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchStatesByCountry.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchStatesByCountry.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload;
            })
            .addCase(fetchStatesByCountry.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(fetchStatesWithoutFilters.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchStatesWithoutFilters.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.dropdownItems = action.payload.data?.data?.data;
            })
            .addCase(fetchStatesWithoutFilters.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });
    },
});

// Export actions
export const { setSelectedState, updateFilters, resetFilters, setAuthToken } = statesSlice.actions;

export default statesSlice.reducer;
