<template>
  <main class="container mx-auto px-6 py-8">
    <div class="my-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">
          Parc Machines
        </h2>
        <NuxtLink to="/machines/new" class="btn btn-primary">
          <IconLucidePlus class="w-5 h-5 mr-2" aria-hidden="true" />
          Ajouter une machine
        </NuxtLink>
      </div>

      <div class="card bg-base-100 shadow-lg mb-6">
        <div class="card-body">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Site</span>
              </label>
              <select v-model="selectedSite" class="select select-bordered">
                <option value="">
                  Tous les sites
                </option>
                <option v-for="site in sites" :key="site.id" :value="site.id">
                  {{ site.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Type de machine</span>
              </label>
              <select v-model="selectedType" class="select select-bordered">
                <option value="">
                  Tous les types
                </option>
                <option v-for="type in machineTypes" :key="type.id" :value="type.id">
                  {{ type.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Catégorie</span>
              </label>
              <select v-model="selectedCategory" class="select select-bordered">
                <option value="">
                  Toutes les catégories
                </option>
                <option v-for="category in categories" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <div v-if="loading" class="flex justify-center items-center py-12">
        <span class="loading loading-spinner loading-lg" />
      </div>

      <div v-else-if="filteredMachines.length === 0" class="text-center py-12">
        <div class="max-w-md mx-auto">
          <IconLucideFactory class="w-16 h-16 mx-auto text-gray-400 mb-4" aria-hidden="true" />
          <h3 class="text-lg font-medium text-gray-900 mb-2">
            Aucune machine trouvée
          </h3>
          <p class="text-gray-500 mb-4">
            Commencez par ajouter votre première machine.
          </p>
          <NuxtLink to="/machines/new" class="btn btn-primary">
            Ajouter une machine
          </NuxtLink>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="machine in filteredMachines"
          :key="machine.id"
          class="card bg-base-100 shadow-lg hover:shadow-xl transition-shadow cursor-pointer"
          @click="viewMachineDetails(machine)"
        >
          <div class="card-body">
            <div class="flex items-center justify-between mb-2">
              <h3 class="card-title text-lg">
                {{ machine.name }}
              </h3>
              <div class="badge badge-primary badge-sm">
                {{ machine.typeMachine?.category || 'N/A' }}
              </div>
            </div>

            <p class="text-sm text-gray-600 mb-3">
              {{ machine.description || machine.typeMachine?.description }}
            </p>

            <div class="space-y-2 text-sm">
              <div class="flex items-center gap-2">
                <IconLucideMapPin class="w-4 h-4 text-blue-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.site?.name || 'Site inconnu' }}</span>
              </div>

              <div class="flex items-center gap-2">
                <IconLucideSettings2 class="w-4 h-4 text-green-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.typeMachine?.name || 'Type inconnu' }}</span>
              </div>

              <div v-if="machine.reference" class="flex items-center gap-2">
                <IconLucideTag class="w-4 h-4 text-orange-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.reference }}</span>
              </div>
            </div>

            <div class="card-actions justify-end mt-4">
              <button class="btn btn-sm btn-outline" @click.stop="editMachine(machine)">
                Modifier
              </button>
              <button class="btn btn-sm btn-error" @click.stop="confirmDeleteMachine(machine)">
                Supprimer
              </button>
              <NuxtLink :to="`/machine/${machine.id}`" class="btn btn-sm btn-primary">
                Voir détails
              </NuxtLink>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useMachines } from '~/composables/useMachines'
import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useToast } from '~/composables/useToast'
import IconLucidePlus from '~icons/lucide/plus'
import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin'
import IconLucideSettings2 from '~icons/lucide/settings-2'
import IconLucideTag from '~icons/lucide/tag'

const { machines, loading, loadMachines, deleteMachine } = useMachines()
const { sites, loadSites } = useSites()
const { machineTypes, loadMachineTypes } = useMachineTypesApi()
const toast = useToast()

const selectedSite = ref('')
const selectedType = ref('')
const selectedCategory = ref('')

const categories = computed(() => {
  const cats = new Set()
  machineTypes.value.forEach((type) => {
    if (type.category) {
      cats.add(type.category)
    }
  })
  return Array.from(cats)
})

// Enrichir les machines avec les objets site et typeMachine complets
const enrichedMachines = computed(() => {
  return machines.value.map((machine) => {
    const site = sites.value.find(s => s.id === machine.siteId)
    const typeMachine = machineTypes.value.find(t => t.id === machine.typeMachineId)
    return {
      ...machine,
      site: site || null,
      typeMachine: typeMachine || null
    }
  })
})

const filteredMachines = computed(() => {
  let filtered = enrichedMachines.value

  if (selectedSite.value) {
    filtered = filtered.filter(machine => machine.siteId === selectedSite.value)
  }

  if (selectedType.value) {
    filtered = filtered.filter(machine => machine.typeMachineId === selectedType.value)
  }

  if (selectedCategory.value) {
    filtered = filtered.filter(machine => machine.typeMachine?.category === selectedCategory.value)
  }

  return filtered
})

const viewMachineDetails = (machine) => {
  navigateTo(`/machine/${machine.id}`)
}

const editMachine = (machine) => {
  navigateTo(`/machine/${machine.id}?edit=true`)
}

const confirmDeleteMachine = async (machine) => {
  const { showError, showSuccess } = toast

  if (confirm(`Êtes-vous sûr de vouloir supprimer la machine "${machine.name}" ? Cette action est irréversible.`)) {
    try {
      const result = await deleteMachine(machine.id)
      if (result.success) {
        showSuccess(`Machine "${machine.name}" supprimée avec succès`)
      } else {
        showError(`Erreur lors de la suppression: ${result.error}`)
      }
    } catch (error) {
      showError(`Erreur lors de la suppression: ${error.message}`)
    }
  }
}

onMounted(async () => {
  await Promise.all([
    loadMachines(),
    loadSites(),
    loadMachineTypes()
  ])
})
</script>
