<template>
  <div class="general-event-service-card">
    <div class="card-content">
      <!-- Columna de imagen -->
      <div class="image-column">
        <img :src="mainImage" alt="Imagen del servicio" class="service-image" />
      </div>
      <!-- Columna de información -->
      <div class="info-column">
        <div class="info-header">
          <div class="service-title">
            <strong>{{ reserva.service.name }}</strong>
            <span v-if="serviceTypeLabel">({{ serviceTypeLabel }})</span>
          </div>
          <div class="action-buttons">
            <button class="details-btn" @click="goToDetails">
              <i class="bi bi-eye"></i>
              Ver
            </button>
            <button class="delete-btn" @click="emitDelete">
              <i class="bi bi-trash"></i>
              Eliminar
            </button>
          </div>
        </div>
        <div class="service-info">
          <div><strong>Fecha inicio:</strong> {{ formatDate(reserva.data_inicio) }}</div>
          <div><strong>Fecha fin:</strong> {{ formatDate(reserva.data_fin) }}</div>
          <div><strong>Cantidad:</strong> {{ reserva.cantidad }}</div>
          <div><strong>Precio total:</strong> {{ reserva.price_total }} €</div>
          <div v-if="reserva.service.address">
            <strong>Dirección:</strong> {{ formatAddress(reserva.service.address) }}
          </div>
          <div v-if="caracteristicas && caracteristicas.length">
            <strong>Características:</strong> {{ caracteristicas.join(', ') }}
          </div>
        </div>
        <div class="edit-btn-wrapper" v-if="!editMode">
          <button class="edit-btn-orange" @click="editMode = true">Editar reserva</button>
        </div>
        <div v-else class="edit-form-wrapper">
          <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="editMode = false">Cancelar</button>
                <button type="submit" class="edit-btn-orange">Guardar</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ServiceCardEditForm from './ServiceCardEditForm.vue'
import EventServiceServices from '@/services/EventServiceServices'
import Swal from 'sweetalert2'
export default {
  name: 'GeneralEventServiceCard',
  props: {
    reserva: { type: Object, required: true },
    onRemove: { type: Function, required: false },
    onEdit: { type: Function, required: false }
  },
  components: { ServiceCardEditForm },
  data () {
    return {
      showDeleteConfirm: false,
      editMode: false,
      formData: {
        startDate: '',
        endDate: '',
        quantity: 1
      }
    }
  },
  computed: {
    mainImage () {
      return this.reserva.service.images && this.reserva.service.images.length > 0
        ? this.reserva.service.images[0]
        : 'https://via.placeholder.com/300x200?text=Sin+imagen'
    },
    serviceTypeLabel () {
      return this.reserva.service.type || ''
    },
    caracteristicas () {
      if (this.reserva.service.espai && this.reserva.service.espai.caracteristiques) {
        return this.reserva.service.espai.caracteristiques
      }
      return []
    },
    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: {
    goToDetails () {
      this.$router.push({ name: 'detallesService', params: { id: this.reserva.service.id } })
    },
    emitDelete () {
      if (this.onRemove) this.onRemove(this.reserva)
    },
    handleUpdated () {
      this.editMode = false
      if (this.onEdit) this.onEdit(this.reserva)
    },
    formatDate (dateStr) {
      if (!dateStr) return '-'
      const d = new Date(dateStr)
      return d.toLocaleString('es-ES', { dateStyle: 'short', timeStyle: 'short' })
    },
    formatAddress (addr) {
      if (!addr) return ''
      return `${addr.direccion}, ${addr.ciudad} (${addr.codigo_postal})`
    },
    getMinPrice () {
      return this.reserva.service.price || 0
    },
    async handleSubmit () {
      try {
        // Asegurarnos de que las fechas son válidas
        if (!this.formData.startDate || !this.formData.endDate) {
          throw new Error('Las fechas son requeridas')
        }

        // Convertir las fechas a objetos Date
        const startDateObj = new Date(this.formData.startDate)
        const endDateObj = new Date(this.formData.endDate)

        // Validar que las fechas son válidas
        if (isNaN(startDateObj.getTime()) || isNaN(endDateObj.getTime())) {
          throw new Error('Las fechas no son válidas')
        }

        // Validar que la fecha de fin es posterior a la fecha de inicio
        if (endDateObj <= startDateObj) {
          throw new Error('La fecha de fin debe ser posterior a la fecha de inicio')
        }

        // Formatear las fechas en el formato esperado por el backend, manteniendo la zona horaria local
        const formatDate = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }

        const startDate = formatDate(startDateObj)
        const endDate = formatDate(endDateObj)

        const payload = {
          cantidad: this.showQuantityField ? this.formData.quantity
            : ['espai', 'musica', 'fotografia'].includes(this.reserva.service.type) ? 1
              : this.reserva.service.type === 'catering' ? this.reserva.numInvitats : 1,
          data_fin: endDate,
          data_inicio: startDate
        }
        // eslint-disable-next-line
        const response = await EventServiceServices.updateServiceInEvent(
          this.reserva.event_id,
          this.reserva.service.id,
          payload
        )

        // Si llegamos aquí, la actualización fue exitosa
        this.editMode = false
        this.$emit('updated', this.reserva)
        this.$emit('update-event-info')

        // Mostrar mensaje de éxito
        Swal.fire({
          icon: 'success',
          title: 'Éxito',
          text: 'La reserva se ha actualizado correctamente',
          timer: 2000,
          showConfirmButton: false
        })
      } catch (error) {
        console.error('Error al editar el servicio:', error)
        let errorMessage = 'No se pudo editar el servicio. Por favor, intenta de nuevo.'

        if (error.response?.data?.detail) {
          errorMessage += ` ${error.response.data.detail}`
        } else if (error.message) {
          errorMessage += ` ${error.message}`
        }

        Swal.fire({
          icon: 'error',
          title: 'Error',
          html: errorMessage
        })
      }
    }
  }
}
</script>

<style scoped>
.general-event-service-card {
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  margin-bottom: 24px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  overflow: hidden;
}
.card-content {
  display: flex;
  flex-direction: row;
}
.image-column {
  flex: 0 0 260px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f7f7;
}
.service-image {
  width: 240px;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
}
.info-column {
  flex: 1;
  padding: 24px 24px 16px 24px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
  text-align: left;
}
.info-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}
.service-title {
  font-size: 1.2em;
  font-weight: bold;
}
.action-buttons {
  display: flex;
  gap: 8px;
}
.details-btn, .delete-btn {
  background: #fff;
  border: 1px solid #1976d2;
  color: #1976d2;
  border-radius: 6px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 0.95em;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.delete-btn {
  border-color: #e53935;
  color: #e53935;
}
.details-btn:hover {
  background: #e3f2fd;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.delete-btn:hover {
  background: #ffebee;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.service-info {
  margin-bottom: 18px;
}
.edit-btn-wrapper {
  margin-top: auto;
}
.edit-btn-orange {
  width: 100%;
  background: rgb(231, 108, 0);
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 10px 0;
  font-size: 1em;
  cursor: pointer;
  margin-top: 10px;
  transition: all 0.2s ease;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.edit-btn-orange:hover {
  background: #d35400;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.edit-form-wrapper {
  margin-top: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}
.add-service-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}
.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.form-group label {
  font-weight: 500;
  color: #495057;
}
.form-input {
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 0.95em;
  transition: border-color 0.2s;
}
.form-input:focus {
  outline: none;
  border-color: #1976d2;
}
.form-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 8px;
}
.buttons-container {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: white;
  color: #4b5563;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}
.cancel-btn:hover {
  background-color: #f3f4f6;
  border-color: #d1d5db;
}
.total-price {
  text-align: right;
  color: rgb(145, 2, 38);
  font-weight: 600;
  font-size: 1.1rem;
  white-space: nowrap;
}
</style>
