<template>
  <div class="event-details-container">
    <div v-if="loading" class="loading">Cargando detalles del evento...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <!-- Cabecera evento -->
      <div class="event-header-block">
        <div class="event-title-row">
          <h2 class="event-title">
            <i class="bi bi-calendar-event"></i> {{ event.name }}
            <span class="event-type-badge"><i class="bi bi-star-fill"></i> {{ getEventTypeLabel(event.tipus) }}</span>
          </h2>
        </div>
        <div class="event-budget"><i class="bi bi-cash"></i> <span class="budget-label">Presupuesto:</span> <span class="budget-amount">{{ event.pressupost }} €</span></div>
        <div class="event-meta-centered">
          <span><i class="bi bi-calendar-check"></i> {{ formatDateTime(event.data_inici) }}</span>
          <span><i class="bi bi-calendar-check"></i> {{ formatDateTime(event.data_fi) }}</span>
          <span><i class="bi bi-people"></i> {{ event.num_invitats }} invitados</span>
        </div>
      </div>
      <!-- Espacio propio -->
      <div v-if="event.espai_propi" class="espai-propi-block-compact">
        <div class="espai-propi-title"><i class="bi bi-house-door-fill"></i> Espacio propio</div>
        <div class="espai-propi-grid-v2">
          <div class="espai-row espai-row-main">
            <div><i class="bi bi-building"></i> <strong>Nombre:</strong> {{ event.espai_propi.nombre }}</div>
            <div><i class="bi bi-geo"></i> <strong>Tipo:</strong> {{ event.espai_propi.tipus }}</div>
            <div><i class="bi bi-people"></i> <strong>Capacidad:</strong> {{ event.espai_propi.capacitat_aproximada }}</div>
          </div>
          <div class="espai-row espai-row-desc">
            <i class="bi bi-info-circle"></i> <strong>Descripción:</strong> {{ event.espai_propi.descripcion }}
          </div>
          <div class="espai-row espai-row-dir">
            <i class="bi bi-geo-alt"></i> <strong>Dirección:</strong> {{ event.espai_propi.address.direccion }}, {{ event.espai_propi.address.ciudad }} ({{ event.espai_propi.address.codigo_postal }}, {{ event.espai_propi.address.provincia }})
          </div>
        </div>
        <div class="espai-caracteristicas"><strong>Características:</strong> <span v-for="c in event.espai_propi.caracteristicas" :key="c" class="espai-feature">{{ c }}</span></div>
      </div>
      <!-- Servicios -->
      <div class="services-section">
        <h3 class="section-title">Servicios contratados</h3>
        <div v-if="orderedServices.length === 0" class="no-services">No hay servicios contratados.</div>
        <div v-else>
          <template v-for="type in serviceTypes">
            <div v-if="servicesByType(type).length" :key="type">
              <h4 class="service-type-title">{{ getServiceTypeLabel(type) }}</h4>
              <div class="service-type-list service-type-list-fullwidth">
                <template v-for="service in servicesByType(type)">
                  <GeneralEventServiceCard
                    v-if="!readonly"
                    :key="service.id"
                    :reserva="service"
                    @updated="fetchEvent"
                    @update-event-info="fetchEvent"
                  />
                  <ReadOnlyEventServiceCard
                    v-else
                    :key="service.id"
                    :reserva="service"
                  />
                </template>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import EventServiceServices from '@/services/EventServiceServices'
import GeneralEventServiceCard from './GeneralEventServiceCard.vue'
import ReadOnlyEventServiceCard from './ReadOnlyEventServiceCard.vue'

export default {
  name: 'EventDetails',
  props: {
    eventId: { type: String, required: true },
    readonly: { type: Boolean, default: false }
  },
  components: {
    GeneralEventServiceCard,
    ReadOnlyEventServiceCard
  },
  data () {
    return {
      event: null,
      loading: true,
      error: null,
      serviceTypes: ['espai', 'catering', 'mobiliari', 'decoracio', 'musica', 'fotografia']
    }
  },
  computed: {
    orderedServices () {
      if (!this.event || !this.event.services) return []
      const order = this.serviceTypes
      return [...this.event.services].sort((a, b) => order.indexOf(a.service.type) - order.indexOf(b.service.type))
    },
    isEventEditable () {
      return !this.readonly && this.event && this.event.estat === 'guardado'
    }
  },
  methods: {
    async fetchEvent () {
      console.log('[EventDetails] fetchEvent llamado con eventId:', this.eventId)
      this.loading = true
      this.error = null
      try {
        // 1. Datos generales del evento
        const eventGeneral = await EventServiceServices.getAllServicesForEvent(this.eventId)
        // 2. Servicios contratados (relación evento-servicio)
        const res = await EventServiceServices.getEventServices(this.eventId)
        console.log('Respuesta CRUDA de getEventServices:', res)
        // 3. Mezclar ambos
        this.event = {
          ...eventGeneral,
          services: res
        }
        console.log('[EventDetails] Evento final:', this.event)
      } catch (e) {
        console.error('[EventDetails] Error al cargar detalles del evento:', e)
        this.error = 'No se pudieron cargar los detalles del evento.'
      }
      this.loading = false
    },
    formatDateTime (dateTime) {
      return new Date(dateTime).toLocaleString('es-ES', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getEventTypeLabel (type) {
      const types = {
        'boda': 'Boda',
        'graduacio': 'Graduación',
        'festa': 'Fiesta',
        'celebracio': 'Celebración',
        'menjar_grup': 'Comida de Grupo',
        'altres': 'Otros'
      }
      return types[type] || type
    },
    getServiceTypeLabel (type) {
      const map = {
        espai: 'Espacio',
        catering: 'Catering',
        mobiliari: 'Mobiliario',
        decoracio: 'Decoración',
        musica: 'Música',
        fotografia: 'Fotografía'
      }
      return map[type] || type
    },
    servicesByType (type) {
      if (!this.event || !this.event.services) return []
      return this.event.services.filter(s => s.service && s.service.type === type)
    },
    async deleteService (service) {
      if (confirm('¿Seguro que quieres eliminar este servicio del evento?')) {
        try {
          await EventServiceServices.removeServiceFromEvent(this.eventId, service.id)
          this.fetchEvent()
        } catch (e) {
          alert('No se pudo eliminar el servicio.')
        }
      }
    },
    editService (service) {
      this.$emit('edit-service', service)
    }
  },
  mounted () {
    console.log('[EventDetails] mounted, eventId:', this.eventId)
    this.fetchEvent()
  }
}
</script>

<style scoped>
.event-details-container {
  padding: 2rem 1rem;
  max-width: 900px;
  margin: 0 auto;
}
.loading, .error {
  color: #800020;
  font-weight: 500;
  text-align: center;
  margin: 2rem 0;
}
.event-header-block {
  margin-bottom: 2.5rem;
  text-align: center;
}
.event-title-row {
  display: flex;
  justify-content: center;
  align-items: center;
}
.event-title {
  color: #800020;
  font-size: 2rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 1.2rem;
  margin-bottom: 0.5rem;
}
.event-type-badge {
  background: #f8f9fa;
  color: #800020;
  border-radius: 16px;
  padding: 0.3rem 1.1rem;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.4rem;
}
.event-budget {
  margin: 0.5rem 0 0.7rem 0;
  font-size: 1.15rem;
  color: #800020;
  font-weight: 600;
}
.budget-label {
  font-weight: 500;
}
.budget-amount {
  font-weight: 700;
  color: #800020;
  margin-left: 0.2rem;
}
.event-meta-centered {
  display: flex;
  justify-content: center;
  gap: 2.5rem;
  color: #444;
  font-size: 1.1rem;
  margin-top: 0.7rem;
}
.event-meta-centered i {
  color: #800020;
  margin-right: 0.3rem;
}
.espai-propi-block-compact {
  background: #e0e7ff;
  border-radius: 12px;
  padding: 1.2rem 2rem;
  margin-bottom: 2.5rem;
  margin-top: 1.5rem;
}
.espai-propi-title {
  color: #2563eb;
  font-size: 1.2rem;
  font-weight: 700;
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.espai-propi-grid-v2 {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  color: #222;
  margin-bottom: 0.7rem;
}
.espai-row {
  display: flex;
  gap: 2.5rem;
  align-items: center;
}
.espai-row-main > div {
  min-width: 180px;
}
.espai-row-desc, .espai-row-dir {
  margin-left: 1.5rem;
  margin-top: 0.2rem;
}
.espai-caracteristicas {
  grid-column: 1 / -1;
  margin-top: 0.5rem;
}
.espai-feature {
  background: #c7d2fe;
  color: #2563eb;
  border-radius: 8px;
  padding: 0.2rem 0.7rem;
  margin-right: 0.4rem;
  font-size: 0.95rem;
  margin-bottom: 0.2rem;
  display: inline-block;
}
.services-section {
  margin-top: 2rem;
}
.section-title {
  color: #800020;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  font-weight: 600;
}
.no-services {
  text-align: center;
  color: #666;
  padding: 2rem;
  background: #f8f9fa;
  border-radius: 8px;
  margin: 1rem 0;
}
.service-type-title {
  color: #800020;
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
}
.service-type-list {
  display: grid;
  gap: 1.5rem;
}
.service-type-list-fullwidth {
  grid-column: 1 / -1;
}
</style>
