import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { serviceProviderEndpoints } from '../../endpoints/fleet-service/service-provider-endpoints';
import { ServiceProvider, ServiceProviderPageFilterParams, ServiceProviderRequest } from '@/shared/types/fleet-management/service-provider';

type ServiceProviderStore = {
    loading: boolean;
    error: string | null;
    serviceProvidersPage: ServiceProvider[];
    totalElements: number;
    lastParams: ServiceProviderPageFilterParams | null;
    serviceProviderById: ServiceProvider | null;
    existsByNameLoading: boolean;
    allServiceProviders: ServiceProvider[];

    fetchServiceProvidersPage: (params?: ServiceProviderPageFilterParams) => Promise<void>;
    getServiceProviderById: (id: string) => Promise<ServiceProvider | null>;
    createServiceProvider: (serviceProvider: ServiceProviderRequest) => Promise<void>;
    updateServiceProvider: (id: string, serviceProvider: ServiceProviderRequest) => Promise<void>;
    toggleActive: (id: string, active: boolean) => Promise<void>;
    fetchAllServiceProviders: () => Promise<ServiceProvider[]>;
    existsByName: (name: string, excludeId?: number) => Promise<boolean>;
    startCsvExportFiltredServiceProviders: (userId: number, params?: ServiceProviderPageFilterParams) => Promise<any>;
    downloadCsvExport: (filePath: string) => Promise<Blob>;
};

export const useServiceProviderStore = create<ServiceProviderStore>((set, get) => ({
    loading: false,
    error: null,
    serviceProvidersPage: [],
    totalElements: 0,
    lastParams: null,
    serviceProviderById: null,
    existsByNameLoading: false,
    allServiceProviders: [],

    fetchServiceProvidersPage: async (params) => {
        set({ loading: true, error: null, lastParams: params });
        try {
            const res = await axiosInstance.get(serviceProviderEndpoints.getServiceProvidersPage, { params });
            const { content, totalElements } = res.data;
            set({ serviceProvidersPage: content, totalElements, loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch service providers', loading: false });
            throw err;
        }
    },

    getServiceProviderById: async (id) => {
        set({ loading: true, error: null });
        try {
            const res = await axiosInstance.get(serviceProviderEndpoints.getServiceProviderById(id));
            set({ serviceProviderById: res.data, loading: false });
            return res.data;
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch service provider', loading: false });
            throw err;
        }
    },

    createServiceProvider: async (serviceProvider) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.post(serviceProviderEndpoints.createServiceProvider, serviceProvider);
            const { lastParams, fetchServiceProvidersPage } = get();
            if (lastParams) await fetchServiceProvidersPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to create service provider', loading: false });
            throw err;
        }
    },

    updateServiceProvider: async (id, serviceProvider) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.put(serviceProviderEndpoints.updateServiceProvider(id), serviceProvider);
            const { lastParams, fetchServiceProvidersPage } = get();
            if (lastParams) await fetchServiceProvidersPage(lastParams);
            set({ loading: false });
        } catch (err: any) {
            set({ error: err.message || 'Failed to update service provider', loading: false });
            throw err;
        }
    },

    toggleActive: async (id: string, active: boolean) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.patch(serviceProviderEndpoints.toggleActive(id), null, {
                params: {
                    active
                }
            });
            const { serviceProvidersPage } = get();
            set({
                serviceProvidersPage: serviceProvidersPage.map((sp) =>
                    sp.id === id ? { ...sp, active } : sp
                ),
                loading: false
            });
        } catch (err: any) {
            set({ error: err.message || 'Failed to toggle active status for service provider', loading: false });
            throw err;
        }
    },

    fetchAllServiceProviders: async (): Promise<ServiceProvider[]> => {
        set({ loading: true, error: null });
        try {
            const res = await axiosInstance.get(serviceProviderEndpoints.getAllServiceProviders);
            set({ allServiceProviders: res.data, loading: false });
            return res.data;
        } catch (err: any) {
            set({ error: err.message || 'Failed to fetch all service providers', loading: false });
            throw err;
        }
    },

    existsByName: async (name, excludeId) => {
        set({ existsByNameLoading: true, error: null });
        try {
            const response = await axiosInstance.get(serviceProviderEndpoints.existsByName, {
                params: { name, excludeId }
            });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to check if service provider exists by name' });
            throw error;
        } finally {
            set({ existsByNameLoading: false });
        }
    },

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

    downloadCsvExport: async (filePath: string) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(serviceProviderEndpoints.downloadCsvExport, {
                params: { filePath },
                responseType: 'blob'
            });
            set({ loading: false });
            return response.data;
        } catch (error: any) {
            set({ error: error.message || 'Failed to download service providers CSV export', loading: false });
            throw error;
        }
    },
}));