<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">
            <!-- Información del usuario -->
            <div class="user-info" v-if="account && service.account_id">
              <img :src="account.photo || defaultProfile" alt="Foto de perfil" class="profile-image" />
              <router-link :to="'/profile/' + service.account_id" class="username">
                {{ account.username }}
              </router-link>
            </div>
            <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">
              <h2 class="service-name">{{ service.name }}</h2>
              <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 AccountService from '@/services/AccountServices'
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 defaultProfile from '@/assets/user_icon.png'
import DetallesEspai from './services_details/detallesEspai.vue'
import DetallesCatering from './services_details/detallesCatering.vue'
import DetallesMobiliari from './services_details/detallesMobiliari.vue'
import DetallesDecoracio from './services_details/detallesDecoracio.vue'
import DetallesMusica from './services_details/detallesMusica.vue'
import DetallesFotografia from './services_details/detallesFotografia.vue'

export default {
  name: 'DetallesService',
  components: {
    DetallesEspai,
    DetallesCatering,
    DetallesMobiliari,
    DetallesDecoracio,
    DetallesMusica,
    DetallesFotografia
  },
  data () {
    return {
      loading: true,
      service: null,
      account: null,
      minPrice: null,
      selectedImg: 0,
      logo: logo,
      banquete,
      comidagrupos,
      otros,
      defaultProfile,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0,
      observer: null
    }
  },
  computed: {
    getServiceImages () {
      // Si es un servicio de catering y no tiene imágenes, usar imágenes de ejemplo
      if (this.service?.type === 'catering') {
        return [this.banquete, this.comidagrupos, this.otros]
      }
      // Para otros tipos de servicios, 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
      if (this.service.account_id) {
        const accountRes = await AccountService.getAccountById(this.service.account_id)
        this.account = accountRes
      }
      this.minPrice = this.getMinPriceFormatted()
    } catch (error) {
      console.error('Error:', error)
      this.service = null
    } finally {
      this.loading = false
    }
  },
  mounted () {
    // Configurar el Intersection Observer
    this.observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          this.isNavbarHidden = false
        } else {
          // Solo ocultar el navbar si no estamos en la parte superior
          const currentScroll = window.pageYOffset || document.documentElement.scrollTop
          if (currentScroll > 200) {
            this.isNavbarHidden = true
          }
        }
      })
    }, {
      threshold: 0.1 // El callback se ejecutará cuando al menos el 10% del elemento sea visible
    })

    // Observar el primer elemento después del navbar
    const firstElement = document.querySelector('.detalles-service-page')
    if (firstElement) {
      this.observer.observe(firstElement)
    }
  },
  beforeDestroy () {
    if (this.observer) {
      this.observer.disconnect()
    }
  },
  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(', ')
    },
    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-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;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin-bottom: 0.5rem;
  width: 100%;
}

.profile-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #800020;
}

.username {
  color:#333;
  font-weight: 600;
  text-decoration: none;
  font-size: 1rem;
  transition: color 0.3s;
}

.username:hover {
  color: #800020;
}

@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>
