import { create } from "zustand"
import axiosInstance from "@/utils/axios"
import { vehicleRepairEndpoints } from "../../endpoints/fleet-service/vehicle-repair-endpoints"
import type {
  VehicleRepairListResponse,
  VehicleRepairRequest,
  RepairStatus,
  VehicleRepairPageFilterParams,
  VehicleRepair,
} from "@/shared/types/fleet-management/vehicle-repair"

type VehicleRepairStore = {
  error: string | null
  loading: boolean
  repairsPage: VehicleRepairListResponse[]
  totalElements: number
  repairById: VehicleRepair | null

  fetchRepairsPage: (params: VehicleRepairPageFilterParams) => Promise<void>
  getRepairById: (id: string) => Promise<VehicleRepair | null>
  createRepair: (data: VehicleRepairRequest) => Promise<void>
  updateRepair: (id: string, data: VehicleRepairRequest) => Promise<void>
  setStatus: (id: string, status: RepairStatus) => Promise<void>
  acceptQuote: (id: string, accepted: boolean) => Promise<void>
  recordCosts: (
    id: string,
    costHT: number,
    costTTC: number,
    invoiceNumber: string,
    invoiceDate: string,
  ) => Promise<void>
  setImmobilization: (id: string, start: string, end: string) => Promise<void>
  toggleActive: (id: string) => Promise<void>
  deleteRepair: (id: string) => Promise<void>
  getOpenRepairsByVehicle: (vehicleId: string) => Promise<VehicleRepairListResponse[]>
  startCsvExport: (userId: string, params: any) => Promise<void>
  downloadCsvExport: (filePath: string) => Promise<void>
}

export const useVehicleRepairStore = create<VehicleRepairStore>((set) => ({
  error: null,
  loading: false,
  repairsPage: [],
  totalElements: 0,
  repairById: null,

  fetchRepairsPage: async (params: VehicleRepairPageFilterParams) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get(vehicleRepairEndpoints.getPage, { params })
      set({
        repairsPage: response.data.content,
        totalElements: response.data.totalElements,
        loading: false,
      })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  getRepairById: async (id: string) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get(vehicleRepairEndpoints.getById(id))
      set({ repairById: response.data, loading: false })
      return response.data
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  createRepair: async (data) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.post(vehicleRepairEndpoints.create, data)
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  updateRepair: async (id, data) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.put(vehicleRepairEndpoints.update(id), data)
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  setStatus: async (id, status) => {
    try {
      await axiosInstance.put(vehicleRepairEndpoints.setStatus(id), { status })
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  acceptQuote: async (id, accepted) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.put(vehicleRepairEndpoints.acceptQuote(id), { accepted })
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  recordCosts: async (id, costHT, costTTC, invoiceNumber, invoiceDate) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.put(vehicleRepairEndpoints.recordCosts(id), {
        costHT,
        costTTC,
        invoiceNumber,
        invoiceDate,
      })
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  setImmobilization: async (id, start, end) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.put(vehicleRepairEndpoints.setImmobilization(id), { start, end })
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  toggleActive: async (id) => {
    try {
      await axiosInstance.put(vehicleRepairEndpoints.toggleActive(id))
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  deleteRepair: async (id) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.delete(vehicleRepairEndpoints.delete(id))
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  getOpenRepairsByVehicle: async (vehicleId: string) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get(vehicleRepairEndpoints.getOpenByVehicle(vehicleId))
      set({ loading: false })
      return response.data
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },

  startCsvExport: async (userId, params) => {
    set({ loading: true, error: null })
    try {
      await axiosInstance.get(vehicleRepairEndpoints.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(vehicleRepairEndpoints.downloadCsvExport, {
        params: { filePath },
        responseType: "blob",
      })
      set({ loading: false })
    } catch (error: any) {
      set({ error: error.message, loading: false })
      throw error
    }
  },
}))
