<template>
  <div class="event-card">
    <div class="event-header">
      <h3 class="event-name">
        <i class="bi bi-calendar-event"></i>
        {{ event.name }}  <i class="bi bi-star-fill"></i>  {{ getEventTypeLabel(event.tipus) }}
      </h3>
      <div class="header-actions">
        <span class="event-type">
          {{ event.pressupost }} €
        </span>
        <button v-if="myEvents && !readonly"
                class="delete-event-btn"
                @click="confirmDelete(event.id)"
                title="Eliminar evento">
          <i class="bi bi-trash"></i>
        </button>
      </div>
    </div>
    <div class="event-details">
      <div class="detail-item">
        <span class="detail-title"><i class="bi bi-calendar-check"></i> Fecha inicio</span>
        <span>{{ formatDateTime(event.data_inici) }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-title"><i class="bi bi-calendar-check"></i> Fecha final</span>
        <span>{{ formatDateTime(event.data_fi) }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-title"><i class="bi bi-people"></i> Invitados</span>
        <span>{{ event.num_invitats }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-title"><i class="bi bi-house"></i> Espacio propio</span>
        <span>
          {{ event.espai_propi ? 'Sí' : 'No' }}
          <button v-if="event.espai_propi" class="espai-view-btn" @click.stop="onEspaiPropiClick(event)" title="Ver detalles del espacio propio" aria-label="Ver detalles del espacio propio">
            <i class="bi bi-eye"></i>
          </button>
        </span>
      </div>
    </div>
    <div class="event-status">
      <span :class="['status-badge', getStatusClass(event.estat)]">
        <i v-if="event.estat === 'cancelado'" class="fas fa-times-circle"></i>
        <i v-else-if="event.estat === 'guardado'" class="fas fa-save"></i>
        <i v-else-if="event.estat === 'en_curso'" class="fas fa-hourglass-half"></i>
        <i v-else-if="event.estat === 'pagado'" class="fas fa-check-circle"></i>
        <i v-else-if="event.estat === 'expirado'" class="fas fa-clock"></i>
        <i v-else-if="event.estat === 'finalizado'" class="fas fa-flag-checkered"></i>
        {{ getStatusLabel(event.estat) }}
      </span>
    </div>
    <div class="event-actions">
      <button v-if="showEditButton && myEvents && (event.estat === 'guardado') && !readonly"
              class="edit-event-btn"
              @click="editEvent(event.id)"
              title="Seguir editando">
        <i class="bi bi-pencil-square"></i>
        <span>Editar</span>
      </button>
      <button v-if="myEvents && event.estat === 'guardado' && hasServices && !readonly"
              class="pay-event-btn"
              @click="payEvent(event.id)"
              title="Pagar evento">
        <i class="bi bi-credit-card"></i>
        <span>Pagar</span>
      </button>
      <button v-if="myEvents && event.estat === 'pagado' && !hasStarted && !readonly"
              class="cancel-event-btn"
              @click="confirmCancel(event.id)"
              title="Cancelar evento">
        <i class="bi bi-x-circle"></i>
        <span>Cancelar</span>
      </button>
      <button class="view-details-btn" @click="$emit('view-details', event.id)" title="Ver detalles">
        <i class="bi bi-eye"></i>
        <span>Ver detalles</span>
      </button>
    </div>
  </div>
</template>

<script>
import Swal from 'sweetalert2'
import EspaiPropiServices from '@/services/EspaiPropiServices'
import EspaiPropiDetails from './EspaiPropiDetails.vue'
import EventService from '@/services/EventServices'
import EventServiceServices from '@/services/EventServiceServices'

export default {
  name: 'EventCard',
  props: {
    event: { type: Object, required: true },
    showEditButton: { type: Boolean, default: false },
    myEvents: { type: Boolean, default: false },
    readonly: { type: Boolean, default: false }
  },
  data () {
    return {
      eventServices: []
    }
  },
  created () {
    console.log('EventCard creado para evento:', this.event)
    this.loadEventServices()
  },
  computed: {
    hasStarted () {
      return new Date(this.event.data_inici) < new Date()
    },
    hasServices () {
      return this.eventServices && this.eventServices.length > 0
    },
    statusClass () {
      if (this.readonly) return 'status-expirado'
      return this.getStatusClass(this.event.estat)
    },
    statusLabel () {
      if (this.readonly) return this.getStatusLabel('expirado')
      return this.getStatusLabel(this.event.estat)
    }
  },
  methods: {
    async loadEventServices () {
      try {
        const services = await EventServiceServices.getEventServices(this.event.id)
        this.eventServices = services || []
        console.log('Servicios cargados:', this.eventServices)
      } catch (error) {
        console.error('Error al cargar los servicios del evento:', error)
        this.eventServices = []
      }
    },
    formatDateTime (dateTime) {
      console.log('formatDateTime en EventCard:', 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
    },
    getStatusLabel (status) {
      const statuses = {
        'en_curso': 'En Curso',
        'guardado': 'Guardado',
        'pagado': 'Pagado',
        'expirado': 'Expirado',
        'cancelado': 'Cancelado',
        'finalizado': 'Finalizado'
      }
      return statuses[status] || status
    },
    getStatusClass (status) {
      const classes = {
        'en_curso': 'status-en_curso',
        'guardado': 'status-guardado',
        'pagado': 'status-pagado',
        'expirado': 'status-expirado',
        'cancelado': 'status-cancelado',
        'finalizado': 'status-finalizado'
      }
      return classes[status] || ''
    },
    editEvent (eventId) {
      console.log('editEvent emitido desde EventCard:', eventId)
      this.$router.push(`/eventServices/${eventId}`)
    },
    async onEspaiPropiClick (space) {
      try {
        const spaceDetails = await EspaiPropiServices.getEspaiPropiById(space.espai_propi_id)
        // Renderizar el componente EspaiPropiDetails en el modal
        const container = document.createElement('div')
        const EspaiPropiClass = this.$options.components.EspaiPropiDetails
        const vm = new this.$root.constructor({
          render: h => h(EspaiPropiClass, { props: { espai: spaceDetails } })
        }).$mount(container)
        await Swal.fire({
          title: '',
          html: vm.$el,
          width: '700px',
          showConfirmButton: true,
          confirmButtonColor: '#800020',
          customClass: {
            container: 'space-details-modal'
          }
        })
      } catch (error) {
        console.error('Error al cargar los detalles del espacio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los detalles del espacio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    async confirmDelete (eventId) {
      const result = await Swal.fire({
        title: '¿Estás seguro?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
      })

      if (result.isConfirmed) {
        try {
          await EventService.delete(eventId)
          this.$emit('event-deleted', eventId)
          Swal.fire(
            '¡Eliminado!',
            'El evento ha sido eliminado correctamente',
            'success'
          )
        } catch (error) {
          console.error('Error al eliminar el evento:', error)
          Swal.fire(
            'Error',
            'No se pudo eliminar el evento',
            'error'
          )
        }
      }
    },
    payEvent (eventId) {
      this.$router.push(`/payment/${eventId}`)
    },
    async confirmCancel (eventId) {
      const result = await Swal.fire({
        title: '¿Estás seguro?',
        text: '¿Quieres cancelar este evento? Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Sí, cancelar',
        cancelButtonText: 'No'
      })

      if (result.isConfirmed) {
        try {
          await EventService.update(eventId, { estat: 'cancelado' })
          // Actualizar el estado del evento localmente
          this.event.estat = 'cancelado'
          // Emitir evento de actualización en lugar de eliminación
          this.$emit('event-updated', this.event)
          Swal.fire(
            '¡Cancelado!',
            'El evento ha sido cancelado correctamente',
            'success'
          )
        } catch (error) {
          console.error('Error al cancelar el evento:', error)
          Swal.fire(
            'Error',
            'No se pudo cancelar el evento',
            'error'
          )
        }
      }
    }
  },
  components: {
    EspaiPropiDetails
  }
}
</script>

<style scoped>
.event-card {
  background: white;
  border: none;
  border-radius: 14px;
  padding: 1.5rem 2.5rem 1.2rem 2.5rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.07);
  transition: all 0.2s;
  position: relative;
  overflow: hidden;
  min-width: 600px;
  max-width: 900px;
  margin: 0 auto 1.5rem auto;
}
.event-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.2rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #f0f0f0;
}
.event-name i, .event-type i, .detail-title i {
  font-size: 1rem;
  margin-right: 0.2rem;
  color: #800020;
}
.event-type {
  background: #f8f9fa;
  color: #800020;
  padding: 0.5rem 1.5rem;
  border-radius: 24px;
  font-size: 1.2rem;
  font-weight: 700;
  border: 1px solid rgba(128, 0, 32, 0.1);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.event-details {
  margin-bottom: 0.7rem;
  display: flex;
  flex-wrap: nowrap;
  gap: 3.5rem;
  align-items: flex-end;
  font-size: 1rem;
  justify-content: space-between;
}
.detail-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0.3rem;
  color: #4b5563;
  font-size: 1rem;
  min-width: 120px;
}
.detail-title {
  font-size: 0.92rem;
  color: #800020;
  font-weight: 500;
  margin-bottom: 0.1rem;
  display: flex;
  align-items: center;
}
.espai-view-btn {
  background: transparent;
  border: none;
  color: #2563eb;
  cursor: pointer;
  font-size: 1.1rem;
  margin-left: 0.3rem;
  padding: 0.1rem 0.3rem;
  border-radius: 4px;
  transition: background 0.2s;
}
.espai-view-btn:hover, .espai-view-btn:focus {
  background: #c7d2fe;
  outline: none;
}
.event-status {
  margin-top: 0.2rem;
  margin-bottom: 0.2rem;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.status-badge {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.35rem 1rem;
  border-radius: 16px;
  font-size: 0.95rem;
  font-weight: 600;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  border: none;
}
.status-cancelado {
  background: #ffeaea;
  color: #b91c1c;
  border: 1px solid #fca5a5;
}
.status-guardado {
  background: #e0e7ff;
  color: #2563eb;
  border: 1px solid #60a5fa;
}
.status-en_curso {
  background: #fff7e6;
  color: #d97706;
  border: 1px solid #fbbf24;
}
.status-pagado {
  background: #e6fbe6;
  color: #059669;
  border: 1px solid #34d399;
}
.status-expirado {
  background: #e5e7eb;
  color: #374151;
  border: 1px solid #9ca3af;
}
.status-finalizado {
  background: #ede9fe;
  color: #7c3aed;
  border: 1px solid #a78bfa;
}
.event-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 0.7rem;
  padding-top: 0.7rem;
  border-top: 1px solid #f0f0f0;
}
.edit-event-btn, .view-details-btn {
  padding: 0.5rem 1rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}
.edit-event-btn {
  background: #ff9800;
  color: white;
  border: none;
}
.edit-event-btn:hover {
  background: #f57c00;
  transform: scale(1.05);
}
.view-details-btn {
  background: #800020;
  color: white;
  border: none;
}
.view-details-btn:hover {
  background: #a8324a;
  transform: scale(1.05);
}
.pay-event-btn {
  background: #2196f3;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
}
.pay-event-btn:hover {
  background: #1976d2;
  transform: scale(1.05);
}
.delete-event-btn {
  background: #ffeaea;
  color: #dc3545;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}
.delete-event-btn:hover {
  background: #ffcaca;
  transform: scale(1.05);
}
.cancel-event-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}
.cancel-event-btn:hover {
  background: #c82333;
  transform: scale(1.05);
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
}
</style>
