<template>
  <div class="card mt-4">
    <div class="table-responsive">
      <table id="facture-fournisseur-list" class="table table-flush">
        <thead class="thead-light">
          <tr>
            <th>N° Facture</th>
            <th>Fournisseur</th>
            <th>Date</th>
            <th>Montant TTC</th>
            <th>Statut</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="facture in data" :key="facture.id">
            <!-- Invoice Number -->
            <td>
              <div class="d-flex align-items-center">
                <soft-checkbox class="me-2" />
                <p class="text-xs font-weight-bold ms-2 mb-0">
                  {{ facture.number }}
                </p>
              </div>
            </td>

            <!-- Supplier -->
            <td class="text-xs font-weight-bold">
              <span>{{ facture.supplierName }}</span>
            </td>

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

            <!-- Total TTC -->
            <td class="text-xs font-weight-bold">
              <span class="my-2 text-xs">{{ formatCurrency(facture.totalTtc) }}</span>
            </td>

            <!-- Status -->
            <td class="text-xs font-weight-bold">
              <div class="d-flex align-items-center">
                <soft-button
                  :color="getStatusColor(facture.status)"
                  variant="outline"
                  class="btn-icon-only btn-rounded mb-0 me-2 btn-sm d-flex align-items-center justify-content-center"
                >
                  <i :class="getStatusIcon(facture.status)" aria-hidden="true"></i>
                </soft-button>
                <span>{{ getStatusLabel(facture.status) }}</span>
              </div>
            </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="facture.id"
                  data-action="view"
                  title="Voir la facture"
                >
                  <i class="fas fa-eye text-xs" aria-hidden="true"></i>
                </button>
                <button
                  class="btn btn-link text-danger mb-0 px-2"
                  :data-id="facture.id"
                  data-action="delete"
                  title="Supprimer la facture"
                >
                  <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 SoftButton from "@/components/SoftButton.vue";
import SoftCheckbox from "@/components/SoftCheckbox.vue";

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

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

const dataTableInstance = ref(null);

const formatDate = (dateString) => {
  if (!dateString) return null;
  const options = {
    day: "numeric",
    month: "short",
    year: "numeric",
  };
  return new Date(dateString).toLocaleDateString("fr-FR", options);
};

const formatCurrency = (value) => {
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(value);
};

const getStatusColor = (status) => {
  const map = {
    payee: "success",
    en_attente: "warning",
    annulee: "danger",
    brouillon: "secondary",
  };
  return map[status] || "secondary";
};

const getStatusIcon = (status) => {
  const map = {
    payee: "fas fa-check",
    en_attente: "fas fa-hourglass-half",
    annulee: "fas fa-ban",
    brouillon: "fas fa-pen",
  };
  return map[status] || "fas fa-info";
};

const getStatusLabel = (status) => {
  const labels = {
    payee: "Payée",
    en_attente: "En attente",
    annulee: "Annulée",
    brouillon: "Brouillon",
  };
  return labels[status] || status;
};

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

  const dataTableEl = document.getElementById("facture-fournisseur-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("facture-fournisseur-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 === "delete") {
          emit("delete", parseInt(id));
        }
      }
    });
  }
});

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

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