import api from '@/lib/axios';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { toast } from 'sonner';

export interface VehicleStatus {
    id: number;
    name: string;
    description: string;
    color_code: string;
    color_name: string;
    color_description: string;
}

interface VehicleStatusesState {
    items: VehicleStatus[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: {
        search: string;
        skip: number;
        limit: number;
        sortBy?: string;
        sortOrder?: 'ASC' | 'DESC';
    };
    totalCount: number;
}

const initialState: VehicleStatusesState = {
    items: [],
    status: 'idle',
    error: null,
    filters: {
        search: '',
        limit: 10,
        skip: 0,
        sortBy: '',
        sortOrder: 'DESC',
    },
    totalCount: 0,
};

export const fetchVehicleStatuses = createAsyncThunk(
    'vehicleStatuses/fetchVehicleStatuses',
    async (params: { skip?: number; limit?: number; search?: string; sortBy?: string; sortOrder?: 'ASC' | 'DESC' }) => {
        try {
            const response = await api.get(`/vehicle-statuses`, {
                params,
            });
            return response.data.data;
        } catch (error: any) {
            throw error.response?.data || error.message;
        }
    },
);

export const addVehicleStatus = createAsyncThunk(
    'vehicleStatuses/addVehicleStatus',
    async (payload: { name: string; description: string; color: string; color_name: string }) => {
        try {
            const response = await api.post(`/vehicle-statuses`, payload);
            return response;
        } catch (error: any) {
            return error.response;
        }
    },
);

export const updateVehicleStatus = createAsyncThunk(
    'vehicleStatuses/updateVehicleStatus',
    async ({ id, name, description, color_description, color_code, color_name }: VehicleStatus) => {
        try {
            const response = await api.patch(`/vehicle-statuses/${id}`, {
                name,
                description,
                color_description,
                color_code,
                color_name,
            });
            return response;
        } catch (error: any) {
            return error.response;
        }
    },
);

export const deleteVehicleStatus = createAsyncThunk('vehicleStatuses/deleteVehicleStatus', async (id: number) => {
    try {
        const response = await api.delete(`/vehicle-statuses/${id}`);
        return response;
    } catch (error: any) {
        return error.response;
    }
});

export const fetchVehicleStatusById = createAsyncThunk('vehicleStatuses/fetchVehicleStatusById', async (id: number) => {
    try {
        const response = await api.get(`/vehicle-statuses/${id}`);
        return response.data;
    } catch (error: any) {
        throw error.response?.data || error.message;
    }
});

const vehicleStatusesSlice = createSlice({
    name: 'vehicleStatuses',
    initialState,
    reducers: {
        updateFilters: (state, action: PayloadAction<Partial<VehicleStatusesState['filters']>>) => {
            state.filters = { ...state.filters, ...action.payload };
        },
        resetFilters: (state) => {
            state.filters = initialState.filters;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchVehicleStatuses.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchVehicleStatuses.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.items = action.payload.data;
                state.totalCount = action.payload.count;
            })
            .addCase(fetchVehicleStatuses.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            })
            .addCase(addVehicleStatus.fulfilled, (state, action) => {
                const code = action.payload?.data?.code;

                if (code === 200 || code === 201) {
                    state.items.push(action.payload.data.data);
                    toast.success('Vehicle Status added successfully');
                } else if (code === 422) {
                    toast.error('Vehicle Status already exists');
                } else {
                    toast.error('Something went wrong');
                }
            })
            .addCase(updateVehicleStatus.fulfilled, (state, action) => {
                const code = action.payload?.data?.code;

                if (code === 200 || code === 201) {
                    const index = state.items.findIndex((item) => item.id === action.payload.data.data.id);
                    if (index !== -1) {
                        state.items[index] = action.payload.data.data;
                    }
                    toast.success('Vehicle Status updated successfully');
                } else if (code === 422) {
                    toast.error('Vehicle Status already exists');
                } else {
                    toast.error('Something went wrong');
                }
            })
            .addCase(deleteVehicleStatus.fulfilled, (state, action) => {
                const code = action.payload?.data?.code;

                if (code === 200) {
                    // state.items = state.items.filter((item) => item.id !== action.payload.data.data.id);
                    toast.success('Vehicle Status deleted successfully');
                } else {
                    toast.error('Something went wrong');
                }
            })
            .addCase(fetchVehicleStatusById.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchVehicleStatusById.fulfilled, (state, action) => {
                state.status = 'succeeded';
            })
            .addCase(fetchVehicleStatusById.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.error.message || 'Failed to fetch vehicle status details';
            });
    },
});

export const { updateFilters, resetFilters } = vehicleStatusesSlice.actions;

export default vehicleStatusesSlice.reducer;
