<template>
  <form @submit.prevent="handleSubmit" class="add-service-form">
    <div class="form-row">
      <div class="form-group">
        <label for="startDate">Fecha de inicio</label>
        <input
          type="datetime-local"
          id="startDate"
          v-model="formData.startDate"
          required
          class="form-input"
        >
      </div>
      <div class="form-group">
        <label for="endDate">Fecha de fin</label>
        <input
          type="datetime-local"
          id="endDate"
          v-model="formData.endDate"
          required
          class="form-input"
        >
      </div>
      <div class="form-group" v-if="showQuantityField">
        <label for="quantity">Cantidad</label>
        <input
          type="number"
          id="quantity"
          v-model="formData.quantity"
          min="1"
          required
          class="form-input"
        >
      </div>
    </div>
    <div class="form-actions">
      <span class="total-price" v-if="totalPriceText">{{ totalPriceText }}</span>
      <div class="buttons-container">
        <button type="button" class="cancel-btn" @click="$emit('close')">Cancelar</button>
        <button type="submit" class="edit-btn-orange">Guardar</button>
      </div>
    </div>
  </form>
</template>

<script>
export default {
  name: 'ServiceCardEditForm',
  props: {
    reserva: { type: Object, required: true }
  },
  data () {
    return {
      formData: {
        startDate: '',
        endDate: '',
        quantity: 1
      }
    }
  },
  computed: {
    showQuantityField () {
      return ['mobiliari-decoracio'].includes(this.reserva.service.type)
    },
    totalPriceText () {
      if (!this.formData.startDate || !this.formData.endDate) return ''
      const start = new Date(this.formData.startDate)
      const end = new Date(this.formData.endDate)
      let hours = (end - start) / 3600000
      if (hours <= 0) return ''
      const price = this.getMinPrice()
      if (!price) return ''
      if (['espai', 'musica', 'fotografia'].includes(this.reserva.service.type)) {
        return `Precio total: ${(price * hours).toFixed(2)}€`
      }
      if (this.reserva.service.type === 'catering') {
        const pax = this.reserva.numInvitats || 1
        return `Precio total: ${(price * pax).toFixed(2)}€`
      }
      if (this.reserva.service.type === 'mobiliari-decoracio') {
        const qty = this.formData.quantity || 1
        return `Precio total: ${(price * qty).toFixed(2)}€`
      }
      return ''
    }
  },
  mounted () {
    // Precargar datos si es edición
    if (this.reserva) {
      this.formData.startDate = this.reserva.data_inicio ? this.reserva.data_inicio.replace(' ', 'T').slice(0, 16) : ''
      this.formData.endDate = this.reserva.data_fin ? this.reserva.data_fin.replace(' ', 'T').slice(0, 16) : ''
      this.formData.quantity = this.reserva.cantidad !== undefined ? this.reserva.cantidad : 1
    }
  },
  methods: {
    getMinPrice () {
      if (!this.reserva.service.availability_rules || this.reserva.service.availability_rules.length === 0) return null
      const prices = this.reserva.service.availability_rules
        .map(rule => rule.price)
        .filter(price => typeof price === 'number' && !isNaN(price))
      if (prices.length === 0) return null
      return Math.min(...prices)
    },
    async handleSubmit () {
      // Aquí deberías llamar a la API para actualizar la reserva
      // y emitir el evento 'updated' al terminar
      this.$emit('updated', {
        ...this.reserva,
        data_inicio: this.formData.startDate.replace('T', ' ') + ':00',
        data_fin: this.formData.endDate.replace('T', ' ') + ':00',
        cantidad: this.showQuantityField ? this.formData.quantity : 1
      })
    }
  }
}
</script>

<style scoped>
.add-service-form {
  background: white;
  padding: 1rem;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.form-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}
.form-group {
  flex: 1;
  min-width: 0;
}
.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #374151;
  font-weight: 500;
  font-size: 0.95rem;
}
.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: all 0.2s ease;
  background-color: #f9fafb;
  box-sizing: border-box;
}
.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.form-input:hover {
  border-color: #d1d5db;
}
.form-actions {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 1rem;
  margin-bottom: 0rem;
  position: relative;
}
.buttons-container {
  display: flex;
  gap: 1rem;
  justify-content: center;
  width: 100%;
}
.cancel-btn {
  padding: 0.75rem 1.5rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: white;
  color: #4b5563;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}
.cancel-btn:hover {
  background-color: #f3f4f6;
  border-color: #d1d5db;
}
.edit-btn-orange {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  background-color: rgb(231, 108, 0);
  color: white;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}
.edit-btn-orange:hover {
  background-color: #d35400;
}
.total-price {
  text-align: right;
  color: rgb(145, 2, 38);
  font-weight: 600;
  font-size: 1.1rem;
  white-space: nowrap;
  margin-top: 1rem;
  margin-bottom: -3rem;
}
</style>
