import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { interventionEndpoints } from '../../endpoints/fleet-service/intervention-endpoints';
import { Intervention, InterventionPageFilterParams } from '@/shared/types/fleet-management/service-provider';

type InterventionStore = {
  loading: boolean;
  error: string | null;
  interventionsPage: Intervention[];
  totalElements: number;
  lastParams: InterventionPageFilterParams | null;
  interventionById: Intervention | null;
  existsByNameLoading: boolean;
  allInterventions: Intervention[];

  fetchInterventionsPage: (params?: InterventionPageFilterParams) => Promise<void>;
  getInterventionById: (id: string) => Promise<Intervention | null>;
  createIntervention: (intervention: Intervention) => Promise<void>;
  updateIntervention: (id: string, intervention: Intervention) => Promise<void>;
  fetchAllInterventions: () => Promise<Intervention[]>;
  existsByName: (name: string, excludeId?: number) => Promise<boolean>;
  startCsvExportFiltredInterventions: (userId: number, params?: InterventionPageFilterParams) => Promise<any>;
  downloadCsvExport: (filePath: string) => Promise<Blob>;
};

export const useInterventionStore = create<InterventionStore>((set, get) => ({
  loading: false,
  error: null,
  interventionsPage: [],
  totalElements: 0,
  lastParams: null,
  interventionById: null,
  existsByNameLoading: false,
  allInterventions: [],

  fetchInterventionsPage: async (params) => {
    set({ loading: true, error: null, lastParams: params });
    try {
      const res = await axiosInstance.get(interventionEndpoints.getInterventionsPage, { params });
      const { content, totalElements } = res.data;
      set({ interventionsPage: content, totalElements, loading: false });
    } catch (err: any) {
      set({ error: err.message || 'Failed to fetch interventions', loading: false });
      throw err;
    }
  },

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

  createIntervention: async (intervention) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.post(interventionEndpoints.createIntervention, intervention);
      const { lastParams, fetchInterventionsPage } = get();
      if (lastParams) await fetchInterventionsPage(lastParams);
      set({ loading: false });
    } catch (err: any) {
      set({ error: err.message || 'Failed to create intervention', loading: false });
      throw err;
    }
  },

  updateIntervention: async (id, intervention) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.put(interventionEndpoints.updateIntervention(id), intervention);
      const { lastParams, fetchInterventionsPage } = get();
      if (lastParams) await fetchInterventionsPage(lastParams);
      set({ loading: false });
    } catch (err: any) {
      set({ error: err.message || 'Failed to update intervention', loading: false });
      throw err;
    }
  },

  fetchAllInterventions: async (): Promise<Intervention[]> => {
    set({ loading: true, error: null });
    try {
      const res = await axiosInstance.get(interventionEndpoints.getAllInterventions);
      set({ allInterventions: res.data, loading: false });
      return res.data;
    } catch (err: any) {
      set({ error: err.message || 'Failed to fetch all interventions', loading: false });
      throw err;
    }
  },

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

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

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