<template>
  <div class="tva-row">
    <!-- TVA label like TOTAL -->
    <span class="row-label">TVA</span>
    <div class="tva-fields">
      <div
        v-for="(entry, index) in visibleEntries"
        :key="entry.code"
        class="tva-item"
        :class="{ active: modelValue[entry.code]?.amount > 0 }"
      >
        <!-- Percent as InputNumber (not dropdown) -->
        <InputNumber
          v-model="modelValue[entry.code].percent"
          suffix="%"
          :min="0"
          :max="100"
          placeholder="21"
          :disabled="disabled"
          class="tva-percent"
          @input="emitUpdate"
        />
        <InputNumber
          v-model="modelValue[entry.code].amount"
          :minFractionDigits="2"
          :maxFractionDigits="2"
          :disabled="disabled"
          placeholder="0.00"
          class="tva-amount"
          @input="emitUpdate"
        />
        <!-- Remove button (if more than 1 visible) -->
        <button
          v-if="visibleEntries.length > 1 && !disabled"
          type="button"
          class="remove-btn"
          @click="removeEntry(index)"
        >
          <i class="pi pi-times"></i>
        </button>
      </div>

      <!-- Add button -->
      <button
        v-if="canAddMore && !disabled"
        type="button"
        class="add-btn"
        @click="addEntry"
      >
        <i class="pi pi-plus"></i>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import InputNumber from 'primevue/inputnumber'

const props = defineProps({
  modelValue: { type: Object, required: true },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue'])

const ALL_CODES = ['A', 'B', 'C', 'D', 'E']

// Track which TVA codes are visible (default: just 'A')
const visibleCodes = ref(['A'])

// Computed: entries to display
const visibleEntries = computed(() => {
  return visibleCodes.value.map(code => ({
    code,
    ...props.modelValue[code]
  }))
})

// Computed: can add more rows?
const canAddMore = computed(() => {
  return visibleCodes.value.length < ALL_CODES.length
})

// Add next available code
const addEntry = () => {
  const nextCode = ALL_CODES.find(code => !visibleCodes.value.includes(code))
  if (nextCode) {
    visibleCodes.value = [...visibleCodes.value, nextCode]
  }
}

// Remove code at index
const removeEntry = (index) => {
  if (visibleCodes.value.length > 1) {
    const codeToRemove = visibleCodes.value[index]
    visibleCodes.value = visibleCodes.value.filter((_, i) => i !== index)
    // Reset the removed code's values
    if (props.modelValue[codeToRemove]) {
      props.modelValue[codeToRemove].percent = null
      props.modelValue[codeToRemove].amount = 0
      emitUpdate()
    }
  }
}

// Watch modelValue for OCR changes - auto-expand to show filled values
watch(() => props.modelValue, (newVal) => {
  if (!newVal) return
  const codesWithValues = ALL_CODES.filter(
    code => newVal[code]?.amount > 0
  )
  if (codesWithValues.length > 0) {
    // Ensure all codes with values are visible
    const newVisibleCodes = [...new Set([...visibleCodes.value, ...codesWithValues])]
    if (newVisibleCodes.length !== visibleCodes.value.length) {
      visibleCodes.value = newVisibleCodes
    }
  }
}, { deep: true, immediate: true })

const emitUpdate = () => {
  emit('update:modelValue', { ...props.modelValue })
}
</script>

<style scoped>
/* === TVA ROW - with label and green background === */
.tva-row {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  background: var(--green-100);  /* different from TOTAL which uses green-50 */
  border-radius: var(--radius-sm);
  padding: var(--space-sm) var(--space-md);
  margin: var(--space-xs) 0;
}

.row-label {
  font-weight: var(--font-semibold);
  font-size: var(--text-xs);  /* 12px - uniform for labels */
  color: var(--text-color);
  flex-shrink: 0;
  min-width: 40px;
}

.tva-fields {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-sm, 0.5rem);
  align-items: center;
  flex: 1;
}

.tva-item {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
}

.tva-item.active .tva-amount :deep(.p-inputnumber-input) {
  background: color-mix(in srgb, var(--green-500) 8%, var(--surface-ground));
}

/* TVA percent input (wider to see "21%") */
.tva-percent {
  width: 70px;  /* wider to show % suffix */
}

.tva-percent :deep(.p-inputnumber-input) {
  width: 100%;
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform for inputs */
  font-weight: var(--font-normal);
  text-align: right;
  height: 32px;  /* uniform height */
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  color: var(--text-color);
}

.tva-percent :deep(.p-inputnumber-input:focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 1px var(--primary-color);
}

/* TVA amount input (wider to see "1234.56") */
.tva-amount {
  width: 90px;  /* wider */
}

.tva-amount :deep(.p-inputnumber-input) {
  width: 100%;
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform for inputs */
  font-weight: var(--font-normal);
  text-align: right;
  height: 32px;  /* uniform height */
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  color: var(--text-color);
}

.tva-amount :deep(.p-inputnumber-input:focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 1px var(--primary-color);
}

/* Add/Remove buttons - icon only, compact */
.add-btn, .remove-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: var(--radius-sm);
  border: 1px dashed var(--surface-border);
  background: var(--surface-ground);
  color: var(--text-color-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.add-btn:hover {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
  border-style: solid;
}

.remove-btn {
  border-style: solid;
  border-color: transparent;
  background: transparent;
}

.remove-btn:hover {
  background: var(--red-500);
  border-color: var(--red-500);
  color: white;
}

.add-btn i, .remove-btn i {
  font-size: var(--text-xs);
}

/* Responsive: stack on mobile */
@media (max-width: 480px) {
  .tva-row {
    flex-direction: column;
    align-items: stretch;
    gap: var(--space-xs);
  }

  .row-label {
    margin-bottom: var(--space-xs);
  }

  .tva-fields {
    width: 100%;
  }

  .tva-item {
    width: 100%;
    justify-content: flex-start;
  }

  .tva-percent {
    flex: 0 0 70px;
  }

  .tva-amount {
    flex: 1;
  }
}
</style>

<!-- NON-SCOPED: Force dark mode styling -->
<style>
[data-theme="dark"] .tva-row {
  background: rgba(34, 197, 94, 0.15);  /* slightly more visible than TOTAL */
}

[data-theme="dark"] .tva-row .p-inputnumber-input {
  background: var(--surface-ground) !important;
  color: var(--text-color) !important;
  border-color: var(--surface-border) !important;
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .tva-row {
    background: rgba(34, 197, 94, 0.15);  /* slightly more visible than TOTAL */
  }

  :root:not([data-theme="light"]) .tva-row .p-inputnumber-input {
    background: var(--surface-ground) !important;
    color: var(--text-color) !important;
    border-color: var(--surface-border) !important;
  }
}
</style>
