<template>
    <div class="service-card" :class="type" v-if="service">
        <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 calendar" @click="handleViewEvents">
            <i class="bi bi-calendar3"></i>
            </button>
            <button class="action-btn edit" @click="handleEdit">
            <i class="bi bi-pencil-fill"></i>
            </button>
            <button class="action-btn delete" @click="handleDelete">
            <i class="bi bi-trash-fill"></i>
            </button>
        </div>
        </div>
        <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">
            <h3 class="service-name">{{ service.name }}</h3>
            </div>
            <div class="service-features">
            <slot name="additional-info"></slot>
            </div>
            <span v-if="getMinPriceFormatted() !== null" class="service-price">{{ getFormattedPrice() }}</span>
        </div>
        </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 EspaiServices from '@/services/EspaiServices'
import CateringServices from '@/services/CateringServices'
import MobiliariDecoracioServices from '@/services/MobiliariDecoracioServices'
import MusicaServices from '@/services/MusicaServices'
import FotografiaServices from '@/services/FotografiaServices'
import EventServiceServices from '@/services/EventServiceServices'
import Swal from 'sweetalert2'
import EventosDeMiServicio from './EventosDeMiServicio.vue'

export default {
  name: 'ServiceCard',
  props: {
    service: {
      type: Object,
      required: true,
      validator: function (obj) {
        return obj && obj.id && typeof obj.id === 'string'
      }
    },
    type: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      imagenEjemplo,
      imagenEjemplo2,
      defaultAvatar,
      account: null,
      currentImageIndex: 0,
      isProcessing: false
    }
  },
  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.$router.push({ name: 'mydetallesService', params: { id: this.service.id } })
    },
    handleEdit () {
      try {
        if (!this.service || !this.service.id) {
          throw new Error('ID de servicio no válido')
        }
        console.log('Editando servicio:', {
          id: this.service.id,
          type: this.service.type,
          service: this.service
        })

        // Determinar el tipo de servicio correcto
        let typeService = this.service.type
        console.log('service', this.service)
        if (typeService === 'mobiliari-decoracio') {
          typeService = this.service.mobiliari_decoracio.service_type
        }
        console.log('typeService', typeService)

        // Asegurarnos de que tenemos un ID válido
        const serviceId = this.service.id.toString()
        console.log('serviceId', serviceId)
        this.$router.push({
          name: 'editService',
          params: {
            type_service: typeService,
            service_id: serviceId
          }
        }).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            console.error('Error de navegación:', err)
            this.showError('Error al navegar a la página de edición')
          }
        })
      } catch (error) {
        console.error('Error al editar:', error)
        this.showError('Error al intentar editar el servicio')
      }
    },
    async handleDelete () {
      if (this.isProcessing) return

      try {
        if (!this.service || !this.service.id) {
          throw new Error('ID de servicio no válido')
        }

        console.log('Intentando eliminar servicio:', this.service.id)
        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.isProcessing = true
          let response

          switch (this.service.type) {
            case 'espai':
              response = await EspaiServices.deleteEspai(this.service.id)
              break
            case 'catering':
              response = await CateringServices.deleteCatering(this.service.id)
              break
            case 'mobiliari-decoracio':
              response = await MobiliariDecoracioServices.deleteMobiliari(this.service.id)
              break
            case 'musica':
              response = await MusicaServices.deleteMusica(this.service.id)
              break
            case 'fotografia':
              response = await FotografiaServices.deleteFotografia(this.service.id)
              break
            default:
              throw new Error('Tipo de servicio no válido')
          }

          console.log('Respuesta de eliminación:', response)

          await Swal.fire(
            '¡Eliminado!',
            `El servicio de ${this.getServiceTypeName()} ha sido eliminado.`,
            'success'
          )

          this.$emit('service-deleted', this.service.id)
          window.location.reload()
        }
      } catch (error) {
        console.error('Error al eliminar el servicio:', this.service.id, error)
        this.showError('Error al eliminar el servicio', error)
      } finally {
        this.isProcessing = false
      }
    },
    getServiceTypeName () {
      const types = {
        'espai': 'espacio',
        'catering': 'catering',
        'mobiliari-decoracio': 'mobiliario y decoración',
        'musica': 'música',
        'fotografia': 'fotografía'
      }
      return types[this.service.type] || this.service.type
    },
    showError (message) {
      Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: message || 'Ha ocurrido un error inesperado.'
      })
    },
    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}€/pers.`
        case 'mobiliari-decoracio':
          return `Desde ${price}€/u`
        case 'musica':
        case 'fotografia':
          return `Desde ${price}€/h`
        default:
          return `Desde ${price}€`
      }
    },
    goToProfile () {
      if (this.account && this.account.id) {
        this.$router.push({ name: 'profile', params: { id: this.account.id } })
      }
    },
    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 handleViewEvents () {
      try {
        if (!this.service || !this.service.id) {
          throw new Error('ID de servicio no válido')
        }

        const response = await EventServiceServices.getEventsForService(this.service.id)
        const events = response.data

        // Crear un contenedor para montar el componente
        const container = document.createElement('div')
        const EventosDeMiServicioClass = this.$options.components.EventosDeMiServicio || EventosDeMiServicio
        const vm = new this.$root.constructor({
          render: h => h(EventosDeMiServicioClass, {
            props: {
              events,
              serviceId: this.service.id
            }
          })
        }).$mount(container)

        await Swal.fire({
          title: '',
          html: vm.$el,
          width: '800px',
          showConfirmButton: true,
          confirmButtonColor: '#800020',
          customClass: {
            container: 'eventos-servicio-modal-swal'
          }
        })
      } catch (error) {
        console.error('Error al obtener los eventos:', error)
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'No se pudieron obtener los eventos asociados a este servicio'
        })
      }
    }
  },
  watch: {
    service: {
      immediate: true,
      handler (newVal) {
        if (!newVal || !newVal.id) {
          console.error('Servicio inválido:', newVal)
        }
      }
    }
  },
  components: {
    EventosDeMiServicio
  }
}
</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;
}

.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;
  margin-right: 3rem;
}

.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.edit {
  color: #0d6efd;
}

.action-btn.edit:hover {
  background-color: rgba(13, 110, 253, 0.1);
}

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

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

.action-btn.calendar {
  color: #28a745;
}

.action-btn.calendar:hover {
  background-color: rgba(40, 167, 69, 0.1);
}

.action-btn i {
  font-size: 1.1rem;
}

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

.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;
}

.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-btn:hover i {
  color: #800020;
}

.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);
}

.indicator:hover {
  background: rgba(255, 255, 255, 0.5);
  border-color: rgba(0, 0, 0, 1);
}

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

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

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

.service-title {
  margin-bottom: 0rem;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
}

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

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

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

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

.service-card.mobiliari-decoracio {
  border-left: 4px solid #4ECDC4;
}

.service-card.musica {
  border-left: 4px solid #FFD93D;
}

.service-card.fotografia {
  border-left: 4px solid #95E1D3;
}

.service-card.espai {
  border-left: 4px solid #6C5CE7;
}

@media (max-width: 900px) {
  .service-card {
    max-width: 100%;
    min-width: 0;
  }
  .service-image {
    flex: 0 0 100px;
    min-width: 100px;
    min-height: 100px;
    width: 100px;
    height: 100px;
  }
  .service-content {
    padding: 0.5rem 0.5rem;
    min-height: 80px;
  }
}

@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;
  }
  .action-buttons {
    gap: 0.3rem;
  }
  .action-btn {
    padding: 0.4rem;
  }
  .action-btn i {
    font-size: 1rem;
  }
}
</style>
