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

type DashboardCounts = {
    totalVehicles: number;
    totalClients: number;
    totalHospitals: number;
    totalCustomers: number;
    totalCustomerEscorts: number;
    totalTrips: number;
};

interface DashboardState {
    counts: DashboardCounts;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error: string | null;
}

const initialState: DashboardState = {
    counts: {
        totalVehicles: 0,
        totalClients: 0,
        totalHospitals: 0,
        totalCustomers: 0,
        totalCustomerEscorts: 0,
        totalTrips: 0,
    },
    status: 'idle',
    error: null,
};

export const fetchDashboardCounts = createAsyncThunk(
    'dashboard/fetch',
    async (params: { startDate?: string; endDate?: string } | undefined, { rejectWithValue }) => {
        try {
            const response = await api.get('dashboard/counts', { params });
            return response?.data?.data ?? response?.data;
        } catch (err: any) {
            return rejectWithValue('Failed to fetch dashboard counts');
        }
    },
);

const dashboardSlice = createSlice({
    name: 'dashboard',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
            .addCase(fetchDashboardCounts.pending, (state) => {
                state.status = 'loading';
                state.error = null;
            })
            .addCase(fetchDashboardCounts.fulfilled, (state, action) => {
                state.status = 'succeeded';
                const data = action.payload as any;
                state.counts = {
                    totalVehicles: Number(data?.total_vehicles?.total ?? 0),
                    totalClients: Number(data?.total_clients ?? 0),
                    totalHospitals: Number(data?.total_hospitals ?? 0),
                    totalCustomers: Number(data?.total_customers?.total ?? 0),
                    totalCustomerEscorts: Number(data?.total_customer_escorts?.total ?? 0),
                    totalTrips: Number(data?.total_trips?.total ?? 0),
                };
            })
            .addCase(fetchDashboardCounts.rejected, (state, action) => {
                state.status = 'failed';
                state.error = (action.payload as string) || 'Failed to fetch dashboard counts';
            });
    },
});

export default dashboardSlice.reducer;
