<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>Editar 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="create-service-page">
      <!-- Formulario común para todos los servicios -->
      <div v-if="selectedType" class="service-form-container">
        <div class="form-card">
          <h5 class="avis-campos">* campo obligatorio</h5>
          <!-- Información General -->
          <div class="form-section">
            <h3><i class="bi bi-info-circle"></i> Información General</h3>

            <!-- Nombre -->
            <div class="form-group">
              <label for="name">
                <i class="bi bi-tag"></i> Nombre del Servicio*
              </label>
              <input
                id="name"
                v-model="commonData.name"
                type="text"
                class="form-control"
                required
              />
            </div>

            <!-- Descripción -->
            <div class="form-group">
              <label for="description">
                <i class="bi bi-card-text"></i> Descripción*
              </label>
              <textarea
                id="description"
                v-model="commonData.description"
                class="form-control"
                rows="4"
                required
              ></textarea>
            </div>

            <!-- Imágenes -->
            <div class="form-group">
              <label>
                <i class="bi bi-images"></i> Imágenes*
              </label>
              <button class="btn-upload" @click="triggerImageUpload">
                <i class="bi bi-cloud-upload"></i>
                Subir Imágenes
              </button>
              <input
                type="file"
                ref="imageInput"
                @change="handleImageUpload"
                accept="image/*"
                multiple
                style="display: none"
              />

              <div class="image-preview-container" v-if="imagePreviews.length">
                <div class="image-preview-scroll">
                  <div class="image-preview-grid">
                    <div
                      v-for="(image, index) in imagePreviews"
                      :key="index"
                      class="image-preview-item"
                    >
                      <img :src="image" alt="Preview" />
                      <button @click="removeImage(index)" class="remove-image">
                        <i class="bi bi-x"></i>
                      </button>
                    </div>
                  </div>
                </div>
                <small class="text-muted">{{ imagePreviews.length }}/30 imágenes</small>
              </div>
            </div>
          </div>

          <!-- Ubicación -->
          <div class="form-section">
            <h3><i class="bi bi-geo-alt"></i> Ubicación</h3>
            <div class="form-group">
              <label for="direccion">Dirección*</label>
              <input
                id="direccion"
                v-model="commonData.address.direccion"
                type="text"
                class="form-control"
                required
              />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="ciudad">Ciudad*</label>
                <input
                  id="ciudad"
                  v-model="commonData.address.ciudad"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
              <div class="form-group">
                <label for="provincia">Provincia*</label>
                <input
                  id="provincia"
                  v-model="commonData.address.provincia"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
              <div class="form-group">
                <label for="codigo_postal">Código Postal*</label>
                <input
                  id="codigo_postal"
                  v-model="commonData.address.codigo_postal"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
            </div>
          </div>

          <!-- Detalles Específicos -->
          <div class="form-section">
            <h3><i class="bi bi-list-check"></i> Detalles Específicos</h3>
            <component
              v-if="selectedType && (selectedType !== 'musica' || accountId)"
              :is="currentFormComponent"
              @service-data="handleServiceData"
              :service-data="serviceData"
              v-bind="selectedType === 'musica' ? { accountId } : {}"
            />
          </div>

          <!-- Disponibilidad -->
          <div class="form-section">
            <h3><i class="bi bi-calendar-check"></i> Disponibilidad</h3>
            <div class="availability-rules">
              <div v-for="(rule, index) in commonData.availability_rules" :key="index" class="availability-rule">
                <div class="rule-header">
                  <h4>Regla de Disponibilidad {{ index + 1 }}</h4>
                  <button v-if="index > 0" @click="removeAvailabilityRule(index)" class="remove-rule">
                    Quitar <i class="bi bi-trash"></i>
                  </button>
                </div>

                <!-- Días de la semana en una fila -->
                <div class="weekday-selector">
                  <button
                    v-for="day in weekDays"
                    :key="day.value"
                    type="button"
                    :class="['weekday-button', { active: rule.dias_semana.includes(day.value) }]"
                    @click="toggleWeekday(rule, day.value)"
                  >
                    {{ day.label }}
                  </button>
                </div>

                <!-- Resto de campos en otra fila -->
                <div class="availability-details">
                  <div class="form-row">
                    <div class="form-group">
                      <label><i class="bi bi-clock"></i>
                      Hora de Inicio*
                      </label>
                      <input
                        v-model="rule.hora_inicio"
                        type="time"
                        class="form-control"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-clock"></i>
                      Hora de Fin*
                      </label>
                      <input
                        v-model="rule.hora_fin"
                        type="time"
                        class="form-control"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-currency-euro"></i>
                        {{ getPriceLabel() }}
                      </label>
                      <input
                        v-model.number="rule.price"
                        type="number"
                        class="form-control"
                        min="0"
                        step="0.01"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-calendar-check"></i>
                      Días Mín. de Antelación*
                      </label>
                      <input
                        v-model.number="rule.min_days_before"
                        type="number"
                        class="form-control"
                        min="1"
                        required
                      />
                    </div>
                  </div>
                </div>
              </div>

              <button @click="addAvailabilityRule" class="btn-add-rule">
                <i class="bi bi-plus-circle"></i>
                Añadir Regla de Disponibilidad
              </button>
            </div>
          </div>

          <!-- Botones de acción -->
          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="handleCancel">
              <i class="bi bi-x"></i> Cancelar
            </button>
            <button type="button" class="submit-btn" @click="handleSubmit" :disabled="isSubmitting">
              <i class="bi bi-check2"></i> Guardar Cambios
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import logo from '@/assets/LogoEventAiTransGran.png'
import EditEspai from './EditEspai.vue'
import EditCatering from './EditCatering.vue'
import EditMobiliari from './EditMobiliari.vue'
import EditDecoracio from './EditDecoracio.vue'
import EditMusica from './EditMusica.vue'
import EditFotografia from './EditFotografia.vue'
import EspaiService from '@/services/EspaiServices'
import CateringService from '@/services/CateringServices'
import MobiliariDecoracioService from '@/services/MobiliariDecoracioServices'
import MusicaService from '@/services/MusicaServices'
import FotografiaService from '@/services/FotografiaServices'
import Swal from 'sweetalert2'
import UploadServices from '@/services/UploadServices'

export default {
  name: 'EditServices',
  components: {
    EditEspai,
    EditCatering,
    EditMobiliari,
    EditDecoracio,
    EditMusica,
    EditFotografia
  },
  props: {
    type_service: {
      type: String,
      required: true,
      validator: function (value) {
        return ['espai', 'catering', 'mobiliario', 'decoracion', 'musica', 'fotografia'].includes(value)
      }
    },
    service_id: {
      type: [String, Number],
      required: true,
      validator: function (value) {
        return value !== undefined && value !== null && value !== ''
      }
    }
  },
  data () {
    return {
      logo,
      selectedType: this.type_service,
      response: null,
      isSubmitting: false,
      commonData: {
        name: '',
        description: '',
        images: [],
        address: {
          direccion: '',
          ciudad: '',
          codigo_postal: '',
          provincia: ''
        },
        availability_rules: [{
          dias_semana: [],
          hora_inicio: '',
          hora_fin: '',
          price: 0,
          min_days_before: 1
        }]
      },
      weekDays: [
        { value: 1, label: 'L' },
        { value: 2, label: 'M' },
        { value: 3, label: 'X' },
        { value: 4, label: 'J' },
        { value: 5, label: 'V' },
        { value: 6, label: 'S' },
        { value: 7, label: 'D' }
      ],
      serviceData: null,
      imageFiles: [],
      imagePreviews: [],
      accountId: null,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0,
      observer: null
    }
  },
  computed: {
    currentFormComponent () {
      const componentMap = {
        espai: 'EditEspai',
        catering: 'EditCatering',
        mobiliario: 'EditMobiliari',
        decoracion: 'EditDecoracio',
        musica: 'EditMusica',
        fotografia: 'EditFotografia'
      }
      return this.selectedType ? componentMap[this.selectedType] : null
    }
  },
  watch: {
    type_service: {
      immediate: true,
      handler (newVal) {
        console.log('type_service changed:', newVal)
        if (newVal) {
          this.selectedType = newVal
        }
      }
    },
    service_id: {
      immediate: true,
      handler (newVal) {
        console.log('service_id changed:', newVal)
      }
    }
  },
  async created () {
    console.log('EditServices created with props:', {
      type_service: this.type_service,
      service_id: this.service_id
    })
  },
  async mounted () {
    console.log('EditServices mounted with props:', {
      type_service: this.type_service,
      service_id: this.service_id
    })

    if (!this.type_service || !this.service_id) {
      console.error('Props requeridos no proporcionados:', {
        type_service: this.type_service,
        service_id: this.service_id
      })
      this.$router.push('/mainPageVendor')
      return
    }

    const user = JSON.parse(localStorage.getItem('user'))
    if (user && user.id) {
      this.accountId = user.id
    }

    // Cargar los datos del servicio
    await this.loadServiceData()

    // Configurar el Intersection Observer
    this.observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          this.isNavbarHidden = false
        } else {
          const currentScroll = window.pageYOffset || document.documentElement.scrollTop
          if (currentScroll > 200) {
            this.isNavbarHidden = true
          }
        }
      })
    }, {
      threshold: 0.1
    })

    const firstElement = document.querySelector('.create-service-page')
    if (firstElement) {
      this.observer.observe(firstElement)
    }
  },
  beforeDestroy () {
    if (this.observer) {
      this.observer.disconnect()
    }
  },
  methods: {
    async loadServiceData () {
      try {
        console.log('EditServices - Cargando datos del servicio:', {
          type: this.type_service,
          id: this.service_id
        })

        let serviceData
        switch (this.type_service) {
          case 'espai':
            serviceData = await EspaiService.getEspaiById(this.service_id)
            break
          case 'catering':
            serviceData = await CateringService.getCateringById(this.service_id)
            break
          case 'mobiliario':
          case 'decoracion':
            serviceData = await MobiliariDecoracioService.getMobiliariById(this.service_id)
            break
          case 'musica':
            serviceData = await MusicaService.getMusicaById(this.service_id)
            break
          case 'fotografia':
            serviceData = await FotografiaService.getFotografiaById(this.service_id)
            break
          default:
            console.error('Tipo de servicio no válido:', this.type_service)
            throw new Error(`Tipo de servicio no válido: ${this.type_service}`)
        }

        console.log('EditServices - Datos del servicio cargados:', serviceData)

        // Cargar datos comunes
        this.commonData = {
          name: serviceData.name || '',
          description: serviceData.description || '',
          images: serviceData.images || [],
          address: serviceData.address || {
            direccion: '',
            ciudad: '',
            codigo_postal: '',
            provincia: ''
          },
          availability_rules: serviceData.availability_rules || [{
            dias_semana: [],
            hora_inicio: '',
            hora_fin: '',
            price: 0,
            min_days_before: 1
          }]
        }

        // Cargar imágenes existentes
        this.imagePreviews = [...(serviceData.images || [])]
        console.log('Tipo de servicio:', this.type_service)
        // Cargar datos específicos del servicio
        if (this.type_service === 'espai') {
          this.serviceData = {
            // eslint-disable-next-line camelcase
            espai_type: serviceData.espai?.espai_type || '',
            // eslint-disable-next-line camelcase
            capacitat_min: serviceData.espai?.capacitat_min || 1,
            // eslint-disable-next-line camelcase
            capacitat_max: serviceData.espai?.capacitat_max || 1,
            caracteristicas: serviceData.espai?.caracteristicas || [],
            service_include: serviceData.service_include || {}
          }
        } else if (this.type_service === 'catering') {
          this.serviceData = {
            ...serviceData.catering,
            service_include: serviceData.service_include || {}
          }
        } else if (this.type_service === 'mobiliario' || this.type_service === 'decoracion') {
          // Asegurarse de que los datos del mobiliario se procesen correctamente
          const mobiliariData = serviceData.mobiliari_decoracio || {}
          this.serviceData = {
            tipologia: mobiliariData.tipologia || '',
            is_rental: mobiliariData.is_rental !== undefined ? mobiliariData.is_rental : true,
            cantidad_min: mobiliariData.cantidad_min || 1,
            cantidad_max: mobiliariData.cantidad_max || 1,
            subtipologia: mobiliariData.subtipologia || '',
            forma: mobiliariData.forma || '',
            modality: mobiliariData.modality || '',
            style: mobiliariData.style || '',
            color: Array.isArray(mobiliariData.color) ? [...mobiliariData.color] : [],
            material: Array.isArray(mobiliariData.material) ? [...mobiliariData.material] : [],
            size: mobiliariData.size || '',
            dimensions: {
              width: mobiliariData.dimensions?.width || 0,
              height: mobiliariData.dimensions?.height || 0,
              depth: mobiliariData.dimensions?.depth || 0
            },
            caracteristicas: Array.isArray(mobiliariData.caracteristicas) ? [...mobiliariData.caracteristicas] : [],
            complement: Array.isArray(mobiliariData.complement) ? [...mobiliariData.complement]
              : (typeof mobiliariData.complement === 'string' ? mobiliariData.complement.split(',').map(item => item.trim()) : []),
            service_include: serviceData.service_include || {}
          }
        } else {
          this.serviceData = serviceData[this.type_service] || {}
        }

        console.log('serviceData procesado:', JSON.parse(JSON.stringify(this.serviceData)))
        console.log('type_service:', this.type_service)
        console.log('EditServices - serviceData preparado para el componente hijo:', JSON.parse(JSON.stringify(this.serviceData)))

        // Emitir evento para cargar datos específicos del servicio
        this.$nextTick(() => {
          if (this.$refs[this.currentFormComponent]) {
            const component = this.$refs[this.currentFormComponent]
            if (component && typeof component.loadServiceData === 'function') {
              console.log('EditServices - Llamando a loadServiceData del componente hijo con datos:', JSON.parse(JSON.stringify(this.serviceData)))
              component.loadServiceData(this.serviceData)
            }
          }
        })
      } catch (error) {
        console.error('Error loading service data:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los datos del servicio',
          icon: 'error',
          confirmButtonText: 'OK'
        }).then(() => {
          this.$router.push('/mainPageVendor')
        })
      }
    },
    handleServiceData (data) {
      console.log('EditServices - handleServiceData recibido:', data)
      this.serviceData = data
    },
    async handleSubmit () {
      try {
        this.isSubmitting = true
        const loadingPopup = Swal.fire({
          title: 'Guardando cambios...',
          text: 'Por favor, espere mientras se procesan los cambios',
          allowOutsideClick: false,
          allowEscapeKey: false,
          showConfirmButton: false,
          didOpen: () => {
            Swal.showLoading()
          }
        })

        // Subir nuevas imágenes si hay
        if (this.imageFiles.length > 0) {
          const uploadPromises = this.imageFiles.map(file => {
            const uniqueName = `${Date.now()}_${file.name}`
            const renamedFile = new File([file], uniqueName, { type: file.type })
            return UploadServices.uploadImage(renamedFile)
          })
          const newImageUrls = await Promise.all(uploadPromises)
          this.commonData.images = [...this.commonData.images, ...newImageUrls]
        }

        let response
        if (this.selectedType === 'espai') {
          const finalData = {
            type: 'espai',
            name: this.commonData.name,
            description: this.commonData.description,
            images: this.commonData.images,
            service_include: this.serviceData.service_include,
            address: this.commonData.address,
            availability_rules: this.commonData.availability_rules,
            espai: {
              capacitat_max: this.serviceData.capacitat_max,
              espai_type: this.serviceData.espai_type,
              capacitat_min: this.serviceData.capacitat_min,
              caracteristicas: this.serviceData.caracteristicas
            }
          }
          response = await EspaiService.updateEspai(this.service_id, finalData)
        } else if (this.selectedType === 'mobiliario' || this.selectedType === 'decoracion') {
          console.log('serviceData Mobiliari o Decoracio:', JSON.parse(JSON.stringify(this.serviceData)))
          const mobiliariData = {
            ...this.serviceData,
            color: Array.isArray(this.serviceData.color) ? this.serviceData.color : [],
            material: Array.isArray(this.serviceData.material) ? this.serviceData.material : [],
            caracteristicas: Array.isArray(this.serviceData.caracteristicas) ? this.serviceData.caracteristicas : [],
            complement: (
              Array.isArray(this.serviceData.complement)
                ? (this.serviceData.complement.length > 0 ? this.serviceData.complement.join(', ') : null)
                : (this.serviceData.complement || null)
            ),
            dimensions: this.serviceData.dimensions || { width: 0, height: 0, depth: 0 }
          }
          if (mobiliariData.service_include) {
            delete mobiliariData.service_include
          }

          const finalData = {
            type: 'mobiliari-decoracio',
            name: this.commonData.name,
            description: this.commonData.description,
            images: this.commonData.images,
            address: this.commonData.address,
            availability_rules: this.commonData.availability_rules,
            service_include: this.serviceData.service_include,
            mobiliari_decoracio: mobiliariData
          }
          console.log('finalData Mobiliari o Decoracio:', JSON.parse(JSON.stringify(finalData)))
          response = await MobiliariDecoracioService.updateMobiliari(this.service_id, finalData)
        } else if (this.selectedType === 'musica') {
          const musicaData = { ...this.serviceData }
          delete musicaData.servicios_incluidos
          delete musicaData.raider_id
          if (musicaData.raider && musicaData.raider.id) {
            musicaData.raider_id = musicaData.raider.id
          }
          delete musicaData.raider
          musicaData.duracion = parseFloat(musicaData.duracion)

          // Asegurarnos de que el address se serializa correctamente
          if (this.commonData.address) {
            this.commonData.address = {
              calle: this.commonData.address.calle,
              ciudad: this.commonData.address.ciudad,
              codigo_postal: this.commonData.address.codigo_postal,
              provincia: this.commonData.address.provincia
            }
          }

          const finalData = {
            ...this.commonData,
            type: 'musica',
            service_include: this.serviceData.service_include,
            musica: musicaData
          }
          response = await MusicaService.updateMusica(this.service_id, finalData)
        } else if (this.selectedType === 'fotografia') {
          const fotografiaData = { ...this.serviceData }
          if (fotografiaData.raider && fotografiaData.raider.id) {
            fotografiaData.raider_id = fotografiaData.raider.id
          }
          delete fotografiaData.raider
          if (fotografiaData.servicio_especial_type === '') {
            delete fotografiaData.servicio_especial_type
          }

          const finalData = {
            ...this.commonData,
            type: 'fotografia',
            service_include: this.serviceData.service_include,
            fotografia: fotografiaData
          }
          console.log('finalData Fotografia:', JSON.parse(JSON.stringify(finalData)))
          response = await FotografiaService.updateFotografia(this.service_id, finalData)
        } else if (this.selectedType === 'catering') {
          const finalData = {
            type: 'catering',
            name: this.commonData.name,
            description: this.commonData.description,
            images: this.commonData.images,
            service_include: this.serviceData.service_include,
            address: this.commonData.address,
            availability_rules: this.commonData.availability_rules,
            catering: {
              tipo_entrega: this.serviceData.tipo_entrega,
              ...(this.serviceData.tipo_entrega === 'servicio_domicilio' && { tipo_catering: this.serviceData.tipo_catering }),
              min_comensales: parseInt(this.serviceData.min_comensales) || 1,
              max_comensales: parseInt(this.serviceData.max_comensales) || 1,
              duracion: parseFloat(this.serviceData.duracion) || 1,
              alergenos: this.serviceData.alergenos || [],
              caracteristicas: this.serviceData.caracteristicas || [],
              menu: this.serviceData.menu,
              articulo: this.serviceData.articulo
            }
          }
          console.log('serviceData Catering:', this.service_id)
          console.log('finalData Catering:', JSON.parse(JSON.stringify(finalData)))
          response = await CateringService.updateCatering(this.service_id, finalData)
        } else {
          throw new Error('Tipo de servicio no válido')
        }

        await loadingPopup.close()
        await Swal.fire({
          title: '¡Cambios guardados!',
          text: 'El servicio se ha actualizado correctamente.',
          icon: 'success',
          confirmButtonText: 'OK'
        })
        this.$router.push(`/mydetallesService/${response.id}`)
      } catch (error) {
        if (Swal.isVisible()) {
          await Swal.close()
          await new Promise(resolve => setTimeout(resolve, 100))
        }
        await Swal.fire({
          title: 'Error',
          html: 'Error al actualizar el servicio.<br>Por favor, revise los datos e inténtelo de nuevo.',
          icon: 'error',
          confirmButtonText: 'OK'
        })
        console.error('Error updating service:', error)
      } finally {
        if (Swal.isVisible()) {
          await Swal.close()
        }
        this.isSubmitting = false
      }
    },
    handleCancel () {
      this.$router.back()
    },
    triggerImageUpload () {
      this.$refs.imageInput.click()
    },
    handleImageUpload (event) {
      const files = Array.from(event.target.files)
      files.forEach(file => {
        if (this.imageFiles.length >= 30) return
        this.imageFiles.push(file)
        this.imagePreviews.push(URL.createObjectURL(file))
      })
      // Limpiar el input para permitir seleccionar la misma imagen de nuevo
      event.target.value = ''
    },
    removeImage (index) {
      // Eliminar la imagen de los arrays locales
      this.imageFiles.splice(index, 1)
      this.imagePreviews.splice(index, 1)
      // Actualizar también el array de imágenes en commonData
      this.commonData.images.splice(index, 1)
      console.log('Imagen eliminada. Imágenes restantes:', this.commonData.images)
    },
    addAvailabilityRule () {
      this.commonData.availability_rules.push({
        dias_semana: [],
        hora_inicio: '',
        hora_fin: '',
        price: 0,
        min_days_before: 1
      })
    },
    removeAvailabilityRule (index) {
      if (this.commonData.availability_rules.length > 1) {
        this.commonData.availability_rules.splice(index, 1)
      }
    },
    toggleWeekday (rule, day) {
      const index = rule.dias_semana.indexOf(day)
      if (index === -1) {
        rule.dias_semana.push(day)
      } else {
        rule.dias_semana.splice(index, 1)
      }
    },
    getPriceLabel () {
      switch (this.selectedType) {
        case 'espai':
          return 'Precio (€/h)*'
        case 'catering':
          return 'Precio (€/pax)*'
        case 'mobiliario':
          return 'Precio (€/u)*'
        case 'decoracion':
          return 'Precio (€/u)*'
        case 'musica':
          return 'Precio (€/h)*'
        case 'fotografia':
          return 'Precio (€/h)*'
        default:
          return 'Precio (€)*'
      }
    },
    handleScroll () {
      if (this.scrollTimeout) {
        clearTimeout(this.scrollTimeout)
      }

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

        if (currentScroll <= 200) {
          this.isNavbarHidden = false
          return
        }

        if (currentScroll > this.lastScrollTop && currentScroll > 200) {
          this.isNavbarHidden = true
        } else {
          this.isNavbarHidden = false
        }
        this.lastScrollTop = currentScroll <= 0 ? 0 : currentScroll
      }, 50)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      this.isNavbarHidden = this.mouseY > 110
    }
  }
}
</script>

<style scoped>
h5.avis-campos {
  color: #333;
  text-align: right;
  font-size: 0.9rem;
  font-weight: 600;
  margin: -0.5rem 1rem -1.5rem 0;
}
.submit-btn,
.cancel-btn {
  padding: 0.8rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn {
  background-color: #800020;
  color: white;
  border: none;
}

.submit-btn:hover {
  background-color: #600018;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.cancel-btn {
  background-color: #e9ecef;
  color: #2C3E50;
  border: 1px solid #dee2e6;
}

.cancel-btn:hover {
  background-color: #dee2e6;
}

.service-type-img {
  width: 2.75rem;
  height: 2.75rem;
  margin-bottom: 0.5rem;
  object-fit: contain;
}

.page-container {
  padding-top: 140px; /* Ajusta este valor según la altura de tu navbar */
  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-right {
  margin-right: 1rem;
}

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

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

.service-type-selector {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  backdrop-filter: blur(5px);
}

.service-type-selector h2 {
  color: #800020;
  margin-bottom: 1.5rem;
  text-align: center;
}

.service-types {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  justify-content: center;
  margin-bottom: 0.1rem;
}

.type-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1.5rem;
  border: 2px solid #ddd;
  border-radius: 10px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.type-button:hover {
  border-color: #800020;
  transform: translateY(-2px);
}

.type-button.active {
  background: #800020;
  border-color: #800020;
  color: white;
}

.type-button i {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.service-form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0rem;
}

.form-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 2.5rem;
  padding-bottom: 1rem;
  border-bottom: 3px solid #eee;
  width: 100%;
}

.form-section:last-child {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: none;
}

h3 {
  color: #800020;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.25rem;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  width: 100%;
  margin-bottom: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin-bottom: 1.5rem;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #800020;
  box-shadow: 0 0 0 0.2rem rgba(128, 0, 32, 0.1);
}

label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  color: #2C3E50;
  font-weight: 500;
}

.btn-upload {
  width: 100%;
  padding: 0.75rem;
  background: #f8f9fa;
  border: 2px dashed #ddd;
  border-radius: 8px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.3s;
  margin-bottom: 1rem;
}

.btn-upload:hover {
  border-color: #800020;
  color: #800020;
}

.image-preview-container {
  margin-top: 1rem;
  max-width: 100%;
}

.image-preview-scroll {
  overflow-x: auto;
  padding: 0.5rem;
  margin-bottom: 0.5rem;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
}

.image-preview-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ddd;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #dc3545;
}

.availability-rule {
  background:rgb(245, 245, 245);
  border-radius: 8px;
  padding: 1.5rem;
  padding-bottom: -0.5rem;
  margin-bottom: 1rem;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0rem;
}

.rule-header h4 {
  margin: 0;
  color: #2C3E50;
  font-weight: 550;
}

.remove-rule {
  background: none;
  border: none;
  color: #dc3545;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 8px;
  transition: all 0.3s;
}

.remove-rule:hover {
  background: rgba(220, 53, 69, 0.1);
}

.weekday-selector {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
}

.weekday-button {
  width: 40px;
  height: 40px;
  border: 2px solid #ddd;
  border-radius: 50%;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.weekday-button.active {
  background: #800020;
  border-color: #800020;
  color: white;
}

.availability-details {
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: -3.5rem;
}

.availability-details .form-row {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
}

.btn-add-rule {
  width: 100%;
  padding: 0.75rem;
  background: none;
  border: 2px dashed #ddd;
  border-radius: 8px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.3s;
  margin-top: 1rem;
}

.btn-add-rule:hover {
  border-color: #800020;
  color: #800020;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  padding: 0.2rem;
}

.text-muted {
  color: #6c757d;
  font-size: 0.875rem;
}

textarea.form-control {
  min-height: 120px;
}

.service-type-message {
  text-align: center;
  color: #666;
  margin-top: 3rem;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.service-type-message i {
  color: #800020;
  font-size: 1.2rem;
}
</style>
