import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { vehicleIncidentEndpoints } from '../../endpoints/fleet-service/vehicle-incident-endpoints';
import { VehicleIncidentRequest, VehicleIncident, VehicleIncidentPageFilterParams, IncidentStatus } from '@/shared/types/fleet-management/vehicle-incident';

type VehicleIncidentStore = {
    error: string | null;
    loading: boolean;
    vehicleIncidentsPage: VehicleIncident[];
    totalElements: number;
    incidentById: VehicleIncident | null;
    lastUsedVehicleIncidentsParams: VehicleIncidentPageFilterParams | null;

    fetchVehicleIncidentsPage: (params: VehicleIncidentPageFilterParams) => Promise<void>;
    getVehicleIncidentById: (id: string | number) => Promise<VehicleIncident | null>;
    createVehicleIncident: (data: VehicleIncidentRequest) => Promise<void>;
    updateVehicleIncident: (id: string | number, data: VehicleIncidentRequest) => Promise<void>;
    toggleActive: (id: string | number, active: boolean) => Promise<void>;
    toggleStatus: (id: string | number, status: IncidentStatus) => Promise<void>;
    startCsvExport: (userId: string | number, params: VehicleIncidentPageFilterParams) => Promise<void>;
    downloadCsvExport: (filePath: string) => Promise<void>;
};

export const useVehicleIncidentStore = create<VehicleIncidentStore>((set, get) => ({
    error: null,
    loading: false,
    vehicleIncidentsPage: [],
    totalElements: 0,
    incidentById: null,
    lastUsedVehicleIncidentsParams: null,

    fetchVehicleIncidentsPage: async (params) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(vehicleIncidentEndpoints.getPage, { params });
            set({
                vehicleIncidentsPage: response.data.content,
                totalElements: response.data.totalElements,
                loading: false,
            });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    getVehicleIncidentById: async (id) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(vehicleIncidentEndpoints.getById(id));
            set({ incidentById: response.data, loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    createVehicleIncident: async (data) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(vehicleIncidentEndpoints.create, data);
            const { lastUsedVehicleIncidentsParams, fetchVehicleIncidentsPage } = get();
            if (lastUsedVehicleIncidentsParams) {
                await fetchVehicleIncidentsPage(lastUsedVehicleIncidentsParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    updateVehicleIncident: async (id, data) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(vehicleIncidentEndpoints.update(id), data);
            const { lastUsedVehicleIncidentsParams, fetchVehicleIncidentsPage } = get();
            if (lastUsedVehicleIncidentsParams) {
                await fetchVehicleIncidentsPage(lastUsedVehicleIncidentsParams);
            }
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    toggleActive: async (id, active) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.patch(vehicleIncidentEndpoints.toggleActive(id), null, { params: { active } });
            const { vehicleIncidentsPage } = get();
            set({
                vehicleIncidentsPage: vehicleIncidentsPage.map((vi) =>
                    vi.id === id ? { ...vi, active } : vi
                ),
                loading: false
            });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    toggleStatus: async (id, status) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.patch(vehicleIncidentEndpoints.toggleStatus(id), null, { params: { status } });
            const { vehicleIncidentsPage } = get();
            set({
                vehicleIncidentsPage: vehicleIncidentsPage.map((vi) =>
                    vi.id === id ? { ...vi, status } : vi
                ),
                loading: false
            });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    startCsvExport: async (userId, params) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.get(vehicleIncidentEndpoints.startCsvExport, {
                params: { ...params, userId },
            });
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },

    downloadCsvExport: async (filePath) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.get(vehicleIncidentEndpoints.downloadCsvExport, {
                params: { filePath },
                responseType: 'blob',
            });
            set({ loading: false });
        } catch (error: any) {
            set({ error: error.message, loading: false });
            throw error;
        }
    },
}));