import { ref } from 'vue'
import { useToast } from './useToast'
import { useApi } from './useApi'
import { extractCollection } from '~/shared/utils/apiHelpers'

export interface Site {
  id: string
  name?: string
  color?: string
  contactName?: string
  contactPhone?: string
  contactAddress?: string
  contactPostalCode?: string
  contactCity?: string
  machines?: unknown[]
  documents?: unknown[]
  [key: string]: unknown
}

interface SiteResult {
  success: boolean
  data?: Site
  error?: string
}

const sites = ref<Site[]>([])
const loading = ref(false)
const loaded = ref(false)

export function useSites() {
  const { showSuccess } = useToast()
  const { get, post, patch, delete: del } = useApi()

  const loadSites = async (options: { force?: boolean } = {}): Promise<void> => {
    if (!options.force && loaded.value) return
    loading.value = true
    try {
      const result = await get('/sites')
      if (result.success) {
        const collection = extractCollection(result.data)
        sites.value = collection
        loaded.value = true
      }
    } catch (error) {
      console.error('Erreur lors du chargement des sites:', error)
    } finally {
      loading.value = false
    }
  }

  const createSite = async (siteData: Partial<Site>): Promise<SiteResult> => {
    loading.value = true
    try {
      const result = await post('/sites', siteData)
      if (result.success && result.data) {
        sites.value.push(result.data as Site)
        showSuccess(`Site "${siteData.name}" créé avec succès`)
      }
      return result as SiteResult
    } catch (error) {
      console.error('Erreur lors de la création du site:', error)
      return { success: false, error: (error as Error).message }
    } finally {
      loading.value = false
    }
  }

  const updateSite = async (id: string, siteData: Partial<Site>): Promise<SiteResult> => {
    loading.value = true
    try {
      const result = await patch(`/sites/${id}`, siteData)
      if (result.success && result.data) {
        const index = sites.value.findIndex((site) => site.id === id)
        if (index !== -1) {
          sites.value[index] = result.data as Site
        }
        showSuccess(`Site "${siteData.name}" mis à jour avec succès`)
      }
      return result as SiteResult
    } catch (error) {
      console.error('Erreur lors de la mise à jour du site:', error)
      return { success: false, error: (error as Error).message }
    } finally {
      loading.value = false
    }
  }

  const deleteSite = async (id: string): Promise<SiteResult> => {
    loading.value = true
    try {
      const result = await del(`/sites/${id}`)
      if (result.success) {
        const deletedSite = sites.value.find((site) => site.id === id)
        sites.value = sites.value.filter((site) => site.id !== id)
        showSuccess(`Site "${deletedSite?.name || 'inconnu'}" supprimé avec succès`)
      }
      return result as SiteResult
    } catch (error) {
      console.error('Erreur lors de la suppression du site:', error)
      return { success: false, error: (error as Error).message }
    } finally {
      loading.value = false
    }
  }

  const getSiteById = (id: string): Site | undefined => {
    return sites.value.find((site) => site.id === id)
  }

  const getSites = () => sites.value
  const isLoading = () => loading.value

  return {
    sites,
    loading,
    loadSites,
    createSite,
    updateSite,
    deleteSite,
    getSiteById,
    getSites,
    isLoading,
  }
}
