<template>
  <div class="page-container" @mousemove="handleMouseMove">
    <!-- Navbar -->
    <nav class="navbar" :class="{ 'navbar-hidden': isNavbarHidden }">
      <div class="navbar-left">
        <img :src="logo" alt="EventAI Logo" class="logo" @click="$router.push('/mainPageVendor')" />
      </div>
      <div class="navbar-center">
        <h1>Detalles del Servicio</h1>
      </div>
      <div class="navbar-right">
        <button class="nav-button back" @click="$router.back()">
          <i class="bi bi-arrow-left"></i>
          Volver
        </button>
      </div>
    </nav>
    <div class="detalles-service-page">
      <div v-if="loading" class="loading">Cargando...</div>
      <div v-else-if="service" class="service-details-layout">
        <div class="content-wrapper">
          <!-- Galería de imágenes -->
          <div class="gallery-column">
            <div class="main-image">
              <img :src="getServiceImages[selectedImg]" :alt="service.name" />
            </div>
            <div class="thumbnails">
              <img
                v-for="(img, idx) in getServiceImages"
                :key="idx"
                :src="img"
                :alt="service.name + ' miniatura ' + idx"
                :class="{ selected: idx === selectedImg }"
                @click="selectedImg = idx"
              />
            </div>
          </div>

          <!-- Columna de información -->
          <div class="info-column">
            <!-- Información Básica -->
            <div class="section basic-info">
              <div class="service-bottoms">
                <div class="action-buttons">
                  <button class="action-btn calendar" @click="handleViewEvents">
                    <i class="bi bi-calendar3"></i>
                    Ver Eventos
                  </button>
                  <button class="action-btn edit" @click="handleEdit">
                    <i class="bi bi-pencil-fill"></i>
                    Editar
                  </button>
                  <button class="action-btn delete" @click="handleDelete">
                    <i class="bi bi-trash-fill"></i>
                    Eliminar
                  </button>
                </div>
              </div>
              <div class="service-header">
                <h2 class="service-name">{{ service.name }}</h2>
              </div>
              <div class="service-price" v-if="minPrice !== null">
                {{ getFormattedPrice() }}
              </div>
              <div class="divider"></div>
              <div class="service-meta">
                <span class="service-type"><i class="bi bi-tag"></i> {{ getServiceTypeDisplay(service) }}</span>
              </div>
              <div class="service-meta">
                <span v-if="service.address" class="service-type">
                  <i class="bi bi-geo-alt"></i>
                  {{ service.address.direccion }}, {{ service.address.ciudad }}, {{ service.address.provincia }}
                </span>
              </div>
              <div class="service-description">
                {{ service.description }}
              </div>
            </div>

            <!-- Características específicas -->
            <div class="service-specific">
              <component
                :is="getSpecificComponent(service.type)"
                v-if="getSpecificComponent(service.type)"
                :service="service"
              />
            </div>

            <!-- Sección de Disponibilidad -->
            <div class="section" v-if="service.availability_rules && service.availability_rules.length">
              <h3>Disponibilidad</h3>
              <div class="availability-grid">
                <div v-for="(rule, idx) in service.availability_rules" :key="idx" class="availability-card">
                  <div class="detail-row">
                    <i class="bi bi-calendar-week"></i>
                    <strong>Días disponibles:</strong>
                    <span>{{ getDiasSemana(rule.dias_semana) }}</span>
                  </div>
                  <div class="detail-row">
                    <i class="bi bi-clock"></i>
                    <strong>Horario:</strong>
                    <span>{{ rule.hora_inicio }} - {{ rule.hora_fin }}</span>
                  </div>
                  <div class="detail-row">
                    <i class="bi bi-currency-euro"></i>
                    <strong>Precio:</strong>
                    <span class="price">{{ rule.price }}€</span>
                  </div>
                  <div class="detail-row">
                    <i class="bi bi-calendar-plus"></i>
                    <strong>Reserva mínima:</strong>
                    <span>{{ rule.min_days_before }} días antes</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="not-found">Servicio no encontrado.</div>
    </div>
  </div>
</template>

<script>
import ServiceServices from '@/services/ServiceServices'
import logo from '@/assets/LogoEventAiTransGran.png'
import banquete from '@/assets/banquete.jpg'
import comidagrupos from '@/assets/comidagrupos.jpg'
import otros from '@/assets/otros.jpg'
import DetallesEspai from './my_services_details/DetallesEspai.vue'
import DetallesCatering from './my_services_details/DetallesCatering.vue'
import DetallesMobiliari from './my_services_details/DetallesMobiliari.vue'
import DetallesDecoracio from './my_services_details/DetallesDecoracio.vue'
import DetallesMusica from './my_services_details/DetallesMusica.vue'
import DetallesFotografia from './my_services_details/DetallesFotografia.vue'
import Swal from 'sweetalert2'
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 EventosDeMiServicio from '../components/myServices/EventosDeMiServicio.vue'

export default {
  name: 'DetallesService',
  components: {
    DetallesEspai,
    DetallesCatering,
    DetallesMobiliari,
    DetallesDecoracio,
    DetallesMusica,
    DetallesFotografia
  },
  data () {
    return {
      loading: true,
      service: null,
      minPrice: null,
      selectedImg: 0,
      logo: logo,
      banquete,
      comidagrupos,
      otros,
      isProcessing: false,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0
    }
  },
  computed: {
    getServiceImages () {
      if (this.service.images && this.service.images.length > 0) {
        return this.service.images
      }
      // Si no hay imágenes, usar una imagen por defecto
      return [require('@/assets/placeholder_image.png')]
    }
  },
  async created () {
    const id = this.$route.params.id
    try {
      const res = await ServiceServices.get(id)
      this.service = res.data
      this.minPrice = this.getMinPriceFormatted()
    } catch (error) {
      this.service = null
    } finally {
      this.loading = false
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    getServiceTypeDisplay (service) {
      if (service.type === 'mobiliari-decoracio' && service.mobiliari_decoracio) {
        return service.mobiliari_decoracio.service_type === 'mobiliario' ? 'Mobiliario' : 'Decoración'
      }
      return service.type.charAt(0).toUpperCase() + service.type.slice(1)
    },
    getMinPrice () {
      if (!this.service || !this.service.availability_rules) 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 () {
      if (this.minPrice === null) return ''

      switch (this.service.type) {
        case 'espai':
          return `Desde ${this.minPrice}€/h`
        case 'catering':
          return `Desde ${this.minPrice}€/pers.`
        case 'mobiliari-decoracio':
          return `Desde ${this.minPrice}€/u`
        case 'musica':
        case 'fotografia':
          return `Desde ${this.minPrice}€/h`
        default:
          return `Desde ${this.minPrice}€`
      }
    },
    getSpecificComponent (type) {
      if (type === 'espai') return 'DetallesEspai'
      if (type === 'catering') return 'DetallesCatering'
      // eslint-disable-next-line camelcase
      if (type === 'mobiliari-decoracio' && this.service.mobiliari_decoracio?.service_type === 'mobiliario') return 'DetallesMobiliari'
      // eslint-disable-next-line camelcase
      if (type === 'mobiliari-decoracio' && this.service.mobiliari_decoracio?.service_type === 'decoracion') return 'DetallesDecoracio'
      if (type === 'musica') return 'DetallesMusica'
      if (type === 'fotografia') return 'DetallesFotografia'
    },
    getDiasSemana (dias) {
      const diasSemana = {
        0: 'Domingo',
        1: 'Lunes',
        2: 'Martes',
        3: 'Miércoles',
        4: 'Jueves',
        5: 'Viernes',
        6: 'Sábado'
      }
      return dias.map(dia => diasSemana[dia]).join(', ')
    },
    async handleDelete () {
      if (this.isProcessing) return

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

        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.deleteMobiliariDecoracio(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.getServiceTypeDisplay(this.service)} ha sido eliminado.`,
            'success'
          )

          this.$router.push('/mainPageVendor')
        }
      } catch (error) {
        console.error('Error al eliminar el servicio:', error)
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'No se pudo eliminar el servicio'
        })
      } finally {
        this.isProcessing = false
      }
    },
    handleEdit () {
      try {
        if (!this.service || !this.service.id) {
          throw new Error('ID de servicio no válido')
        }
        // Determinar el tipo de servicio correcto
        let typeService = this.service.type
        if (typeService === 'mobiliari-decoracio') {
          typeService = this.service.mobiliari_decoracio.service_type
        }

        // Asegurarnos de que tenemos un ID válido
        const serviceId = this.service.id.toString()

        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)
            Swal.fire({
              icon: 'error',
              title: 'Error',
              text: 'Error al navegar a la página de edición'
            })
          }
        })
      } catch (error) {
        console.error('Error al editar:', error)
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Error al intentar editar el servicio'
        })
      }
    },
    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'
        })
      }
    },
    handleScroll () {
      if (this.scrollTimeout) {
        clearTimeout(this.scrollTimeout)
      }

      this.scrollTimeout = setTimeout(() => {
        const currentScroll = window.pageYOffset || document.documentElement.scrollTop

        // Si estamos en la parte superior de la página o scrollY <= 200, siempre mostrar el navbar
        if (currentScroll <= 200) {
          this.isNavbarHidden = false
          return
        }

        const scrollDifference = this.lastScrollTop - currentScroll

        if (currentScroll > this.lastScrollTop && currentScroll > 200) {
          // Scrolling down & past threshold
          this.isNavbarHidden = true
        } else if (scrollDifference > 10 && currentScroll > 0) {
          // Scrolling up with significant difference
          this.isNavbarHidden = false
        }

        this.lastScrollTop = currentScroll <= 0 ? 0 : currentScroll
      }, 50)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      // Mostrar la barra cuando el ratón está en los primeros 100px de la ventana
      this.isNavbarHidden = this.mouseY > 110
    }
  }
}
</script>

<style scoped>
.page-container {
  padding-top: 140px;
  min-height: 100vh;
  background: #f8f9fa;
  background-image: url('../assets/foto_horizontal_3colores.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  background-repeat: no-repeat;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 2rem;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  width: auto;
  margin-bottom: 2rem;
  backdrop-filter: blur(5px);
  transition: transform 0.3s ease-in-out;
}

.navbar-hidden {
  transform: translateY(-100%);
}

.navbar-left .logo {
  height: 80px;
  width: auto;
  cursor: pointer;
}

.navbar-center h1 {
  color: #800020;
  font-size: 2rem;
  margin: 0;
  flex-grow: 1;
  text-align: center;
}

.nav-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.7rem 1.2rem;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
}

.back {
  background-color: #2C3E50;
  color: white;
}

.back:hover {
  background-color: #1a252f;
  transform: translateY(-2px);
}

.section h3 {
  color: #800020;
  margin: 0 0 1rem 0;
  font-size: 1.2rem;
  font-weight: 600;
}

.detalles-service-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem 2rem 2rem;
}

.service-details-layout {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  padding: 2.5rem 2rem;
  max-width: 1200px;
  margin: 0 auto;
  backdrop-filter: blur(5px);
}

.content-wrapper {
  display: flex;
  gap: 2.5rem;
}

.gallery-column {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 1.2rem;
  width: 450px;
  flex-shrink: 0;
}

.main-image {
  width: 450px;
  height: 350px;
  background: #f5f5f5;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.thumbnails {
  display: flex;
  flex-direction: row;
  gap: 0.5rem;
  width: 100%;
  overflow-x: auto;
  padding-bottom: 0.5rem;
}

.thumbnails img {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: border 0.2s;
  flex-shrink: 0;
}

.thumbnails img.selected {
  border: 2px solid #800020;
}

.info-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  min-width: 0;
}

.basic-info {
  margin-bottom: 0rem;
}

.service-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.service-bottoms {
  display: flex;
  align-items: center;
  justify-content: right;
  gap: 0.5rem;
  margin-bottom: 0rem;
}

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

.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;
  font-size: 0.9rem;
}

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

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

.action-btn.edit {
  color: #0d6efd;
}

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

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

.service-name {
  color: #800020;
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
  font-weight: 700;
}

.service-price {
  color: #800020;
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 1rem;
}

.divider {
  height: 2px;
  background-color: #eee;
  margin: 1.5rem 0;
}

.service-meta {
  display: flex;
  gap: 2rem;
  align-items: center;
  margin-bottom: 1rem;
}

.service-type {
  color: #333;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  white-space: nowrap;
  margin-left: 1.25rem;
}

.service-address {
  color: #444;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  flex: 1;
  min-width: 0;
}

.service-description {
  color: #666;
  font-size: 0.95rem;
  line-height: 1.6;
  margin-top: 1rem;
  text-align: left;
  margin-left: 1.25rem;
}

.service-specific {
  background: #fff;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.section {
  background: #fff;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  width: auto;
}

.availability-grid {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 1rem;
  width: auto;
}

.availability-card {
  background: rgb(245, 245, 245);
  border-radius: 8px;
  padding: 1.2rem;
  border: 1px solid #e9ecef;
  width: auto;
}

.detail-row {
  font-size: 1rem;
  color: #333;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  flex-wrap: nowrap;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row i {
  color: #333;
  font-size: 1.1rem;
  flex-shrink: 0;
}

.detail-row strong {
  color: #333;
  font-weight: 700;
  flex-shrink: 0;
  margin-right: 0.2rem;
}

.detail-row span {
  color: #666;
}

.detail-row .price {
  color: #800020;
  font-weight: 600;
}

.loading {
  text-align: center;
  color: #800020;
  font-size: 1.2rem;
}

.not-found {
  text-align: center;
  color: #c00;
  font-size: 1.2rem;
}

@media (max-width: 900px) {
  .content-wrapper {
    flex-direction: column;
    gap: 1.5rem;
  }
  .gallery-column {
    width: 100%;
  }
  .main-image {
    width: 100%;
    height: 250px;
  }
  .thumbnails img {
    width: 60px;
    height: 45px;
  }
  .service-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  .service-address {
    width: 100%;
  }
  .detail-row {
    flex-direction: column;
    align-items: flex-start;
    margin-left: 1.7rem;
    gap: 0.3rem;
  }
  .detail-row span {
    width: 100%;
  }
}
</style>
