import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import {
    VehicleType,
    VehicleTypePageFilterParams,
} from '@/shared/types/fleet-management/vehicleType';
import { vehicleTypeEndpoints } from '../../endpoints/fleet-service/vehicle-type-endpoints';

type VehicleTypeStore = {
    loading: boolean;
    error: string | null;
    vehicleTypesPage: VehicleType[];
    allVehicleTypes: VehicleType[];
    totalElements: number;
    lastParams: VehicleTypePageFilterParams | null;
    vehicleTypeById: VehicleType | null;
    existsByNameLoading: boolean;

    fetchVehicleTypesPage: (params?: VehicleTypePageFilterParams) => Promise<void>;
    getVehicleTypeById: (id: string) => Promise<VehicleType | null>;
    createVehicleType: (dto: VehicleType) => Promise<void>;
    updateVehicleType: (id: string, dto: VehicleType) => Promise<void>;
    toggleVehicleTypeActive: (id: string, active: boolean) => Promise<void>;
    fetchAllVehicleTypes: (active?: boolean) => Promise<void>;
    startExportFiltredVehicleTypes: (userId: string, params?: VehicleTypePageFilterParams) => Promise<void>;
    existsByName: (name: string, excludeId?: number) => Promise<boolean>;
};

export const useVehicleTypeStore = create<VehicleTypeStore>((set, get) => ({
    loading: false,
    error: null,
    vehicleTypesPage: [],
    allVehicleTypes: [],
    totalElements: 0,
    lastParams: null,
    vehicleTypeById: null,
    existsByNameLoading: false,

    fetchVehicleTypesPage: async (params) => {
        set({ loading: true, error: null, lastParams: params });
        try {
            const res = await axiosInstance.get(vehicleTypeEndpoints.getPage, { params });
            const { content, totalElements } = res.data;
            set({ vehicleTypesPage: content, totalElements, loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch vehicle types', loading: false });
            throw err;
        }
    },

    getVehicleTypeById: async (id) => {
        set({ loading: true, error: null });
        try {
            const res = await axiosInstance.get(vehicleTypeEndpoints.getById(id));
            set({ vehicleTypeById: res.data, loading: false });
            return res.data;
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch vehicle type', loading: false });
            throw err;
        }
    },

    createVehicleType: async (dto) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(vehicleTypeEndpoints.create, dto);
            const { lastParams, fetchVehicleTypesPage } = get();
            if (lastParams) await fetchVehicleTypesPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to create vehicle type', loading: false });
            throw err;
        }
    },

    updateVehicleType: async (id, dto) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(vehicleTypeEndpoints.update(id), dto);
            const { lastParams, fetchVehicleTypesPage } = get();
            if (lastParams) await fetchVehicleTypesPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to update vehicle type', loading: false });
            throw err;
        }
    },

    toggleVehicleTypeActive: async (id, active) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.patch(vehicleTypeEndpoints.toggleActive(id), null, { params: { active } });
            const { vehicleTypesPage } = get();
            set({
                vehicleTypesPage: vehicleTypesPage.map((v) =>
                    v.id === id ? { ...v, active } : v
                ),
                loading: false,
            });
        } catch (err: any) {
            set({ error: err.message || 'Failed to toggle vehicle type', loading: false });
            throw err;
        }
    },

    fetchAllVehicleTypes: async (active?: boolean) => {
        set({ loading: true, error: null });
        try {
            const res = await axiosInstance.get(vehicleTypeEndpoints.getAll, { params: { active } });
            set({ allVehicleTypes: res.data, loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch all vehicle types', loading: false });
            throw err;
        }
    },

    startExportFiltredVehicleTypes: async (userId, params) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(vehicleTypeEndpoints.startCsvExport, { 
                params: {
                    ...params,
                    userId: userId
                } 
            });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to start export vehicle types', loading: false });
            throw error;
        }
    },

    existsByName: async (name: string, excludeId?: number) => {
        set({ existsByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get(
                vehicleTypeEndpoints.existsByName,
                { params: { name, excludeId } }
            );
            return response.data;
        } catch (error: any) {
            set({
                error: error.message || "Failed to check if contract exists by title",
            });
            throw error;
        } finally {
            set({ existsByNameLoading: false });
        }
    }
}));