<template>
  <div class="service-card" :class="type">
    <!-- Cabecera con foto de perfil, nombre y botón eliminar -->
    <div class="service-header">
      <div class="provider-info">
        <div class="provider-avatar">
          <img :src="getProviderPhoto()" :alt="getProviderName()">
        </div>
        <span class="provider-name fw-bold" @click="goToProfile">{{ getProviderName() }}</span>
      </div>
      <div class="action-buttons">
        <button class="action-btn delete" @click="handleDelete">
          <i class="bi bi-trash-fill"></i>
        </button>
      </div>
    </div>

    <!-- Contenido principal del servicio -->
    <div class="service-main">
      <div class="service-image">
        <div class="carousel-container">
          <img v-if="service.images && service.images.length > 0"
               :src="service.images[currentImageIndex]"
               :alt="service.name">
          <img v-else
               :src="getExampleImage()"
               :alt="service.name">
          <div v-if="shouldShowControls" class="carousel-controls">
            <button class="carousel-btn prev" @click.stop="prevImage">
              <i class="bi bi-chevron-left fw-bold"></i>
            </button>
            <button class="carousel-btn next" @click.stop="nextImage">
              <i class="bi bi-chevron-right fw-bold"></i>
            </button>
          </div>
          <div v-if="shouldShowControls" class="carousel-indicators">
            <span v-for="(_, index) in getImages()"
                  :key="index"
                  :class="['indicator', { active: index === currentImageIndex }]"
                  @click.stop="currentImageIndex = index">
            </span>
          </div>
        </div>
      </div>
      <div class="service-content" @click="viewDetails" tabindex="0">
        <div class="service-title-row">
          <h3 class="service-name">{{ service.name }}</h3>
        </div>
        <div class="service-features">
          <div v-if="service.description" class="service-description feature-row">{{ service.description }}</div>
          <div v-if="service.address" class="service-address feature-row"><i class="bi bi-geo-alt"></i> {{ service.address.direccion }}, {{ service.address.ciudad }}, {{ service.address.provincia }}, {{ service.address.codigo_postal }}</div>
          <!-- Espai -->
          <template v-if="service.type === 'espai' && service.espai">
            <div v-if="service.espai.espai_type" class="service-espai-type feature-row"><i class="bi bi-house"></i> Tipo de espacio: {{ service.espai.espai_type }}</div>
            <div v-if="service.espai.capacitat_min || service.espai.capacitat_max" class="service-capacity feature-row">
              <i class="bi bi-people"></i> Capacidad:
              <span v-if="service.espai.capacitat_min">{{ service.espai.capacitat_min }}</span>
              <span v-if="service.espai.capacitat_min && service.espai.capacitat_max"> - </span>
              <span v-if="service.espai.capacitat_max">{{ service.espai.capacitat_max }}</span>
            </div>
            <div v-if="service.espai.address" class="service-address feature-row"><i class="bi bi-geo-alt"></i> {{ service.espai.address.direccion }}, {{ service.espai.address.ciudad }}</div>
          </template>
          <!-- Catering -->
          <template v-else-if="service.type === 'catering' && service.catering">
            <div v-if="service.catering.entrega_type" class="service-entrega-type feature-row"><i class="bi bi-truck"></i> Tipo de entrega: {{ service.catering.entrega_type }}</div>
            <div v-if="service.catering.catering_type" class="service-catering-type feature-row"><i class="bi bi-egg-fried"></i> Tipo de catering: {{ service.catering.catering_type }}</div>
            <div v-if="service.catering.comensals_min || service.catering.comensals_max" class="service-comensals feature-row">
              <i class="bi bi-people"></i> Comensales:
              <span v-if="service.catering.comensals_min">{{ service.catering.comensals_min }}</span>
              <span v-if="service.catering.comensals_min && service.catering.comensals_max"> - </span>
              <span v-if="service.catering.comensals_max">{{ service.catering.comensals_max }}</span>
            </div>
            <div v-if="service.catering.menu" class="service-menu feature-row"><i class="bi bi-list"></i> Menú: {{ service.catering.menu }}</div>
            <div v-if="service.catering.articulo_nombre" class="service-articulo feature-row"><i class="bi bi-list"></i> Artículo: {{ service.catering.articulo_nombre }}</div>
          </template>
          <!-- Mobiliari y Decoració -->
          <template v-else-if="service.type === 'mobiliari-decoracio' && service.mobiliari_decoracio">
            <div v-if="service.mobiliari_decoracio.tipologia" class="service-tipologia feature-row"><i class="bi bi-box"></i> Tipología: {{ service.mobiliari_decoracio.tipologia }}</div>
            <div v-if="service.mobiliari_decoracio.subtipologia" class="service-subtipologia feature-row"><i class="bi bi-box-seam"></i> Subtipología: {{ service.mobiliari_decoracio.subtipologia }}</div>
            <div v-if="service.mobiliari_decoracio.cantidad_min || service.mobiliari_decoracio.cantidad_max" class="service-cantidad feature-row">
              <i class="bi bi-123"></i> Cantidad:
              <span v-if="service.mobiliari_decoracio.cantidad_min">{{ service.mobiliari_decoracio.cantidad_min }}</span>
              <span v-if="service.mobiliari_decoracio.cantidad_min && service.mobiliari_decoracio.cantidad_max"> - </span>
              <span v-if="service.mobiliari_decoracio.cantidad_max">{{ service.mobiliari_decoracio.cantidad_max }}</span>
            </div>
            <div v-if="service.mobiliari_decoracio.alquiler_venta" class="service-alquiler-venta feature-row"><i class="bi bi-currency-euro"></i> {{ service.mobiliari_decoracio.alquiler_venta === 'alquiler' ? 'Alquiler' : 'Venta' }}</div>
          </template>
          <!-- Música -->
          <template v-else-if="service.type === 'musica' && service.musica">
            <div v-if="service.musica.musica_type" class="service-musica-type feature-row"><i class="bi bi-music-note-beamed"></i> Tipo de música: {{ service.musica.musica_type }}</div>
            <div v-if="service.musica.canciones_type" class="service-canciones-type feature-row"><i class="bi bi-music-note-list"></i> Tipo de canciones: {{ service.musica.canciones_type }}</div>
            <div v-if="service.musica.duracion" class="service-duracion feature-row"><i class="bi bi-clock"></i> Duración: {{ service.musica.duracion }}</div>
          </template>
          <!-- Fotografía -->
          <template v-else-if="service.type === 'fotografia' && service.fotografia">
            <div v-if="service.fotografia.fotografia_type" class="service-fotografia-type feature-row"><i class="bi bi-camera"></i> Tipo: {{ service.fotografia.fotografia_type }}</div>
            <div v-if="service.fotografia.fotografia_type === 'servicioespecial' && service.fotografia.servicio_especial" class="service-servicio-especial feature-row"><i class="bi bi-star"></i> Servicio especial: {{ service.fotografia.servicio_especial }}</div>
            <div v-if="service.fotografia.duracion" class="service-duracion feature-row"><i class="bi bi-clock"></i> Duración: {{ service.fotografia.duracion }}</div>
          </template>
        </div>
        <span v-if="getMinPriceFormatted() !== null" class="service-price service-price-bottom">{{ getFormattedPrice() }}</span>
      </div>
    </div>

    <!-- Botón de editar reserva -->
    <div class="card-footer no-gap">
      <button class="edit-reservation-btn" @click="handleEditReservation">
        <i class="bi bi-pencil-fill"></i> Editar reserva
      </button>
    </div>
  </div>
</template>

<script>
import imagenEjemplo from '@/assets/masia_event.jpg'
import imagenEjemplo2 from '@/assets/banquete.jpg'
import defaultAvatar from '@/assets/account_icon.png'
import AccountService from '@/services/AccountServices'
import Swal from 'sweetalert2'

export default {
  name: 'EventServiceCard',
  props: {
    service: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      imagenEjemplo,
      imagenEjemplo2,
      defaultAvatar,
      account: null,
      currentImageIndex: 0
    }
  },
  computed: {
    shouldShowControls () {
      return (this.service.images && this.service.images.length > 1) ||
             (!this.service.images && this.getImages().length > 1)
    }
  },
  async created () {
    try {
      if (this.service.account_id) {
        const response = await AccountService.getAccountById(this.service.account_id)
        this.account = response
      }
    } catch (error) {
      console.error('Error al obtener los datos del proveedor:', error)
    }
  },
  methods: {
    getProviderPhoto () {
      return this.account && this.account.photo ? this.account.photo : this.defaultAvatar
    },
    getProviderName () {
      return this.account && this.account.username ? this.account.username : 'Usuario'
    },
    viewDetails () {
      this.$emit('view-details', this.service)
    },
    goToProfile () {
      if (this.account && this.account.id) {
        this.$router.push({ name: 'profile', params: { id: this.account.id } })
      }
    },
    getMinPrice () {
      if (!this.service.availability_rules || this.service.availability_rules.length === 0) return null
      const prices = this.service.availability_rules
        .map(rule => rule.price)
        .filter(price => typeof price === 'number' && !isNaN(price))
      if (prices.length === 0) return null
      return Math.min(...prices)
    },
    getMinPriceFormatted () {
      const min = this.getMinPrice()
      if (min === null) return null
      return new Intl.NumberFormat('es-ES', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(min)
    },
    getFormattedPrice () {
      const price = this.getMinPriceFormatted()
      if (price === null) return ''

      switch (this.service.type) {
        case 'espai':
          return `Desde ${price}€/h`
        case 'catering':
          return `Desde ${price}€/pax.`
        case 'mobiliari-decoracio':
          return `Desde ${price}€/u`
        case 'musica':
        case 'fotografia':
          return `Desde ${price}€/h`
        default:
          return `Desde ${price}€`
      }
    },
    getImages () {
      return [this.imagenEjemplo, this.imagenEjemplo2]
    },
    getExampleImage () {
      return this.getImages()[this.currentImageIndex]
    },
    nextImage () {
      const images = this.getImages()
      if (images.length > 1) {
        this.currentImageIndex = (this.currentImageIndex + 1) % images.length
      }
    },
    prevImage () {
      const images = this.getImages()
      if (images.length > 1) {
        this.currentImageIndex = (this.currentImageIndex - 1 + images.length) % images.length
      }
    },
    async handleDelete () {
      const result = await Swal.fire({
        title: '¿Estás seguro?',
        text: 'No podrás revertir esta acción',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#800020',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
      })

      if (result.isConfirmed) {
        this.$emit('delete', this.service)
      }
    },
    handleEditReservation () {
      this.$emit('edit', this.service)
    }
  }
}
</script>

<style scoped>
.service-card {
  background: rgb(246, 246, 246);
  border-radius: 5px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  flex-direction: column;
  min-width: 400px;
  min-height: 140px;
  max-width: 1100px;
  width: 100%;
  margin: auto;
}

.service-header {
  width: 100%;
  padding: 0.5rem 1.5rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgba(241, 241, 241, 0.9);
  border-bottom: 1px solid #eee;
  box-sizing: border-box;
  margin: 0;
}

.provider-info {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.provider-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #800020;
  box-sizing: border-box;
  flex-shrink: 0;
}

.provider-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.provider-name {
  font-size: 0.95rem;
  color: #333;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.2s ease;
}

.provider-name:hover {
  color: #800020;
}

.provider-name.fw-bold {
  font-weight: 700;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  background: none;
  border: none;
  padding: 0.5rem;
  cursor: pointer;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: scale(1.1);
}

.action-btn.delete {
  color: #dc3545;
}

.action-btn.delete:hover {
  background-color: rgba(220, 53, 69, 0.1);
}

.service-main {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  flex: 1;
  gap: 0;
}

.service-image {
  flex: 0 0 200px;
  min-width: 350px;
  max-height: 350px;
  width: auto;
  height: auto;
  min-height: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: #f5f5f5;
}

.service-image img {
  width: 100%;
  height: auto;
  max-height: 300px;
  object-fit: cover;
  border-radius: 5px;
}

.carousel-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.carousel-controls {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  pointer-events: none;
}

.carousel-btn {
  background: transparent;
  border: none;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  pointer-events: auto;
  transition: all 0.3s ease;
  position: relative;
}

.carousel-btn::before {
  content: '';
  position: absolute;
  width: 30px;
  height: 30px;
  background: rgba(255, 255, 255, 0.75);
  border-radius: 50%;
  opacity: 0;
  transition: all 0.3s ease;
}

.carousel-btn:hover::before {
  opacity: 0.75;
}

.carousel-btn i {
  color: #800020;
  font-size: 1.25rem;
  position: relative;
  z-index: 1;
  text-shadow: 0 0 3px rgba(255, 255, 255, 1);
}

.carousel-indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  pointer-events: none;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(0, 0, 0, 1);
  cursor: pointer;
  pointer-events: auto;
  transition: all 0.3s ease;
}

.indicator.active {
  background: #800020;
  border-color: rgba(0, 0, 0, 1);
  transform: scale(1.1);
}

.service-content {
  padding: 1rem 1.5rem 0.5rem 1.5rem;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  min-height: 0px;
  min-width: 0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  background: transparent;
}

.service-content:hover {
  background-color: rgb(236, 236, 236);
}

.service-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.service-name {
  font-size: 1.1rem;
  font-weight: 700;
  color: #800020;
  margin-bottom: 0;
  text-align: left;
}

.service-price {
  font-size: 1rem;
  color: #800020;
  font-weight: 600;
  margin-left: auto;
  margin-bottom: 0;
  text-align: right;
}

.service-features {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
  margin-bottom: 0.3rem;
}

.service-description {
  margin-bottom: 0.5rem;
  justify-content: left;
}

.service-address {
  margin-bottom: 0.5rem;
}

.service-capacity {
  margin-bottom: 0.5rem;
}

.service-catering-type {
  margin-bottom: 0.5rem;
}

.service-mobiliari-type {
  margin-bottom: 0.5rem;
}

.service-decoracio-type {
  margin-bottom: 0.5rem;
}

.service-musica-type {
  margin-bottom: 0.5rem;
}

.service-fotografia-type {
  margin-bottom: 0.5rem;
}

.feature-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.2rem;
  width: 100%;
  justify-content: flex-start;
}

.card-footer {
  border: 1px solid #eee;
  background-color: rgba(250, 250, 250, 0.9);
}

.edit-reservation-btn {
  width: 100%;
  padding: 0.5rem;
  background: #4CAF50;
  color: white;
  border: none;
  font-size: 1rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.edit-reservation-btn:hover {
  background: #388e3c;
}

/* Estilos específicos para cada tipo de servicio */
.service-card.catering {
  border-left: 5px solid #800020;
}

.service-card.mobiliari-decoracio {
  border-left: 5px solid #800020;
}

.service-card.musica {
  border-left: 5px solid #800020;
}

.service-card.fotografia {
  border-left: 5px solid #800020;
}

.service-card.espai {
  border-left: 5px solid #800020;
}

.card-footer.no-gap {
  margin-top: 0;
  padding-top: 0;
}

.service-price-bottom {
  display: block;
  margin-top: 0.7rem;
  margin-bottom: 0;
  margin-left: auto;
  text-align: right;
  font-size: 1.1rem;
  font-weight: 700;
  color: #800020;
}

@media (max-width: 900px) {
  .service-card {
    max-width: 100%;
    min-width: 0;
  }
  .service-image {
    flex: 0 0 100px;
    min-width: 200px;
    min-height: 200px;
    width: 100px;
    height: 100px;
  }
}

@media (max-width: 700px) {
  .service-card {
    flex-direction: column;
    max-width: 100%;
    min-width: 0;
    min-height: unset;
  }
  .service-main {
    flex-direction: column;
  }
  .service-image {
    width: 100%;
    height: 120px;
    min-width: 0;
    min-height: 0;
    border-radius: 5px;
  }
  .service-image img {
    border-radius: 5px;
  }
  .service-content {
    padding: 0.5rem;
    min-height: unset;
  }
}
</style>
