import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import api from '@/lib/axios';
import messages from '../../../messages/en.json';

export type TripSummaryApiItem = {
    trip_id: number | string;
    trip_pick_up_date: string;
    trip_drop_off_date?: string;
    trip_pick_up_time?: string;
    trip_pick_up_address: string;
    trip_drop_off_address: string;
    trip_drop_off_location?: string;
    driver_first_name: string;
    driver_last_name: string;
    vehicle_type_name: string;
    trip_estimated_distance: string | number;
    trip_estimated_time: string | number;
    customer_name: string;
    client_company_name: string;
    trip_status: string;
    [key: string]: unknown;
};

export type DispatcherPerformanceApiItem = {
    dispatcher_id: number;
    dispatcher_first_name: string;
    dispatcher_last_name: string;
    dispatcher_email: string;
    dispatcher_phone_number: string;
    dispatcher_role: string;
    driver_feedback: string | null;
    customer_feedback: string | null;
    trips_assigned: string;
    completed_trips: string;
    performance: string;
    completion_rate: string;
    [key: string]: unknown;
};

export type HospitalReportApiItem = {
    hospital_id?: number;
    hospital_name?: string;
    name?: string;
    location?: string;
    address?: string;
    city?: string;
    state?: string;
    patients_referred?: number | string;
    total_trips?: number | string;
    appointment_type?: string;
    avg_trip_duration?: string;
    avg_trip_distance?: string;
    [key: string]: unknown;
};

export type CustomerTransportHistoryApiItem = {
    customer_id: number;
    customer_name: string;
    client_name: string | null;
    total_trips: string;
    total_requested_trips: string;
    average_rating?: string | number | null;
    [key: string]: unknown;
};

export type DriverPerformanceApiItem = {
    driver_id: number;
    driver_first_name: string;
    driver_last_name: string;
    driver_email?: string;
    driver_phone_number?: string;
    completed_trips: string | number;
    cancelled_trips: string | number;
    average_trip_time?: string;
    average_trip_rating?: string | number;
    average_trips_per_day?: string | number;
    [key: string]: unknown;
};

export type VehicleUtilizationApiItem = {
    vehicle_id?: number;
    vehicleId?: string;
    registration_number?: string;
    registrationNumber?: string;
    make?: string;
    model?: string;
    vehicle_type?: string;
    vehicleType?: string;
    state?: string;
    total_trips_completed?: string | number;
    totalTripsCompleted?: string | number;
    total_distance_covered?: string | number;
    totalDistanceCovered?: string | number;
    last_trip_date?: string;
    lastTripDate?: string;
    last_maintenance_date?: string;
    lastMaintenanceDate?: string;
    [key: string]: unknown;
};

export type PaymentCollectionSummaryApiItem = {
    payment_id?: number;
    invoice_id?: number;
    invoice_number?: string | number;
    invoiceNumber?: string | number;
    date_of_collection?: string;
    collection_date?: string;
    collectionDate?: string;
    amount_collected?: string | number;
    amountCollected?: string | number;
    received_by?: string;
    receivedBy?: string;
    customer_name?: string;
    customerName?: string;
    client_name?: string | null;
    clientName?: string | null;
    payment_type?: string;
    paymentType?: string;
    [key: string]: unknown;
};

export type PendingPaymentsOutstandingApiItem = {
    payment_id?: number;
    invoice_number?: string | number;
    invoiceNumber?: string | number;
    invoice_date?: string;
    invoiceDate?: string;
    invoice_amount?: string | number;
    invoiceAmount?: string | number;
    amount_due?: string | number;
    amountDue?: string | number;
    customer_name?: string;
    customerName?: string;
    client_name?: string | null;
    clientName?: string | null;
    trip_type?: string;
    tripType?: string;
    [key: string]: unknown;
};

interface TripSummaryResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              trip?: TripSummaryApiItem[];
              totalCount?: string | number;
          }
        | { data?: TripSummaryApiItem[]; count?: number }
        | TripSummaryApiItem[];
    count?: number;
}

interface DispatcherPerformanceResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              dispatchers?: DispatcherPerformanceApiItem[];
              totalCount?: string | number;
          }
        | DispatcherPerformanceApiItem[];
    count?: number;
}

interface HospitalReportResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              hospitals?: HospitalReportApiItem[];
              totalCount?: string | number;
          }
        | HospitalReportApiItem[];
    count?: number;
}

interface CustomerTransportHistoryResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              customers?: CustomerTransportHistoryApiItem[];
              totalCount?: string | number;
          }
        | CustomerTransportHistoryApiItem[];
    count?: number;
}

interface DriverPerformanceResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              drivers?: DriverPerformanceApiItem[];
              totalCount?: string | number;
          }
        | DriverPerformanceApiItem[];
    count?: number;
}

interface VehicleUtilizationResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              vehicles?: VehicleUtilizationApiItem[];
              totalCount?: string | number;
          }
        | VehicleUtilizationApiItem[];
    count?: number;
}

interface PaymentCollectionSummaryResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              payments?: PaymentCollectionSummaryApiItem[];
              totalCount?: string | number;
          }
        | PaymentCollectionSummaryApiItem[];
    count?: number;
}

interface PendingPaymentsOutstandingResponse {
    success?: boolean;
    code?: number;
    message?: string;
    data?:
        | {
              invoices?: PendingPaymentsOutstandingApiItem[];
              totalCount?: string | number;
          }
        | PendingPaymentsOutstandingApiItem[];
    count?: number;
}

interface ReportsState {
    tripSummary: {
        items: TripSummaryApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    dispatcherPerformance: {
        items: DispatcherPerformanceApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    hospitalReport: {
        items: HospitalReportApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    customerTransportHistory: {
        items: CustomerTransportHistoryApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    driverPerformance: {
        items: DriverPerformanceApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    vehicleUtilization: {
        items: VehicleUtilizationApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    paymentCollectionSummary: {
        items: PaymentCollectionSummaryApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
    pendingPaymentsOutstanding: {
        items: PendingPaymentsOutstandingApiItem[];
        totalCount: number;
        status: 'idle' | 'loading' | 'succeeded' | 'failed';
        error: string | null;
    };
}

const initialState: ReportsState = {
    tripSummary: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    dispatcherPerformance: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    hospitalReport: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    customerTransportHistory: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    driverPerformance: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    vehicleUtilization: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    paymentCollectionSummary: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
    pendingPaymentsOutstanding: {
        items: [],
        totalCount: 0,
        status: 'idle',
        error: null,
    },
};

export const fetchTripSummary = createAsyncThunk(
    'reports/fetchTripSummary',
    async (
        params:
            | {
                  search?: string;
                  start_date?: string;
                  end_date?: string;
                  status?: string;
                  skip?: number;
                  limit?: number;
                  is_export?: 'true';
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/trip-summary', { params });
            return response.data as TripSummaryResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_trip_summary;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchDispatcherPerformance = createAsyncThunk(
    'reports/fetchDispatcherPerformance',
    async (
        params:
            | {
                  search?: string;
                  start_date?: string;
                  end_date?: string;
                  dispatcher_id?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: 'true';
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/dispatcher-performance', { params });
            return response.data as DispatcherPerformanceResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_dispatcher_performance;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchHospitalReport = createAsyncThunk(
    'reports/fetchHospitalReport',
    async (
        params:
            | {
                  search?: string;
                  skip?: string;
                  limit?: string;
                  state?: string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/hospital-report', { params });
            return response.data as HospitalReportResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_hospital_report;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchCustomerTransportHistory = createAsyncThunk(
    'reports/fetchCustomerTransportHistory',
    async (
        params:
            | {
                  search?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/customer-transport-history', { params });
            return response.data as CustomerTransportHistoryResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_customer_transport_history;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchDriverPerformance = createAsyncThunk(
    'reports/fetchDriverPerformance',
    async (
        params:
            | {
                  search?: string;
                  start_date?: string;
                  end_date?: string;
                  driver_id?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: boolean | string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/driver-performance', { params });
            return response.data as DriverPerformanceResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_driver_performance;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchVehicleUtilization = createAsyncThunk(
    'reports/fetchVehicleUtilization',
    async (
        params:
            | {
                  search?: string;
                  state?: string;
                  vehicle_type?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: boolean | string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/vehicle-utilization', { params });
            return response.data as VehicleUtilizationResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_vehicle_utilization;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchPaymentCollectionSummary = createAsyncThunk(
    'reports/fetchPaymentCollectionSummary',
    async (
        params:
            | {
                  search?: string;
                  start_date?: string;
                  end_date?: string;
                  payment_type?: string;
                  client_id?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: boolean | string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/payment-collection-summary', { params });
            return response.data as PaymentCollectionSummaryResponse;
        } catch (err: any) {
            const errorMessage = err?.response?.data?.message || messages.toasts.error.failed_to_fetch_payment_collection_summary;
            return rejectWithValue(errorMessage);
        }
    },
);

export const fetchPendingPaymentsOutstanding = createAsyncThunk(
    'reports/fetchPendingPaymentsOutstanding',
    async (
        params:
            | {
                  search?: string;
                  start_date?: string;
                  end_date?: string;
                  client_id?: string;
                  trip_type?: string;
                  skip?: string;
                  limit?: string;
                  is_export?: boolean | string;
              }
            | undefined,
        { rejectWithValue },
    ) => {
        try {
            const response = await api.get('/report/pending-payments-outstanding', { params });
            return response.data as PendingPaymentsOutstandingResponse;
        } catch (err: any) {
            const errorMessage =
                err?.response?.data?.message || messages.toasts.error.failed_to_fetch_pending_payments_outstanding;
            return rejectWithValue(errorMessage);
        }
    },
);

const reportsSlice = createSlice({
    name: 'reports',
    initialState,
    reducers: {
        clearTripSummary(state) {
            state.tripSummary.items = [];
            state.tripSummary.totalCount = 0;
            state.tripSummary.status = 'idle';
            state.tripSummary.error = null;
        },
        clearDispatcherPerformance(state) {
            state.dispatcherPerformance.items = [];
            state.dispatcherPerformance.totalCount = 0;
            state.dispatcherPerformance.status = 'idle';
            state.dispatcherPerformance.error = null;
        },
        clearHospitalReport(state) {
            state.hospitalReport.items = [];
            state.hospitalReport.totalCount = 0;
            state.hospitalReport.status = 'idle';
            state.hospitalReport.error = null;
        },
        clearCustomerTransportHistory(state) {
            state.customerTransportHistory.items = [];
            state.customerTransportHistory.totalCount = 0;
            state.customerTransportHistory.status = 'idle';
            state.customerTransportHistory.error = null;
        },
        clearDriverPerformance(state) {
            state.driverPerformance.items = [];
            state.driverPerformance.totalCount = 0;
            state.driverPerformance.status = 'idle';
            state.driverPerformance.error = null;
        },
        clearVehicleUtilization(state) {
            state.vehicleUtilization.items = [];
            state.vehicleUtilization.totalCount = 0;
            state.vehicleUtilization.status = 'idle';
            state.vehicleUtilization.error = null;
        },
        clearPaymentCollectionSummary(state) {
            state.paymentCollectionSummary.items = [];
            state.paymentCollectionSummary.totalCount = 0;
            state.paymentCollectionSummary.status = 'idle';
            state.paymentCollectionSummary.error = null;
        },
        clearPendingPaymentsOutstanding(state) {
            state.pendingPaymentsOutstanding.items = [];
            state.pendingPaymentsOutstanding.totalCount = 0;
            state.pendingPaymentsOutstanding.status = 'idle';
            state.pendingPaymentsOutstanding.error = null;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchTripSummary.pending, (state) => {
                state.tripSummary.status = 'loading';
                state.tripSummary.error = null;
            })
            .addCase(fetchTripSummary.fulfilled, (state, action: PayloadAction<TripSummaryResponse>) => {
                state.tripSummary.status = 'succeeded';

                const payload = action.payload;

                let itemsArray: TripSummaryApiItem[] = [];
                let countValue: number = 0;

                if (payload?.data) {
                    if ((payload.data as any)?.trip && Array.isArray((payload.data as any).trip)) {
                        itemsArray = (payload.data as any).trip as TripSummaryApiItem[];
                        countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if ((payload.data as any)?.data && Array.isArray((payload.data as any).data)) {
                        itemsArray = (payload.data as any).data as TripSummaryApiItem[];
                        countValue =
                            Number((payload.data as any).count) || Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if (Array.isArray(payload.data)) {
                        itemsArray = payload.data as TripSummaryApiItem[];
                        countValue = Number(payload?.count) || itemsArray.length;
                    }
                }

                state.tripSummary.items = [...itemsArray];
                state.tripSummary.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
            })
            .addCase(fetchTripSummary.rejected, (state, action) => {
                state.tripSummary.status = 'failed';
                state.tripSummary.error = (action.payload as string) || 'Failed to fetch trip summary';
            })
            .addCase(fetchDispatcherPerformance.pending, (state) => {
                state.dispatcherPerformance.status = 'loading';
                state.dispatcherPerformance.error = null;
            })
            .addCase(fetchDispatcherPerformance.fulfilled, (state, action: PayloadAction<DispatcherPerformanceResponse>) => {
                state.dispatcherPerformance.status = 'succeeded';

                const payload = action.payload;

                let itemsArray: DispatcherPerformanceApiItem[] = [];
                let countValue: number = 0;

                if (payload?.data) {
                    if ((payload.data as any)?.dispatchers && Array.isArray((payload.data as any).dispatchers)) {
                        itemsArray = (payload.data as any).dispatchers as DispatcherPerformanceApiItem[];
                        countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if (Array.isArray(payload.data)) {
                        itemsArray = payload.data as DispatcherPerformanceApiItem[];
                        countValue = Number(payload?.count) || itemsArray.length;
                    }
                }

                state.dispatcherPerformance.items = [...itemsArray];
                state.dispatcherPerformance.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
            })
            .addCase(fetchDispatcherPerformance.rejected, (state, action) => {
                state.dispatcherPerformance.status = 'failed';
                state.dispatcherPerformance.error = (action.payload as string) || 'Failed to fetch dispatcher performance';
            })
            .addCase(fetchHospitalReport.pending, (state) => {
                state.hospitalReport.status = 'loading';
                state.hospitalReport.error = null;
            })
            .addCase(fetchHospitalReport.fulfilled, (state, action: PayloadAction<HospitalReportResponse>) => {
                state.hospitalReport.status = 'succeeded';

                const payload = action.payload;

                let itemsArray: HospitalReportApiItem[] = [];
                let countValue: number = 0;

                if (payload?.data) {
                    if ((payload.data as any)?.hospitals && Array.isArray((payload.data as any).hospitals)) {
                        itemsArray = (payload.data as any).hospitals as HospitalReportApiItem[];
                        countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if (Array.isArray(payload.data)) {
                        itemsArray = payload.data as HospitalReportApiItem[];
                        countValue = Number(payload?.count) || itemsArray.length;
                    }
                }

                state.hospitalReport.items = [...itemsArray];
                state.hospitalReport.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
            })
            .addCase(fetchHospitalReport.rejected, (state, action) => {
                state.hospitalReport.status = 'failed';
                state.hospitalReport.error = (action.payload as string) || 'Failed to fetch hospital report';
            })
            .addCase(fetchCustomerTransportHistory.pending, (state) => {
                state.customerTransportHistory.status = 'loading';
                state.customerTransportHistory.error = null;
            })
            .addCase(
                fetchCustomerTransportHistory.fulfilled,
                (state, action: PayloadAction<CustomerTransportHistoryResponse>) => {
                    state.customerTransportHistory.status = 'succeeded';

                    const payload = action.payload;

                    let itemsArray: CustomerTransportHistoryApiItem[] = [];
                    let countValue: number = 0;

                    if (payload?.data) {
                        if ((payload.data as any)?.customers && Array.isArray((payload.data as any).customers)) {
                            itemsArray = (payload.data as any).customers as CustomerTransportHistoryApiItem[];
                            countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                        } else if (Array.isArray(payload.data)) {
                            itemsArray = payload.data as CustomerTransportHistoryApiItem[];
                            countValue = Number(payload?.count) || itemsArray.length;
                        }
                    }

                    state.customerTransportHistory.items = [...itemsArray];
                    state.customerTransportHistory.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
                },
            )
            .addCase(fetchCustomerTransportHistory.rejected, (state, action) => {
                state.customerTransportHistory.status = 'failed';
                state.customerTransportHistory.error = (action.payload as string) || 'Failed to fetch customer transport history';
            })
            .addCase(fetchDriverPerformance.pending, (state) => {
                state.driverPerformance.status = 'loading';
                state.driverPerformance.error = null;
            })
            .addCase(fetchDriverPerformance.fulfilled, (state, action: PayloadAction<DriverPerformanceResponse>) => {
                state.driverPerformance.status = 'succeeded';

                const payload = action.payload;

                let itemsArray: DriverPerformanceApiItem[] = [];
                let countValue: number = 0;

                if (payload?.data) {
                    if ((payload.data as any)?.drivers && Array.isArray((payload.data as any).drivers)) {
                        itemsArray = (payload.data as any).drivers as DriverPerformanceApiItem[];
                        countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if (Array.isArray(payload.data)) {
                        itemsArray = payload.data as DriverPerformanceApiItem[];
                        countValue = Number(payload?.count) || itemsArray.length;
                    }
                }

                state.driverPerformance.items = [...itemsArray];
                state.driverPerformance.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
            })
            .addCase(fetchDriverPerformance.rejected, (state, action) => {
                state.driverPerformance.status = 'failed';
                state.driverPerformance.error = (action.payload as string) || 'Failed to fetch driver performance';
            })
            .addCase(fetchVehicleUtilization.pending, (state) => {
                state.vehicleUtilization.status = 'loading';
                state.vehicleUtilization.error = null;
            })
            .addCase(fetchVehicleUtilization.fulfilled, (state, action: PayloadAction<VehicleUtilizationResponse>) => {
                state.vehicleUtilization.status = 'succeeded';

                const payload = action.payload;

                let itemsArray: VehicleUtilizationApiItem[] = [];
                let countValue: number = 0;

                if (payload?.data) {
                    if ((payload.data as any)?.vehicles && Array.isArray((payload.data as any).vehicles)) {
                        itemsArray = (payload.data as any).vehicles as VehicleUtilizationApiItem[];
                        countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                    } else if (Array.isArray(payload.data)) {
                        itemsArray = payload.data as VehicleUtilizationApiItem[];
                        countValue = Number(payload?.count) || itemsArray.length;
                    }
                }

                state.vehicleUtilization.items = [...itemsArray];
                state.vehicleUtilization.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
            })
            .addCase(fetchVehicleUtilization.rejected, (state, action) => {
                state.vehicleUtilization.status = 'failed';
                state.vehicleUtilization.error = (action.payload as string) || 'Failed to fetch vehicle utilization';
            })
            .addCase(fetchPaymentCollectionSummary.pending, (state) => {
                state.paymentCollectionSummary.status = 'loading';
                state.paymentCollectionSummary.error = null;
            })
            .addCase(
                fetchPaymentCollectionSummary.fulfilled,
                (state, action: PayloadAction<PaymentCollectionSummaryResponse>) => {
                    state.paymentCollectionSummary.status = 'succeeded';

                    const payload = action.payload;

                    let itemsArray: PaymentCollectionSummaryApiItem[] = [];
                    let countValue: number = 0;

                    if (payload?.data) {
                        if ((payload.data as any)?.payments && Array.isArray((payload.data as any).payments)) {
                            itemsArray = (payload.data as any).payments as PaymentCollectionSummaryApiItem[];
                            countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                        } else if (Array.isArray(payload.data)) {
                            itemsArray = payload.data as PaymentCollectionSummaryApiItem[];
                            countValue = Number(payload?.count) || itemsArray.length;
                        }
                    }

                    state.paymentCollectionSummary.items = [...itemsArray];
                    state.paymentCollectionSummary.totalCount = countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
                },
            )
            .addCase(fetchPaymentCollectionSummary.rejected, (state, action) => {
                state.paymentCollectionSummary.status = 'failed';
                state.paymentCollectionSummary.error = (action.payload as string) || 'Failed to fetch payment collection summary';
            })
            .addCase(fetchPendingPaymentsOutstanding.pending, (state) => {
                state.pendingPaymentsOutstanding.status = 'loading';
                state.pendingPaymentsOutstanding.error = null;
            })
            .addCase(
                fetchPendingPaymentsOutstanding.fulfilled,
                (state, action: PayloadAction<PendingPaymentsOutstandingResponse>) => {
                    state.pendingPaymentsOutstanding.status = 'succeeded';

                    const payload = action.payload;

                    let itemsArray: PendingPaymentsOutstandingApiItem[] = [];
                    let countValue: number = 0;

                    if (payload?.data) {
                        if ((payload.data as any)?.invoices && Array.isArray((payload.data as any).invoices)) {
                            itemsArray = (payload.data as any).invoices as PendingPaymentsOutstandingApiItem[];
                            countValue = Number((payload.data as any).totalCount) || itemsArray.length;
                        } else if (Array.isArray(payload.data)) {
                            itemsArray = payload.data as PendingPaymentsOutstandingApiItem[];
                            countValue = Number(payload?.count) || itemsArray.length;
                        }
                    }

                    state.pendingPaymentsOutstanding.items = [...itemsArray];
                    state.pendingPaymentsOutstanding.totalCount =
                        countValue || (Array.isArray(itemsArray) ? itemsArray.length : 0);
                },
            )
            .addCase(fetchPendingPaymentsOutstanding.rejected, (state, action) => {
                state.pendingPaymentsOutstanding.status = 'failed';
                state.pendingPaymentsOutstanding.error =
                    (action.payload as string) || 'Failed to fetch pending payments outstanding';
            });
    },
});

export const {
    clearTripSummary,
    clearDispatcherPerformance,
    clearHospitalReport,
    clearCustomerTransportHistory,
    clearDriverPerformance,
    clearVehicleUtilization,
    clearPaymentCollectionSummary,
    clearPendingPaymentsOutstanding,
} = reportsSlice.actions;
export default reportsSlice.reducer;
