<template>
  <main class="container mx-auto px-6 py-8">
    <!-- Machine Types List -->
    <div class="my-8">
      <!-- Header with Add Button -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Squelettes de machine</h2>
        <NuxtLink to="/machine-skeleton/new" class="btn btn-primary">
          <IconLucidePlus class="w-5 h-5 mr-2" aria-hidden="true" />
          Créer un type
        </NuxtLink>
      </div>

      <!-- Categories Tabs -->
      <div class="tabs tabs-boxed mb-6">
        <a
          v-for="category in categories"
          :key="category"
          class="tab"
          :class="{ 'tab-active': selectedCategory === category }"
          @click="selectedCategory = category"
        >
          {{ category }}
        </a>
      </div>

      <!-- Machine Types Grid -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="type in filteredTypes"
          :key="type.id"
          class="card bg-base-100 shadow-lg hover:shadow-xl transition-all duration-300 cursor-pointer"
        >
          <div class="card-body">
            <div class="flex items-center justify-between mb-4">
              <h3 class="card-title text-lg">
                {{ type.name }}
              </h3>
              <div class="badge badge-primary">
                {{ type.category }}
              </div>
            </div>
            <p class="text-gray-600 mb-4">
              {{ type.description }}
            </p>
            <div class="space-y-2 text-sm text-gray-500">
              <div class="flex items-center gap-2">
                <IconLucidePackage class="w-4 h-4" aria-hidden="true" />
                <span
                  >{{ type.componentRequirements?.length || 0 }} famille(s) de
                  composants</span
                >
              </div>
              <div class="flex items-center gap-2">
                <IconLucideLayoutGrid class="w-4 h-4" aria-hidden="true" />
                <span
                  >{{ type.pieceRequirements?.length || 0 }} groupe(s) de
                  pièces</span
                >
              </div>
              <div class="flex items-center gap-2">
                <IconLucideBox class="w-4 h-4" aria-hidden="true" />
                <span
                  >{{ type.productRequirements?.length || 0 }} produit(s)
                  requis</span
                >
              </div>
            </div>
            <div class="card-actions justify-end mt-4">
              <button
                v-if="canEdit"
                class="btn btn-sm btn-error"
                @click.stop="confirmDeleteType(type)"
              >
                Supprimer
              </button>
              <NuxtLink :to="`/type/${type.id}`" class="btn btn-sm btn-outline">
                Voir détails
              </NuxtLink>
            </div>
          </div>
        </div>
      </div>

      <!-- Empty State -->
      <div v-if="filteredTypes.length === 0" class="text-center py-12">
        <div class="avatar placeholder">
          <div class="bg-neutral text-neutral-content rounded-full w-16">
            <IconLucideLayoutGrid class="w-8 h-8" aria-hidden="true" />
          </div>
        </div>
        <h3 class="text-lg font-semibold text-gray-600 mt-4">
          Aucun type trouvé
        </h3>
        <p class="text-gray-500">
          Aucun type de machine ne correspond à cette catégorie.
        </p>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useMachineTypesApi } from "~/composables/useMachineTypesApi";
import { useToast } from "~/composables/useToast";
import { humanizeError } from "~/shared/utils/errorMessages";
import IconLucidePlus from "~icons/lucide/plus";
import IconLucidePackage from "~icons/lucide/package";
import IconLucideLayoutGrid from "~icons/lucide/layout-grid";
import IconLucideBox from "~icons/lucide/box";

const { canEdit } = usePermissions();
const { machineTypes, loadMachineTypes, deleteMachineType } =
  useMachineTypesApi();

const categories = ref([
  "Toutes",
  "Production",
  "Transformation",
  "Manutention",
  "Traitement",
  "Contrôle",
]);

const selectedCategory = ref("Toutes");

const filteredTypes = computed(() => {
  if (selectedCategory.value === "Toutes") {
    return machineTypes.value;
  }
  return machineTypes.value.filter(
    (type) => type.category === selectedCategory.value
  );
});

const { confirm: confirmDialog } = useConfirm();

const confirmDeleteType = async (type) => {
  const { showError, showSuccess } = useToast();

  if (
    await confirmDialog({
      message: `Êtes-vous sûr de vouloir supprimer le type "${type.name}" ? Cette action est irréversible.`,
    })
  ) {
    try {
      const result = await deleteMachineType(type.id);
      if (result.success) {
        showSuccess(`Type "${type.name}" supprimé avec succès`);
      } else {
        showError(`Impossible de supprimer le type : ${result.error}`);
      }
    } catch (error) {
      showError(`Impossible de supprimer le type : ${humanizeError(error.message)}`);
    }
  }
};

// Load machine types on mount
onMounted(async () => {
  await loadMachineTypes();
});
</script>
