<template>
  <div class="supplier-dual-field">
    <div class="dual-grid">
      <!-- LEFT: OCR Data (read-only) -->
      <div class="ocr-side" :class="{ 'has-data': ocrName || ocrCui }">
        <div class="side-header">
          <span class="side-label">Din OCR</span>
          <OCRConfidenceIndicator
            v-if="ocrConfidence"
            :confidence="ocrConfidence"
            size="small"
          />
        </div>
        <div class="side-content">
          <div class="ocr-name" v-if="ocrName">{{ ocrName }}</div>
          <div class="ocr-cui" v-if="ocrCui">CUI: {{ ocrCui }}</div>
          <div class="ocr-empty" v-if="!ocrName && !ocrCui">
            <i class="pi pi-info-circle"></i>
            Procesati o imagine pentru extragere automata
          </div>
        </div>
      </div>

      <!-- RIGHT: DB Validated (editable) -->
      <div class="db-side">
        <div class="side-header">
          <span class="side-label">Validat DB</span>
          <Button
            v-if="!disabled"
            icon="pi pi-sync"
            size="small"
            text
            rounded
            :loading="syncingSuppliers"
            @click="$emit('sync-suppliers')"
            v-tooltip.top="'Re-sincronizeaza furnizorii din Oracle'"
            class="sync-btn"
          />
        </div>
        <div class="side-content">
          <div class="field-row">
            <AutoComplete
              v-model="localPartnerName"
              :suggestions="filteredPartners"
              optionLabel="name"
              field="name"
              @complete="searchPartners"
              @item-select="onPartnerSelect"
              placeholder="Cauta furnizor..."
              dropdown
              :forceSelection="false"
              :disabled="disabled"
              class="partner-autocomplete"
            />
          </div>
          <div class="field-row cui-row">
            <label>CUI</label>
            <InputText
              v-model="localCui"
              placeholder="RO12345678"
              :disabled="disabled"
              class="cui-input"
            />
          </div>
        </div>

        <!-- Supplier status badges -->
        <div class="supplier-status" v-if="supplierSource || showWarning">
          <div v-if="supplierSource" class="status-badge success">
            <i class="pi pi-check-circle"></i>
            <span>Validat ({{ supplierSource }})</span>
          </div>
          <div v-if="showWarning" class="status-badge warning">
            <i class="pi pi-exclamation-triangle"></i>
            <span>Negasit - se va crea automat</span>
            <Button
              v-if="!disabled"
              label="Creaza acum"
              icon="pi pi-plus"
              size="small"
              severity="warning"
              text
              @click="$emit('create-supplier')"
              class="create-btn"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Address (collapsed by default) -->
    <div class="address-section" v-if="localAddress">
      <div class="address-toggle" @click="showAddress = !showAddress">
        <i :class="showAddress ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"></i>
        <span>{{ showAddress ? 'Ascunde adresa' : localAddress }}</span>
      </div>
      <div class="address-expanded" v-if="showAddress">
        <InputText
          v-model="localAddress"
          placeholder="Adresa furnizor"
          :disabled="disabled"
          class="address-input"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import AutoComplete from 'primevue/autocomplete'
import InputText from 'primevue/inputtext'
import Button from 'primevue/button'
import OCRConfidenceIndicator from '@data-entry/components/ocr/OCRConfidenceIndicator.vue'

const props = defineProps({
  // OCR data (read-only display)
  ocrName: { type: String, default: '' },
  ocrCui: { type: String, default: '' },
  ocrConfidence: { type: Number, default: null },

  // Form values (two-way bound)
  partnerName: { type: [String, Object], default: '' },
  cui: { type: String, default: '' },
  address: { type: String, default: '' },

  // Supplier validation
  supplierSource: { type: String, default: null }, // 'oracle' | 'local' | null
  showWarning: { type: Boolean, default: false },

  // Partners list for autocomplete
  partners: { type: Array, default: () => [] },

  // State
  disabled: { type: Boolean, default: false },
  syncingSuppliers: { type: Boolean, default: false },
})

const emit = defineEmits([
  'update:partnerName',
  'update:cui',
  'update:address',
  'partner-selected',
  'sync-suppliers',
  'create-supplier',
])

// Local refs with two-way binding
const localPartnerName = computed({
  get: () => props.partnerName,
  set: (val) => emit('update:partnerName', val)
})

const localCui = computed({
  get: () => props.cui,
  set: (val) => emit('update:cui', val)
})

const localAddress = computed({
  get: () => props.address,
  set: (val) => emit('update:address', val)
})

const showAddress = ref(false)
const filteredPartners = ref([])

const searchPartners = (event) => {
  const query = event.query.toLowerCase()
  filteredPartners.value = props.partners.filter(p =>
    p.name.toLowerCase().includes(query) ||
    (p.fiscal_code && p.fiscal_code.toLowerCase().includes(query))
  )
}

const onPartnerSelect = (event) => {
  const partner = event.value
  if (partner) {
    emit('update:cui', partner.fiscal_code || '')
    if (partner.address) {
      emit('update:address', partner.address)
    }
    emit('partner-selected', partner)
  }
}
</script>

<style scoped>
.supplier-dual-field {
  width: 100%;
}

.dual-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

/* Side styles */
.ocr-side,
.db-side {
  padding: 0.75rem;
  border-radius: 8px;
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
}

.ocr-side {
  background: var(--surface-ground);
}

.ocr-side.has-data {
  background: var(--blue-50);
  border-color: var(--blue-200);
}

.side-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  padding-bottom: 0.35rem;
  border-bottom: 1px dashed var(--surface-border);
}

.side-label {
  font-size: 0.7rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-color-secondary);
}

.sync-btn {
  padding: 0.25rem;
  width: 1.5rem;
  height: 1.5rem;
}

/* OCR side content */
.ocr-name {
  font-weight: 600;
  font-size: 0.95rem;
  color: var(--text-color);
  margin-bottom: 0.25rem;
}

.ocr-cui {
  font-size: 0.85rem;
  color: var(--text-color-secondary);
}

.ocr-empty {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  font-style: italic;
}

.ocr-empty i {
  color: var(--blue-400);
}

/* DB side content */
.field-row {
  margin-bottom: 0.5rem;
}

.field-row:last-child {
  margin-bottom: 0;
}

.cui-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.cui-row label {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  min-width: 30px;
}

.partner-autocomplete {
  width: 100%;
}

.cui-input {
  flex: 1;
  max-width: 140px;
}

/* Supplier status */
.supplier-status {
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid var(--surface-border);
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  font-size: 0.8rem;
  padding: 0.25rem 0;
}

.status-badge.success {
  color: var(--green-700);
}

.status-badge.success i {
  color: var(--green-500);
}

.status-badge.warning {
  color: var(--yellow-800);
  flex-wrap: wrap;
}

.status-badge.warning i {
  color: var(--yellow-500);
}

.create-btn {
  margin-left: auto;
  font-size: 0.75rem;
}

/* Address section */
.address-section {
  margin-top: 0.5rem;
}

.address-toggle {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.35rem 0.5rem;
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.15s;
}

.address-toggle:hover {
  background: var(--surface-hover);
}

.address-toggle i {
  font-size: 0.75rem;
}

.address-toggle span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.address-expanded {
  padding: 0.5rem;
}

.address-input {
  width: 100%;
  font-size: 0.85rem;
}

/* Responsive */
@media (max-width: 768px) {
  .dual-grid {
    grid-template-columns: 1fr;
  }
}

/* Dark mode adjustments */
[data-theme="dark"] .ocr-side.has-data {
  background: rgba(59, 130, 246, 0.1);
  border-color: var(--blue-700);
}
</style>
