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

// Define a type for the client type
export interface ClientType {
    id: number;
    name: string;
    description: string;
    status: number;
}

// Define the state type
interface ClientTypesState {
    items: ClientType[];
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
    filters: {
        search: string;
        sortBy?: string;
        sortOrder?: 'ASC' | 'DESC';
    };
    totalCount: number;
}

// Initial state
const initialState: ClientTypesState = {
    items: [],
    status: 'idle',
    error: null,
    filters: {
        search: '',
        sortBy: '',
        sortOrder: 'DESC',
    },
    totalCount: 0,
};

// Async thunks for API calls
export const fetchClientTypes = createAsyncThunk(
    'clientTypes/fetchClientTypes',
    async (
        params: { skip?: number; limit?: number; search?: string; sortBy?: string; sortOrder?: 'ASC' | 'DESC' },
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get(`/client-type`, {
                params: {
                    skip: params.skip || 0,
                    limit: params.limit || 10,
                    search: params.search || '',
                    sortBy: params.sortBy,
                    sortOrder: params.sortOrder,
                },
            });

            return response.data.data;
        } catch (error: any) {
            return rejectWithValue(error.response?.data?.message || 'Failed to fetch client types');
        }
    },
);

export const addClientType = createAsyncThunk(
    'clientTypes/addClientType',
    async (payload: { name: string; description: string }) => {
        try {
            const response = await api.post(`/client-type`, payload);
            return response;
        } catch (error: any) {
            return error.response;
        }
    },
);

export const updateClientType = createAsyncThunk(
    'clientTypes/updateClientType',
    async ({ id, name, description }: { id: number; name: string; description: string }) => {
        try {
            const response = await api.patch(`/client-type/${id}`, {
                name,
                description,
            });
            return response;
        } catch (error: any) {
            return error.response;
        }
    },
);

export const deleteClientType = createAsyncThunk('clientTypes/deleteClientType', async (id: number, { rejectWithValue }) => {
    try {
        const response = await api.delete(`/client-type/${id}`);

        if (response?.data?.success === false) {
            toast.error(response.data.message || 'Failed to delete client type');
            return rejectWithValue(response.data.message || 'Deletion failed');
        }

        toast.success('Client type deleted successfully');
        return id;
    } catch (error) {
        return rejectWithValue(error instanceof Error ? error.message : 'Failed to delete client type');
    }
});

export const fetchClientTypeDetails = createAsyncThunk('clientTypes/fetchDetails', async (id: number) => {
    try {
        const response = await api.get(`/client-type/${id}`);
        return response.data;
    } catch (error: any) {
        throw error.response?.data || error.message;
    }
});

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

            .addCase(addClientType.fulfilled, (state, action) => {
                const code = action.payload?.data?.code;

                if (code === 200 || code === 201) {
                    state.items.push(action.payload.data.data);
                    toast.success('Client type added successfully');
                } else if (code === 422) {
                    toast.error('Client type already exists');
                } else {
                    toast.error('Something went wrong');
                }
            })

            .addCase(updateClientType.fulfilled, (state, action) => {
                const code = action.payload?.data?.code;

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

            .addCase(deleteClientType.fulfilled, (state, action) => {
                state.items = state.items.filter((item) => item.id !== action.payload);
            });
    },
});

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

export default clientTypesSlice.reducer;
