<template>
  <div class="border border-gray-200 rounded-lg p-4">
    <div class="flex items-center justify-between mb-3">
      <div class="flex items-center gap-2">
        <svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
        </svg>
        <input 
          v-if="isEditMode"
          :id="`piece-name-${piece.id}`"
          v-model="pieceData.name" 
          type="text" 
          class="font-semibold text-lg input input-sm input-bordered"
          @blur="updatePiece"
        />
        <div v-else class="font-semibold text-lg input input-sm input-bordered bg-base-200">
          {{ pieceData.name }}
        </div>
      </div>
    </div>

    <div class="space-y-2 text-sm">
      <div>
        <span class="font-medium">Référence:</span> 
        <input 
          v-if="isEditMode"
          :id="`piece-reference-${piece.id}`"
          v-model="pieceData.reference" 
          type="text" 
          class="input input-sm input-bordered ml-2"
          @blur="updatePiece"
        />
        <span v-else class="ml-2">{{ pieceData.reference || 'Non définie' }}</span>
      </div>
      <div>
        <span class="font-medium">Prestataire:</span> 
        <input 
          v-if="isEditMode"
          :id="`piece-prestataire-${piece.id}`"
          v-model="pieceData.prestataire" 
          type="text" 
          class="input input-sm input-bordered ml-2"
          @blur="updatePiece"
        />
        <span v-else class="ml-2">{{ pieceData.prestataire || 'Non défini' }}</span>
      </div>
      <div>
        <span class="font-medium">Emplacement:</span> 
        <input 
          v-if="isEditMode"
          :id="`piece-emplacement-${piece.id}`"
          v-model="pieceData.emplacement" 
          type="text" 
          class="input input-sm input-bordered ml-2"
          @blur="updatePiece"
        />
        <span v-else class="ml-2">{{ pieceData.emplacement || 'Non défini' }}</span>
      </div>
      <div>
        <span class="font-medium">Prix:</span> 
        <input 
          v-if="isEditMode"
          :id="`piece-prix-${piece.id}`"
          v-model="pieceData.prix" 
          type="number" 
          step="0.01"
          class="input input-sm input-bordered ml-2"
          @blur="updatePiece"
        />
        <span v-else class="ml-2">{{ pieceData.prix ? `${pieceData.prix}€` : 'Non défini' }}</span>
      </div>
    </div>

    <!-- Champs personnalisés de la pièce -->
    <div v-if="piece.customFieldValues && piece.customFieldValues.length > 0" class="mt-4 pt-4 border-t border-gray-200">
      <h5 class="text-sm font-medium text-gray-700 mb-3">Champs personnalisés</h5>
      <div class="space-y-3">
        <div 
          v-for="fieldValue in piece.customFieldValues" 
          :key="fieldValue.id"
          class="form-control"
        >
          <label class="label">
            <span class="label-text text-sm">{{ fieldValue.customField.name }}</span>
            <span v-if="fieldValue.customField.required" class="label-text-alt text-error">*</span>
          </label>
          
          <!-- Mode édition -->
          <template v-if="isEditMode">
            <!-- Champ de type TEXT -->
            <input 
              v-if="fieldValue.customField.type === 'text'"
              :value="fieldValue.value"
              @input="setCustomFieldValue(fieldValue.id, $event.target.value)"
              type="text"
              :placeholder="fieldValue.customField.defaultValue || ''"
              class="input input-bordered input-sm"
              :required="fieldValue.customField.required"
              @blur="updateCustomFieldValue(fieldValue.id)"
            />
            
            <!-- Champ de type NUMBER -->
            <input 
              v-else-if="fieldValue.customField.type === 'number'"
              :value="fieldValue.value"
              @input="setCustomFieldValue(fieldValue.id, $event.target.value)"
              type="number"
              :placeholder="fieldValue.customField.defaultValue || ''"
              class="input input-bordered input-sm"
              :required="fieldValue.customField.required"
              @blur="updateCustomFieldValue(fieldValue.id)"
            />
            
            <!-- Champ de type SELECT -->
            <select 
              v-else-if="fieldValue.customField.type === 'select'"
              :value="fieldValue.value"
              @change="setCustomFieldValue(fieldValue.id, $event.target.value)"
              class="select select-bordered select-sm"
              :required="fieldValue.customField.required"
              @blur="updateCustomFieldValue(fieldValue.id)"
            >
              <option value="">{{ fieldValue.customField.defaultValue || 'Sélectionner...' }}</option>
              <option 
                v-for="option in fieldValue.customField.options" 
                :key="option" 
                :value="option"
              >
                {{ option }}
              </option>
            </select>
            
            <!-- Champ de type BOOLEAN -->
            <div v-else-if="fieldValue.customField.type === 'boolean'" class="flex items-center gap-2">
              <input 
                :value="fieldValue.value"
                @change="setCustomFieldValue(fieldValue.id, $event.target.checked ? 'true' : 'false')"
                type="checkbox"
                class="checkbox checkbox-sm"
                :checked="fieldValue.value === 'true'"
                @blur="updateCustomFieldValue(fieldValue.id)"
              />
              <span class="text-sm">{{ fieldValue.value === 'true' ? 'Oui' : 'Non' }}</span>
            </div>
            
            <!-- Champ de type DATE -->
            <input 
              v-else-if="fieldValue.customField.type === 'date'"
              :value="fieldValue.value"
              @input="setCustomFieldValue(fieldValue.id, $event.target.value)"
              type="date"
              :placeholder="fieldValue.customField.defaultValue || ''"
              class="input input-bordered input-sm"
              :required="fieldValue.customField.required"
              @blur="updateCustomFieldValue(fieldValue.id)"
            />
          </template>
          
          <!-- Mode lecture seule -->
          <template v-else>
            <div class="input input-bordered input-sm bg-base-200">
              {{ fieldValue.value || fieldValue.customField.defaultValue || 'Non défini' }}
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, watch } from 'vue'
import { useCustomFields } from '~/composables/useCustomFields'
import { useToast } from '~/composables/useToast'

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

const emit = defineEmits(['update', 'edit', 'custom-field-update'])

// Données locales isolées pour cette pièce
const pieceData = reactive({
  name: props.piece.name || '',
  reference: props.piece.reference || '',
  prestataire: props.piece.prestataire || '',
  emplacement: props.piece.emplacement || '',
  prix: props.piece.prix || ''
})

// Méthodes pour gérer les champs personnalisés
const setCustomFieldValue = (fieldValueId, value) => {
  const fieldValue = props.piece.customFieldValues?.find(fv => fv.id === fieldValueId)
  if (fieldValue) {
    fieldValue.value = value
  }
}

const updatePiece = () => {
  const prixValue = pieceData.prix
  emit('update', {
    ...props.piece,
    ...pieceData,
    prix: prixValue && prixValue !== '' ? parseFloat(prixValue) : null
  })
}

const updateCustomFieldValue = async (fieldValueId) => {
  const fieldValue = props.piece.customFieldValues?.find(fv => fv.id === fieldValueId)
  if (fieldValue) {
    const { updateCustomFieldValue } = useCustomFields()
    const { showSuccess, showError } = useToast()
    
    const result = await updateCustomFieldValue(fieldValueId, { value: fieldValue.value })
    if (result.success) {
      showSuccess(`Champ "${fieldValue.customField.name}" mis à jour avec succès`)
    } else {
      showError(`Erreur lors de la mise à jour du champ "${fieldValue.customField.name}"`)
    }
  }
}

// Surveiller les changements dans les champs personnalisés
watch(() => props.piece.customFieldValues, () => {
  console.log('PieceItem - customFieldValues updated:', props.piece.customFieldValues)
}, { deep: true })

onMounted(() => {
  // Initialiser les données avec les props
  pieceData.name = props.piece.name || ''
  pieceData.reference = props.piece.reference || ''
  pieceData.prestataire = props.piece.prestataire || ''
  pieceData.emplacement = props.piece.emplacement || ''
  pieceData.prix = props.piece.prix || ''
  
  // Debug: vérifier si les champs personnalisés sont présents
  console.log('PieceItem - piece:', props.piece)
  console.log('PieceItem - customFieldValues:', props.piece.customFieldValues)
})
</script> 