<template>
  <div class="card mt-4">
    <div class="table-responsive">
      <table id="goods-receipt-list" class="table table-flush">
        <thead class="thead-light">
          <tr>
            <th>Numéro</th>
            <th>Date</th>
            <th>Commande</th>
            <th>Entrepôt</th>
            <th>Statut</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="receipt in data" :key="receipt.id">
            <!-- Receipt Number -->
            <td class="text-xs font-weight-bold">
              <span class="my-2 text-xs">{{ receipt.receipt_number }}</span>
            </td>

            <!-- Receipt Date -->
            <td class="text-xs font-weight-bold">
              <span class="my-2 text-xs">{{ formatDate(receipt.receipt_date) }}</span>
            </td>

            <!-- Purchase Order -->
            <td class="text-xs font-weight-bold">
              <span class="my-2 text-xs">
                {{ receipt.purchase_order?.po_number || receipt.purchase_order_id }}
              </span>
            </td>

            <!-- Warehouse -->
            <td class="text-xs font-weight-bold">
              <span class="my-2 text-xs">{{ receipt.warehouse?.name || '-' }}</span>
            </td>

            <!-- Status -->
            <td class="text-xs font-weight-bold">
              <soft-badge :color="getStatusColor(receipt.status)" variant="gradient">
                {{ getStatusLabel(receipt.status) }}
              </soft-badge>
            </td>

            <!-- Actions -->
            <td class="text-xs font-weight-bold">
              <div class="d-flex align-items-center">
                <button
                  class="btn btn-link text-secondary mb-0 px-2"
                  :data-id="receipt.id"
                  data-action="view"
                  title="Voir la réception"
                >
                  <i class="fas fa-eye text-xs" aria-hidden="true"></i>
                </button>
                <button
                  class="btn btn-link text-info mb-0 px-2"
                  :data-id="receipt.id"
                  data-action="edit"
                  title="Modifier la réception"
                >
                  <i class="fas fa-edit text-xs" aria-hidden="true"></i>
                </button>
                <button
                  class="btn btn-link text-danger mb-0 px-2"
                  :data-id="receipt.id"
                  data-action="delete"
                  title="Supprimer la réception"
                >
                  <i class="fas fa-trash text-xs" aria-hidden="true"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  watch,
  onUnmounted,
  defineProps,
  defineEmits,
} from "vue";
import { DataTable } from "simple-datatables";
import SoftBadge from "@/components/SoftBadge.vue";

const emit = defineEmits(["view", "edit", "delete"]);

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const dataTableInstance = ref(null);

const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('fr-FR');
};

const getStatusColor = (status) => {
  switch (status) {
    case 'draft':
      return 'secondary';
    case 'posted':
      return 'success';
    default:
      return 'info';
  }
};

const getStatusLabel = (status) => {
  switch (status) {
    case 'draft':
      return 'Brouillon';
    case 'posted':
      return 'Validée';
    default:
      return status;
  }
};

const initializeDataTable = () => {
  if (dataTableInstance.value) {
    dataTableInstance.value.destroy();
    dataTableInstance.value = null;
  }

  const dataTableEl = document.getElementById("goods-receipt-list");
  if (dataTableEl) {
    dataTableInstance.value = new DataTable(dataTableEl, {
      searchable: true,
      fixedHeight: false,
      perPageSelect: false,
    });
  }
};

onMounted(() => {
  if (!props.loading && props.data.length > 0) {
    initializeDataTable();
  }

  // Event delegation
  const table = document.getElementById("goods-receipt-list");
  if (table) {
    table.addEventListener("click", (event) => {
      const btn = event.target.closest("button");
      if (!btn) return;

      const id = btn.getAttribute("data-id");
      const action = btn.getAttribute("data-action");

      if (id && action) {
        if (action === "view") {
          emit("view", parseInt(id));
        } else if (action === "edit") {
          emit("edit", parseInt(id));
        } else if (action === "delete") {
          emit("delete", parseInt(id));
        }
      }
    });
  }
});

watch(
  () => props.data,
  () => {
    if (!props.loading) {
      setTimeout(() => {
        initializeDataTable();
      }, 100);
    }
  },
  { deep: true }
);

onUnmounted(() => {
  if (dataTableInstance.value) {
    dataTableInstance.value.destroy();
  }
});
</script>
