import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { FuelType, FuelTypePageFilterParams } from '@/shared/types/fleet-management/fuelType';
import { fuelTypeEndpoints } from '../../endpoints/fleet-service/fuel-type-endpoints';


type FuelTypeStore = {
    loading: boolean;
    error: string | null;
    fuelTypesPage: FuelType[];
    totalElements: number;
    lastParams: FuelTypePageFilterParams | null;
    fuelTypeById: FuelType | null;
    existsFuelTypeByNameLoading: boolean;

    fetchFuelTypesPage: (params?: FuelTypePageFilterParams) => Promise<void>;
    getFuelTypeById: (id: string) => Promise<FuelType | null>;
    createFuelType: (fuelType: FuelType) => Promise<void>;
    updateFuelType: (id: string, fuelType: FuelType) => Promise<void>;
    toggleFuelTypeActive: (id: string, active: boolean) => Promise<void>;
    startExportFiltredFuelTypes: (userId: string, params?: FuelTypePageFilterParams) => Promise<void>;
    existsFuelTypeByName: (name: string, excludeId?: number) => Promise<boolean>;
    fetchAllFuelTypes: (active?: boolean) => Promise<FuelType[]>;
};

export const useFuelTypeStore = create<FuelTypeStore>((set, get) => ({
    loading: false,
    error: null,
    fuelTypesPage: [],
    totalElements: 0,
    lastParams: null,
    fuelTypeById: null,
    existsFuelTypeByNameLoading: false,

    fetchFuelTypesPage: async (params) => {
        set({ loading: true, error: null, lastParams: params });
        try {
            const res = await axiosInstance.get(fuelTypeEndpoints.getFuelTypesPage, { params });
            const { content, totalElements } = res.data;
            set({ fuelTypesPage: content, totalElements, loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch fuel types', loading: false });
            throw err;
        }
    },

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

    createFuelType: async (fuelType) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(fuelTypeEndpoints.createFuelType, fuelType);
            const { lastParams, fetchFuelTypesPage } = get();
            if (lastParams) await fetchFuelTypesPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to create fuel type', loading: false });
            throw err;
        }
    },

    updateFuelType: async (id, fuelType) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(fuelTypeEndpoints.updateFuelType(id), fuelType);
            const { lastParams, fetchFuelTypesPage } = get();
            if (lastParams) await fetchFuelTypesPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to update fuel type', loading: false });
            throw err;
        }
    },

    toggleFuelTypeActive: async (id, active) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.patch(fuelTypeEndpoints.toggleFuelTypeActive(id), null, { params: { active } });
            const { fuelTypesPage } = get();
            set({
                fuelTypesPage: fuelTypesPage.map((f) => (f.id === id ? { ...f, active } : f)),
                loading: false,
            });
        } catch (err: any) {
            set({ error: err.message || 'Failed to toggle fuel type', loading: false });
            throw err;
        }
    },

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

    existsFuelTypeByName: async (name: string, excludeId?: number) => {
        set({ existsFuelTypeByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get(
                fuelTypeEndpoints.existsFuelTypeByName,
                { 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({ existsFuelTypeByNameLoading: false });
        }
    },

    fetchAllFuelTypes: async (active?: boolean): Promise<FuelType[]> => {
        set({ loading: true, error: null });
        try {
            const res = await axiosInstance.get(fuelTypeEndpoints.getAllFuelTypes, { params: { active } });
            set({ loading: false });
            return res.data;
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch all fuel types', loading: false });
            throw err;
            return [];
        }
    }
}));