<template>
  <div class="card bg-base-100 shadow-lg">
    <div class="card-body">
      <div class="flex justify-between items-center mb-4">
        <h2 class="card-title">Composants</h2>
        <div class="flex items-center gap-2">
          <button
            v-if="isEditMode"
            type="button"
            class="btn btn-sm md:btn-md btn-primary"
            @click="$emit('add-component')"
          >
            Ajouter un composant
          </button>
          <button
            type="button"
            class="btn btn-ghost btn-sm gap-2"
            @click="$emit('toggle-collapse')"
            :title="collapsed ? 'Déplier tous les composants' : 'Replier tous les composants'"
          >
            <IconLucideChevronRight
              class="w-5 h-5 transition-transform"
              :class="collapsed ? 'rotate-0' : 'rotate-90'"
              aria-hidden="true"
            />
            <span class="text-sm">
              {{ collapsed ? 'Tout déplier' : 'Tout replier' }}
            </span>
          </button>
        </div>
      </div>

      <div v-if="components.length === 0" class="text-sm text-gray-500 py-4">
        Aucun composant associé à cette machine.
      </div>

      <div v-else class="space-y-2">
        <div v-for="component in components" :key="component.id" class="relative">
          <button
            v-if="isEditMode"
            type="button"
            class="btn btn-error btn-xs absolute top-2 right-2 z-10"
            title="Supprimer ce composant"
            @click="$emit('remove-component', component.linkId || component.id)"
          >
            Supprimer
          </button>
          <ComponentHierarchy
            :components="[component]"
            :is-edit-mode="false"
            :collapse-all="collapsed"
            :toggle-token="collapseToggleToken"
            @edit-piece="$emit('edit-piece', $event)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import ComponentHierarchy from '~/components/ComponentHierarchy.vue'
import IconLucideChevronRight from '~icons/lucide/chevron-right'

defineProps<{
  components: any[]
  isEditMode: boolean
  collapsed: boolean
  collapseToggleToken: number
}>()

defineEmits<{
  'toggle-collapse': []
  'update-component': [component: any]
  'edit-piece': [piece: any]
  'custom-field-update': [fieldUpdate: any]
  'add-component': []
  'remove-component': [linkId: string]
}>()
</script>
