<template>
  <div class="table-responsive">
    <table class="table align-items-center mb-0">
      <thead>
        <tr>
          <th
            class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2"
          >
            Produit
          </th>
          <th
            class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2"
          >
            Qté
          </th>
          <th
            class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2"
          >
            Prix Unit.
          </th>
          <th
            class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2"
          >
            Remise
          </th>
          <th
            class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2 text-end"
          >
            Total HT
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="line in lines" :key="line.id">
          <td>
            <div class="d-flex flex-column justify-content-center">
              <h6 class="mb-0 text-sm">
                {{ line.product_name || line.description }}
              </h6>
              <p
                v-if="line.product && line.product.reference"
                class="text-xs text-secondary mb-0"
              >
                {{ line.product.reference }}
              </p>
            </div>
          </td>
          <td>
            <p class="text-xs font-weight-bold mb-0">
              {{
                line.packages_qty ||
                line.units_qty ||
                line.quantity ||
                line.qty_base
              }}
            </p>
          </td>
          <td>
            <p class="text-xs font-weight-bold mb-0">
              {{ formatCurrency(line.unit_price) }}
            </p>
          </td>
          <td>
            <p class="text-xs font-weight-bold mb-0">
              {{ line.discount_pct }}%
            </p>
          </td>
          <td class="text-end">
            <p class="text-xs font-weight-bold mb-0">
              {{ formatCurrency(line.total_ht) }}
            </p>
          </td>
        </tr>
        <tr v-if="!lines || lines.length === 0">
          <td colspan="5" class="text-center text-sm py-3">
            Aucune ligne de produit
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { defineProps } from "vue";

const props = defineProps({
  lines: {
    type: Array,
    default: () => [],
  },
});

const formatCurrency = (value) => {
  const numberValue = typeof value === 'string' ? parseFloat(value) : value;
  if (isNaN(numberValue)) return '0,00 €';

  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(numberValue);
};
</script>
