<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>Asistente Inteligente</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>

    <!-- Main Content -->
    <div class="main-content">
      <div class="intelligent-assistant">
        <div class="assistant-container">
          <!-- Formulario de Evento -->
          <div class="event-form">
            <div class="form-grid">
              <div class="form-group">
                <label for="name">Nombre del Evento</label>
                <input
                  type="text"
                  id="name"
                  v-model="eventData.name"
                  required
                  placeholder="Ej: Boda María y Juan"
                >
              </div>

              <div class="form-group">
                <label for="type">Tipo de Evento</label>
                <select id="type" v-model="eventData.type" required>
                  <option value="">Selecciona un tipo</option>
                  <option v-for="type in eventTypes" :key="type.value" :value="type.value">
                    {{ type.label }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label for="startDateTime">Fecha y Hora de Inicio</label>
                <input
                  type="datetime-local"
                  id="startDateTime"
                  v-model="eventData.fechahora_inicio"
                  required
                  :min="minDateTime"
                >
              </div>

              <div class="form-group">
                <label for="endDateTime">Fecha y Hora de Fin</label>
                <input
                  type="datetime-local"
                  id="endDateTime"
                  v-model="eventData.fechahora_final"
                  required
                  :min="eventData.fechahora_inicio"
                >
              </div>

              <div class="form-group">
                <label for="guests">Número de Invitados</label>
                <input
                  type="number"
                  id="guests"
                  v-model="eventData.num_invitats"
                  required
                  min="1"
                >
              </div>

              <div class="form-group">
                <label for="budget">Presupuesto Máximo (€)</label>
                <input
                  type="number"
                  id="budget"
                  v-model="eventData.pressupost"
                  required
                  min="0"
                  step="100"
                >
              </div>

              <div class="form-group">
                <label class="checkbox-label space-own-label">
                  <input
                    type="checkbox"
                    v-model="eventData.has_espai_propi"
                    @change="handleEspaiPropiChange"
                  >
                  <span class="checkbox-text">Espacio Propio</span>
                </label>
              </div>
            </div>

            <!-- Selección de Servicios -->
            <div class="services-selection">
              <h3>Servicios Deseados</h3>
              <div class="services-grid">
                <div v-for="service in serviceTypes" :key="service.value" class="service-checkbox">
                  <input
                    type="checkbox"
                    :id="service.value"
                    v-model="eventData.selectedServices"
                    :value="service.value"
                  >
                  <label :for="service.value">
                    <i :class="service.icon"></i>
                    {{ service.label }}
                  </label>
                </div>
              </div>
              <button class="nav-button reset" @click="borrarAsistente">
                <i class="bi bi-trash"></i>
                Borrar conversación
              </button>
            </div>
          </div>

          <!-- Chat del Asistente -->
          <div class="chat-container">
            <div class="chat-messages" ref="chatMessages">
              <div v-for="(message, index) in chatMessages" :key="index"
                   :class="['message', message.type]">
                <div class="message-content">
                  {{ message.text }}
                </div>
                <!-- Botón para ver evento generado si hay preview -->
                <button v-if="message.eventPreview" class="event-preview-btn" @click="openEventPreview(message.eventPreview)">
                  Ver evento generado
                </button>
              </div>
            </div>
            <div class="chat-input">
              <textarea
                v-model="userInput"
                placeholder="Describe tu evento ideal..."
                @keyup.enter="sendMessage"
                :disabled="isProcessing"
              ></textarea>
              <button @click="sendMessage" class="send-button" :disabled="isProcessing">
                <i class="bi icon-send bi-arrow-return-left"></i>
              </button>
            </div>
          </div>
        </div>

        <!-- Modal para Espacio Propio -->
        <div v-if="showEspaiPropiModal" class="modal-overlay">
          <div class="modal-content">
            <div class="modal-header">
              <h3>Gestión de Espacio Propio</h3>
              <button class="close-button" @click="closeEspaiPropiModal">
                <i class="bi bi-x"></i>
              </button>
            </div>

            <div class="modal-body">
              <!-- Selección de tipo de espacio -->
              <div class="space-type-selection">
                <h4>¿Qué tipo de espacio deseas utilizar?</h4>
                <div class="space-type-options">
                  <button
                    type="button"
                    class="space-type-button"
                    :class="{ active: useExistingSpace }"
                    @click="useExistingSpace = true"
                  >
                    <i class="bi bi-building"></i>
                    <span>Usar Espacio Propio Existente</span>
                  </button>
                  <button
                    type="button"
                    class="space-type-button"
                    :class="{ active: !useExistingSpace }"
                    @click="useExistingSpace = false"
                  >
                    <i class="bi bi-plus-circle"></i>
                    <span>Crear Nuevo Espacio Propio</span>
                  </button>
                </div>
              </div>

              <!-- Espacio Existente -->
              <div v-if="useExistingSpace" class="existing-space-section">
                <div v-if="loading" class="loading-spinner">
                  <i class="bi bi-arrow-repeat"></i>
                  <span>Cargando espacios propios...</span>
                </div>
                <div v-else-if="userSpaces.length === 0" class="no-spaces-message">
                  <i class="bi bi-building-x"></i>
                  <h4>No tienes espacios propios creados</h4>
                  <p>Para usar un espacio existente, primero debes crear uno.</p>
                  <button
                    type="button"
                    class="button secondary small"
                    @click="useExistingSpace = false"
                  >
                    Crear Nuevo Espacio Propio
                  </button>
                </div>
                <div v-else class="spaces-table-container">
                  <table class="spaces-table">
                    <thead>
                      <tr>
                        <th>Nombre</th>
                        <th>Tipo</th>
                        <th>Capacidad</th>
                        <th>Ubicación</th>
                        <th>Acciones</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr
                        v-for="space in userSpaces"
                        :key="space.id"
                        :class="{ selected: selectedSpace === space.id }"
                      >
                        <td>{{ space.nombre }}</td>
                        <td>{{ space.tipus }}</td>
                        <td>{{ space.capacitat }} persones</td>
                        <td class="location-cell">
                          <span class="location-text">{{ space.address.direccion }}, {{ space.address.codigo_postal }} {{ space.address.ciudad }}, {{ space.address.provincia }}</span>
                        </td>
                        <td class="actions-cell">
                          <button
                            type="button"
                            class="action-button use"
                            @click="selectSpace(space.id)"
                            :class="{ active: selectedSpace === space.id }"
                          >
                            <i :class="selectedSpace === space.id ? 'bi bi-check-circle-fill' : 'bi bi-check-circle'"></i>
                            {{ selectedSpace === space.id ? 'Seleccionado' : 'Usar' }}
                          </button>
                          <button
                            type="button"
                            class="action-button view"
                            @click="viewSpaceDetails(space)"
                          >
                            <i class="bi bi-eye"></i>
                          </button>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              <!-- Nuevo Espacio -->
              <div v-else>
                <div class="form-grid space-main-info">
                  <div class="form-group">
                    <label for="spaceType">Tipo de Espacio</label>
                    <select id="spaceType" v-model="newSpace.spaceType" required>
                      <option value="">Selecciona un tipo</option>
                      <option v-for="type in spaceTypes" :key="type.value" :value="type.value">
                        {{ type.label }}
                      </option>
                    </select>
                  </div>

                  <div class="form-group">
                    <label for="spaceName">Nombre del Espacio</label>
                    <input
                      type="text"
                      id="spaceName"
                      v-model="newSpace.spaceName"
                      required
                    >
                  </div>

                  <div class="form-group">
                    <label for="spaceCapacity">Capacidad Aproximada</label>
                    <input
                      type="number"
                      id="spaceCapacity"
                      v-model="newSpace.spaceCapacity"
                      required
                      min="1"
                    >
                  </div>
                </div>

                <!-- Dirección -->
                <div class="form-section address-section">
                  <h4>Dirección</h4>
                  <div class="form-grid address-grid">
                    <div class="form-group full-width">
                      <label for="spaceAddress">Dirección</label>
                      <input
                        type="text"
                        id="spaceAddress"
                        v-model="newSpace.spaceAddress"
                        required
                        placeholder="Calle y número"
                      >
                    </div>

                    <div class="form-group">
                      <label for="spaceCity">Ciudad</label>
                      <input
                        type="text"
                        id="spaceCity"
                        v-model="newSpace.spaceCity"
                        required
                      >
                    </div>

                    <div class="form-group">
                      <label for="spacePostalCode">Código Postal</label>
                      <input
                        type="text"
                        id="spacePostalCode"
                        v-model="newSpace.spacePostalCode"
                        required
                        pattern="[0-9]{5}"
                      >
                    </div>

                    <div class="form-group">
                      <label for="spaceProvince">Provincia</label>
                      <input
                        type="text"
                        id="spaceProvince"
                        v-model="newSpace.spaceProvince"
                        required
                      >
                    </div>
                  </div>
                </div>

                <!-- Descripción -->
                <div class="form-section description-section">
                  <h4>Descripción</h4>
                  <div class="form-group">
                    <textarea
                      id="spaceDescription"
                      v-model="newSpace.spaceDescription"
                      required
                      rows="4"
                      placeholder="Describe las características principales del espacio"
                    ></textarea>
                  </div>
                </div>

                <!-- Características -->
                <div class="form-section features-section">
                  <h4>Características</h4>
                  <div class="features-grid">
                    <div v-for="feature in spaceFeatures" :key="feature.value" class="feature-checkbox">
                      <input
                        type="checkbox"
                        :id="feature.value"
                        v-model="newSpace.spaceFeatures"
                        :value="feature.value"
                      >
                      <label :for="feature.value">
                        <i :class="feature.icon"></i>
                        {{ feature.label }}
                      </label>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="modal-footer">
              <button
                type="button"
                class="button secondary"
                @click="closeEspaiPropiModal"
              >
                Cancelar
              </button>
              <button
                type="button"
                class="button primary"
                @click="saveEspaiPropi"
                :disabled="!isEspaiPropiValid"
              >
                Guardar
              </button>
            </div>
          </div>
        </div>
        <!-- Modal de preview de evento generado -->
        <div v-if="showEventPreview" class="modal-overlay">
          <div class="modal-content event-preview-modal">
            <div class="modal-header">
              <h3>Evento generado por el asistente</h3>
              <button class="close-button" @click="closeEventPreview">
                <i class="bi bi-x"></i>
              </button>
            </div>
            <div class="modal-body">
              <div v-if="loadingServices" class="loading-spinner">
                <i class="bi bi-arrow-repeat"></i> Cargando servicios...
              </div>
              <EventPreviewCard
                v-else
                :event="eventPreviewData.event"
                :selectedServices="eventPreviewData.selected_services"
                :servicesInfo="serviciosConDatos"
                :precioTotalEvento="precioTotalEvento"
                :getServiceTypeLabel="getServiceTypeLabel"
                :getServiceExtraInfo="getServiceExtraInfo"
              />
            </div>
            <div class="modal-footer">
              <button class="button secondary" @click="closeEventPreview">Cancelar</button>
              <button class="button primary" @click="saveGeneratedEvent" :disabled="savingEvent">
                {{ savingEvent ? 'Guardando...' : 'Guardar evento' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AssistantService from '../services/AssistantService'
import EspaiPropiServices from '../services/EspaiPropiServices'
import Swal from 'sweetalert2'
import EventPreviewCard from './EventPreviewCard.vue'
import ServiceServices from '@/services/ServiceServices'
import EventServiceServices from '@/services/EventServiceServices'
import EventService from '@/services/EventServices'

export default {
  name: 'IntelligentAssistant',
  components: { EventPreviewCard },
  data () {
    return {
      logo: require('../assets/LogoEventAiTransGran.png'),
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0,
      eventData: {
        name: '',
        type: '',
        fechahora_inicio: '',
        fechahora_final: '',
        num_invitats: '',
        pressupost: '',
        has_espai_propi: false,
        selectedServices: []
      },
      eventTypes: [
        { value: 'boda', label: 'Boda' },
        { value: 'graduacio', label: 'Graduación' },
        { value: 'festa', label: 'Fiesta' },
        { value: 'celebracio', label: 'Celebración' },
        { value: 'menjar_grup', label: 'Menjar de Grup' },
        { value: 'altres', label: 'Otros' }
      ],
      serviceTypes: [
        { value: 'espai', label: 'Espacio', icon: 'bi bi-building' },
        { value: 'catering', label: 'Catering', icon: 'bi bi-cup-hot' },
        { value: 'mobiliario', label: 'Mobiliario', icon: 'bi bi-table' },
        { value: 'decoracion', label: 'Decoración', icon: 'bi bi-flower1' },
        { value: 'musica', label: 'Música', icon: 'bi bi-music-note-beamed' },
        { value: 'fotografia', label: 'Fotografía', icon: 'bi bi-camera' }
      ],
      chatMessages: [
        {
          type: 'assistant',
          text: '¡Hola! Soy tu asistente inteligente para la planificación de eventos. ¿Cómo puedo ayudarte hoy?'
        }
      ],
      userInput: '',
      isProcessing: false,
      eventConfirmed: false,
      showEspaiPropiModal: false,
      useExistingSpace: true,
      selectedSpace: null,
      userSpaces: [],
      loading: false,
      newSpace: {
        spaceType: '',
        spaceName: '',
        spaceAddress: '',
        spaceCity: '',
        spacePostalCode: '',
        spaceProvince: '',
        spaceCapacity: '',
        spaceDescription: '',
        spaceFeatures: []
      },
      spaceTypes: [
        { value: 'sala_privada', label: 'Sala Privada' },
        { value: 'finca', label: 'Finca' },
        { value: 'terraza', label: 'Terraza' },
        { value: 'salon', label: 'Salón' },
        { value: 'casa_particular', label: 'Casa Particular' },
        { value: 'jardin_privado', label: 'Jardín Privado' },
        { value: 'azotea', label: 'Azotea' },
        { value: 'piso', label: 'Piso' },
        { value: 'casa_rural', label: 'Casa Rural' },
        { value: 'nave_industrial', label: 'Nave Industrial' },
        { value: 'parcela', label: 'Parcela' },
        { value: 'local_propio', label: 'Local Propio' },
        { value: 'masia', label: 'Masía' },
        { value: 'otro', label: 'Otro' }
      ],
      spaceFeatures: [
        { value: 'interior', label: 'Interior', icon: 'bi bi-house-door' },
        { value: 'exterior', label: 'Exterior', icon: 'bi bi-tree' },
        { value: 'both', label: 'Interior y Exterior', icon: 'bi bi-house-door-fill' },
        { value: 'natural_light', label: 'Luz Natural', icon: 'bi bi-sun' },
        { value: 'car', label: 'Acceso en Coche', icon: 'bi bi-truck' },
        { value: 'bus', label: 'Acceso para Autocares', icon: 'bi bi-truck' },
        { value: 'motorcycle', label: 'Acceso en Moto', icon: 'bi bi-bicycle' },
        { value: 'wheelchair', label: 'Accesible en Silla de Ruedas', icon: 'bi bi-person-wheelchair' },
        { value: 'parking', label: 'Parking Disponible', icon: 'bi bi-p-circle' },
        { value: 'free_parking', label: 'Parking Gratuito', icon: 'bi bi-p-circle-fill' },
        { value: 'elevator', label: 'Ascensor Disponible', icon: 'bi bi-arrow-up-circle' },
        { value: 'heating', label: 'Calefacción', icon: 'bi bi-thermometer' },
        { value: 'ac', label: 'Aire Acondicionado', icon: 'bi bi-snow' },
        { value: 'wifi', label: 'WiFi Disponible', icon: 'bi bi-wifi' },
        { value: 'storage', label: 'Espacio de Almacenaje', icon: 'bi bi-box' },
        { value: 'bathroom_adapted', label: 'Baños Adaptados', icon: 'bi bi-toilet' },
        { value: 'security', label: 'Seguridad / Vigilancia', icon: 'bi bi-shield' },
        { value: 'cloakroom', label: 'Guardarropa / Ropero', icon: 'bi bi-bag' },
        { value: 'cleaning_service', label: 'Servicio de Limpieza', icon: 'bi bi-broom' }
      ],
      showEventPreview: false,
      eventPreviewData: null,
      servicesInfo: [],
      loadingServices: false,
      savingEvent: false,
      serviciosConDatos: [],
      precioTotalEvento: 0
    }
  },
  computed: {
    minDateTime () {
      const now = new Date()
      return now.toISOString().slice(0, 16)
    },
    formattedEventData () {
      return {
        ...this.eventData,
        fechahora_inicio: this.eventData.fechahora_inicio ? new Date(this.eventData.fechahora_inicio).toISOString() : null,
        fechahora_final: this.eventData.fechahora_final ? new Date(this.eventData.fechahora_final).toISOString() : null
      }
    },
    isEspaiPropiValid () {
      if (this.useExistingSpace) {
        return this.selectedSpace !== null
      } else {
        return (
          this.newSpace.spaceType &&
          this.newSpace.spaceName &&
          this.newSpace.spaceAddress &&
          this.newSpace.spaceCity &&
          this.newSpace.spacePostalCode &&
          this.newSpace.spaceProvince &&
          this.newSpace.spaceCapacity &&
          this.newSpace.spaceDescription &&
          this.newSpace.spaceFeatures.length > 0
        )
      }
    }
  },
  methods: {
    handleScroll () {
      if (this.scrollTimeout) {
        clearTimeout(this.scrollTimeout)
      }

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

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

        const scrollDifference = this.lastScrollTop - currentScroll

        if (currentScroll > this.lastScrollTop && currentScroll > 200) {
          this.isNavbarHidden = true
        } else if (scrollDifference > 10 && currentScroll > 0) {
          this.isNavbarHidden = false
        }

        this.lastScrollTop = currentScroll <= 0 ? 0 : currentScroll
      }, 50)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      this.isNavbarHidden = this.mouseY > 110
    },
    async sendMessage () {
      if (!this.userInput.trim() || this.isProcessing) return

      const userMessage = this.userInput.trim()
      this.userInput = ''
      this.isProcessing = true
      Swal.fire({
        title: 'Pensando...',
        text: 'El asistente está generando una respuesta.',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => {
          Swal.showLoading()
        }
      })

      // Añadir mensaje del usuario
      this.chatMessages.push({
        type: 'user',
        text: userMessage
      })

      try {
        // Preparar los datos del evento en el formato correcto
        const eventData = {
          name: this.eventData.name,
          tipus: this.eventData.type,
          pressupost: Number(this.eventData.pressupost),
          data_inici: this.eventData.fechahora_inicio
            ? new Date(this.eventData.fechahora_inicio).toISOString()
            : null,
          data_fi: this.eventData.fechahora_final
            ? new Date(this.eventData.fechahora_final).toISOString()
            : null,
          num_invitats: Number(this.eventData.num_invitats),
          espai_propi_id: this.eventData.espai_propi_id || null,
          espai_propi: this.eventData.espai_propi || {}
        }

        // Construir el historial de conversación (context)
        const context = this.chatMessages.slice(0, -1).map(msg => ({
          text: msg.text,
          type: msg.type
        }))

        // Preparar el payload para el backend
        const payload = {
          event: eventData,
          services: this.eventData.selectedServices,
          message: userMessage,
          context: context.length > 0 ? JSON.stringify(context) : null
        }

        // LOG para depuración
        console.log('Payload enviado al backend:', JSON.stringify(payload, null, 2))

        // Procesar el mensaje con el asistente
        const response = await AssistantService.processMessage(payload)
        console.log('Respuesta del asistente:', response)
        // Lógica de respuesta inteligente
        if (response.needs_more_info) {
          // Solo mostrar el mensaje de la IA
          this.chatMessages.push({
            type: 'assistant',
            text: response.message
          })
        } else {
          // Mostrar mensaje y botón de evento generado
          this.chatMessages.push({
            type: 'assistant',
            text: response.message,
            eventPreview: {
              event: eventData,
              selected_services: response.selected_services
            }
          })
        }

        // Si el asistente sugiere confirmar el evento (flujo antiguo)
        if (response.suggest_confirmation && !this.eventConfirmed) {
          await this.showConfirmationDialog()
        }

        // Si hay datos del evento para actualizar
        if (response.event_data) {
          this.updateEventData(response.event_data)
        }
      } catch (error) {
        console.error('Error al procesar el mensaje:', error)
        this.chatMessages.push({
          type: 'assistant',
          text: 'Lo siento, ha ocurrido un error al procesar tu mensaje. Por favor, inténtalo de nuevo.'
        })
      } finally {
        this.isProcessing = false
        Swal.close()
        this.scrollToBottom()
      }
    },

    async showConfirmationDialog () {
      const result = await Swal.fire({
        title: '¿Confirmar evento?',
        text: '¿Deseas confirmar los detalles del evento?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#800020',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Sí, confirmar',
        cancelButtonText: 'No, seguir editando'
      })

      if (result.isConfirmed) {
        try {
          const event = await AssistantService.createEvent(this.formattedEventData)
          this.eventConfirmed = true

          this.chatMessages.push({
            type: 'assistant',
            text: '¡Perfecto! Tu evento ha sido creado. ¿Hay algo más en lo que pueda ayudarte?'
          })

          // Redirigir a la página de detalles del evento
          this.$router.push(`/eventServices/${event.id}`)
        } catch (error) {
          console.error('Error al crear el evento:', error)
          Swal.fire({
            title: 'Error',
            text: 'No se pudo crear el evento. Por favor, inténtalo de nuevo.',
            icon: 'error',
            confirmButtonColor: '#800020'
          })
        }
      }
    },

    updateEventData (newData) {
      // Actualizar solo los campos que vienen del asistente
      Object.keys(newData).forEach(key => {
        if (key in this.eventData) {
          this.eventData[key] = newData[key]
        }
      })
    },

    scrollToBottom () {
      this.$nextTick(() => {
        const chatContainer = this.$refs.chatMessages
        chatContainer.scrollTop = chatContainer.scrollHeight
      })
    },

    async handleEspaiPropiChange () {
      if (this.eventData.has_espai_propi) {
        this.showEspaiPropiModal = true
        await this.loadUserSpaces()
      } else {
        this.selectedSpace = null
        this.resetNewSpace()
      }
    },

    async loadUserSpaces () {
      try {
        this.loading = true
        const response = await EspaiPropiServices.getMyEspaiPropis()
        this.userSpaces = response.data || []
      } catch (error) {
        console.error('Error al cargar los espacios propios:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los espacios propios',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      } finally {
        this.loading = false
      }
    },

    selectSpace (spaceId) {
      this.selectedSpace = spaceId
    },

    async viewSpaceDetails (space) {
      try {
        const spaceDetails = await EspaiPropiServices.getEspaiPropiById(space.id)
        await Swal.fire({
          title: spaceDetails.nombre,
          html: `
            <div class="space-details">
              <p><strong>Tipo:</strong> ${spaceDetails.tipus}</p>
              <p><strong>Capacidad:</strong> ${spaceDetails.capacitat} persones</p>
              <p><strong>Dirección:</strong> ${spaceDetails.address.direccion}</p>
              <p><strong>Código Postal:</strong> ${spaceDetails.address.codigo_postal}</p>
              <p><strong>Ciudad:</strong> ${spaceDetails.address.ciudad}</p>
              <p><strong>Provincia:</strong> ${spaceDetails.address.provincia}</p>
              <p><strong>Descripción:</strong> ${spaceDetails.descripcion}</p>
              <div class="features-list">
                <strong>Características:</strong>
                <ul>
                  ${spaceDetails.caracteristicas.map(feature => `<li>${feature}</li>`).join('')}
                </ul>
              </div>
            </div>
          `,
          width: '600px',
          confirmButtonColor: '#800020'
        })
      } catch (error) {
        console.error('Error al cargar los detalles del espacio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los detalles del espacio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },

    resetNewSpace () {
      this.newSpace = {
        spaceType: '',
        spaceName: '',
        spaceAddress: '',
        spaceCity: '',
        spacePostalCode: '',
        spaceProvince: '',
        spaceCapacity: '',
        spaceDescription: '',
        spaceFeatures: []
      }
    },

    closeEspaiPropiModal () {
      this.showEspaiPropiModal = false
      if (!this.selectedSpace && !this.isEspaiPropiValid) {
        this.eventData.has_espai_propi = false
      }
    },

    async saveEspaiPropi () {
      try {
        if (this.useExistingSpace) {
          if (!this.selectedSpace) {
            throw new Error('Debes seleccionar un espacio existente')
          }
          this.eventData.espai_propi_id = this.selectedSpace
        } else {
          const newSpaceData = {
            nombre: this.newSpace.spaceName,
            tipus: this.newSpace.spaceType,
            address: {
              direccion: this.newSpace.spaceAddress,
              ciudad: this.newSpace.spaceCity,
              codigo_postal: this.newSpace.spacePostalCode,
              provincia: this.newSpace.spaceProvince
            },
            descripcion: this.newSpace.spaceDescription,
            capacitat_aproximada: parseInt(this.newSpace.spaceCapacity),
            caracteristicas: this.newSpace.spaceFeatures
          }

          const response = await EspaiPropiServices.createEspaiPropi(newSpaceData)
          this.eventData.espai_propi_id = response.id
          await this.loadUserSpaces()
        }

        this.showEspaiPropiModal = false
        this.resetNewSpace()
      } catch (error) {
        console.error('Error al guardar el espacio propio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo guardar el espacio propio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    async openEventPreview (previewData) {
      this.eventPreviewData = previewData
      this.showEventPreview = true
      this.loadingServices = true
      this.servicesInfo = []
      // Fetch info de cada servicio seleccionado
      const promises = previewData.selected_services.map(async (s) => {
        try {
          const res = await ServiceServices.get(s.id)
          return { ...res.data, category: s.category }
        } catch (e) {
          return { id: s.id, category: s.category, name: 'Servicio no encontrado', description: '', price: '', image: '' }
        }
      })
      this.servicesInfo = await Promise.all(promises)
      // Calcular datos extra para cada servicio usando el nuevo endpoint
      let precioTotalEvento = 0
      const availabilityPromises = this.servicesInfo.map(async service => {
        try {
          const availabilityData = await EventServiceServices.checkServiceAvailability(
            service.id,
            this.eventPreviewData.event
          )
          const precioTotal = availabilityData.price
          precioTotalEvento += precioTotal
          return {
            ...service,
            dataInicio: availabilityData.data_inicio,
            dataFin: availabilityData.data_fin,
            cantidad: availabilityData.cantidad,
            disponible: true,
            precioTotal
          }
        } catch (error) {
          console.error(`Error al verificar disponibilidad del servicio ${service.id}:`, error)
          return {
            ...service,
            dataInicio: this.eventPreviewData.event.data_inici,
            dataFin: this.eventPreviewData.event.data_fi,
            cantidad: 1,
            disponible: false,
            precioTotal: 0
          }
        }
      })
      this.serviciosConDatos = await Promise.all(availabilityPromises)
      this.precioTotalEvento = precioTotalEvento
      this.loadingServices = false
    },
    closeEventPreview () {
      this.showEventPreview = false
      this.eventPreviewData = null
    },
    async saveGeneratedEvent () {
      this.savingEvent = true
      try {
        // 1. Crear el evento
        const eventToSave = { ...this.eventPreviewData.event }
        delete eventToSave.pressupost
        console.log('Creando evento con:', eventToSave)
        const createdEvent = await EventService.create(eventToSave)
        console.log('Evento creado:', createdEvent)

        // 2. Añadir los servicios uno a uno al evento creado
        for (const servicio of this.serviciosConDatos) {
          const serviceData = {
            event_id: createdEvent.id,
            service_id: servicio.id,
            cantidad: servicio.cantidad,
            data_inicio: servicio.dataInicio,
            data_fin: servicio.dataFin
          }
          console.log('Añadiendo servicio al evento:', serviceData)
          await EventServiceServices.addServiceToEvent(serviceData)
        }

        this.savingEvent = false
        this.showEventPreview = false
        Swal.fire({
          title: '¡Evento guardado!',
          text: 'El evento y sus servicios han sido creados correctamente.',
          icon: 'success',
          confirmButtonColor: '#800020'
        })
        this.$router.push(`/eventServices/${createdEvent.id}`)
      } catch (error) {
        this.savingEvent = false
        console.error('Error al guardar el evento o sus servicios:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo guardar el evento o sus servicios. Por favor, inténtalo de nuevo.',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    formatDate (dateStr) {
      if (!dateStr) return ''
      const d = new Date(dateStr)
      return d.toLocaleString('es-ES', { dateStyle: 'medium', timeStyle: 'short' })
    },
    getServiceTypeLabel (type) {
      const types = {
        musica: 'Música',
        fotografia: 'Fotografía',
        espai: 'Espacio',
        catering: 'Catering',
        mobiliario: 'Mobiliario',
        decoracion: 'Decoración',
        decoracio: 'Decoración',
        'mobiliari-decoracio': 'Mobiliario/Decoración'
      }
      return types[type] || type
    },
    getServiceExtraInfo (service) {
      if (!service) return []
      const info = []
      if (service.category === 'espai' && service.espai && service.espai.espai_type) {
        info.push({ label: 'Tipología', value: service.espai.espai_type })
      } else if (service.category === 'catering' && service.catering) {
        if (service.catering.tipo_entrega) info.push({ label: 'Tipo de entrega', value: service.catering.tipo_entrega })
        if (service.catering.tipo_catering) info.push({ label: 'Tipo de servicio', value: service.catering.tipo_catering })
        if (service.catering.menu && service.catering.menu.type_menu) info.push({ label: 'Tipo menú', value: service.catering.menu.type_menu })
        else if (service.catering.articulo && service.catering.articulo.type_articulo) info.push({ label: 'Tipo Artículo', value: service.catering.articulo.type_articulo })
      } else if ((service.category === 'mobiliario' || service.category === 'decoracion' || service.category === 'decoracio' || service.category === 'mobiliari-decoracio') && service.mobiliari_decoracio) {
        if (service.mobiliari_decoracio.tipologia) info.push({ label: 'Tipología', value: service.mobiliari_decoracio.tipologia })
        if (service.mobiliari_decoracio.subtipologia) info.push({ label: 'Subtipología', value: service.mobiliari_decoracio.subtipologia })
      } else if (service.category === 'musica' && service.musica) {
        if (service.musica.musica_type) info.push({ label: 'Tipo de música', value: service.musica.musica_type })
        if (service.musica.canciones) info.push({ label: 'Tipo de canciones', value: service.musica.canciones })
      } else if (service.category === 'fotografia' && service.fotografia) {
        if (service.fotografia.fotografia_type) info.push({ label: 'Tipo de servicio', value: service.fotografia.fotografia_type })
        if (service.fotografia.servicio_especial_type && service.fotografia.fotografia_type === 'servicio_especial') {
          info.push({ label: 'Tipo servicio especial', value: service.fotografia.servicio_especial_type })
        }
      }
      return info
    },
    borrarAsistente () {
      localStorage.removeItem('assistant_eventData')
      localStorage.removeItem('assistant_chatMessages')
      // Resetear estado
      this.eventData = {
        name: '',
        type: '',
        fechahora_inicio: '',
        fechahora_final: '',
        num_invitats: '',
        pressupost: '',
        has_espai_propi: false,
        selectedServices: []
      }
      this.chatMessages = [
        {
          type: 'assistant',
          text: '¡Hola! Soy tu asistente inteligente para la planificación de eventos. ¿Cómo puedo ayudarte hoy?'
        }
      ]
    }
  },
  watch: {
    eventData: {
      handler (val) {
        localStorage.setItem('assistant_eventData', JSON.stringify(val))
      },
      deep: true
    },
    chatMessages: {
      handler (val) {
        localStorage.setItem('assistant_chatMessages', JSON.stringify(val))
      },
      deep: true
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
    // Recuperar estado guardado
    const savedEventData = localStorage.getItem('assistant_eventData')
    if (savedEventData) {
      this.eventData = JSON.parse(savedEventData)
    }
    const savedChat = localStorage.getItem('assistant_chatMessages')
    if (savedChat) {
      this.chatMessages = JSON.parse(savedChat)
    }
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>

<style scoped>
.icon-send {
  font-size: 1.5rem;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
.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 styles */
.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);
}

.reset {
  background-color: #800020;
  color:  #ffeaea;
  border-color: #ffeaea;
  margin-left: 1rem;
  font-weight: 600;
  transition: background 0.2s, color 0.2s, border 0.2s;
  padding: 0.75rem 1rem;
  justify-content: center;
  align-items: center;
  margin-left: 10.5rem;

  margin-top: 2.5rem;
}

.reset:hover {
  background-color:#a8324a;
  color:  #ffeaea;
  border-color: #ffeae;
}

.intelligent-assistant {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.assistant-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  background: white;
  border-radius: 15px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-weight: 600;
  color: #2C3E50;
  font-size: 1rem;
}

input, select {
  padding: 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

input:focus, select:focus {
  outline: none;
  border-color: #800020;
  box-shadow: 0 0 0 3px rgba(128, 0, 32, 0.1);
}

.services-selection {
  margin-top: 2rem;
  grid-column: 1 / -1;
}

.services-selection h3 {
  color: #800020;
  margin-bottom: 1rem;
  font-size: 1.2rem;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}

.service-checkbox {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  padding: 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.service-checkbox:hover {
  border-color: #800020;
  background-color: #f8f9fa;
}

.service-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #800020;
}

.service-checkbox label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-weight: 500;
}

.service-checkbox i {
  color: #800020;
}

/* Chat Styles mejorados */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 800px; /* antes 600px */
  min-width: 500px; /* más ancho */
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message {
  max-width: 90%;
  padding: 1rem;
  border-radius: 12px;
  margin: 0.5rem 0;
  text-align: left; /* Alineación a la izquierda */
  word-break: break-word;
}

.message.user {
  align-self: flex-end;
  background-color: #800020;
  color: white;
}

.message.assistant {
  align-self: flex-start;
  background-color:rgb(237, 237, 237);
  color: #2C3E50;
}

.chat-input {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-top: 2px solid #e0e0e0;
}

.chat-input textarea {
  flex: 1;
  padding: 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  resize: none;
  height: 60px;
  font-family: inherit;
}

.chat-input textarea:focus {
  outline: none;
  border-color: #800020;
}

.send-button {
  background-color: #800020;
  color: white;
  border: none;
  border-radius: 8px;
  width: 60px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.send-button:hover:enabled {
  background-color: #600018;
}

@media (max-width: 1024px) {
  .assistant-container {
    grid-template-columns: 1fr;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .services-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .services-grid {
    grid-template-columns: 1fr;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 15px;
  width: 90%;
  max-width: 1000px;
  max-height: 90vh;
  overflow-y: auto;
  padding: 2rem;
}

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

.modal-header h3 {
  color: #800020;
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #666;
  cursor: pointer;
  padding: 0.5rem;
}

.close-button:hover {
  color: #800020;
}

.modal-body {
  margin-bottom: 2rem;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 2.2rem;
  padding-top: 2rem;
  border-top: 2px solid #e0e0e0;
  background: transparent;
}

.space-type-selection {
  margin-bottom: 2rem;
}

.space-type-options {
  display: flex;
  gap: 1rem;
}

.space-type-button {
  background: none;
  border: none;
  padding: 0.5rem 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

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

.existing-space-section {
  margin-bottom: 2rem;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: #800020;
  gap: 0.5rem;
  margin: 2rem 0;
}

.no-spaces-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 2rem;
}

.spaces-table-container {
  overflow-y: auto;
  max-height: 300px;
}

.spaces-table {
  width: 100%;
  border-collapse: collapse;
}

.spaces-table th,
.spaces-table td {
  padding: 0.75rem;
  text-align: left;
}

.spaces-table th {
  background-color: #f8f9fa;
}

.spaces-table tbody tr {
  background-color: white;
}

.spaces-table tbody tr:nth-child(even) {
  background-color: #f8f9fa;
}

.spaces-table tbody tr:hover {
  background-color: #f0f0f0;
}

.location-cell {
  white-space: nowrap;
}

.location-text {
  display: block;
}

.actions-cell {
  text-align: right;
}

.action-button {
  background: none;
  border: none;
  padding: 0.5rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.action-button.use {
  color: #800020;
}

.action-button.use.active {
  background-color: #800020;
  color: white;
}

.action-button.view {
  color: #666;
}

.action-button.view:hover {
  color: #800020;
}

.space-main-info {
  margin-bottom: 2rem;
}

.form-section {
  margin-bottom: 2rem;
}

.form-section h4 {
  color: #800020;
  margin-bottom: 1rem;
}

.form-grid.address-grid {
  gap: 1rem;
}

.form-group.full-width {
  grid-column: span 2;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}

.feature-checkbox {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.feature-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #800020;
}

.feature-checkbox label {
  cursor: pointer;
}

.event-preview-btn {
  margin-top: 1rem;
  background-color: #800020;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 0.7rem 1.2rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
}
.event-preview-btn:hover {
  background-color: #600018;
}

.event-preview-modal {
  max-width: 850px;
  width: 100%;
  padding: 2.5rem 2.5rem 2rem 2.5rem;
  border-radius: 20px;
  box-shadow: 0 4px 24px rgba(128,0,32,0.13);
}
.event-card-preview {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

/* Estilos globales para los botones del modal */
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 2.2rem;
  padding-top: 2rem;
  border-top: 2px solid #e0e0e0;
  background: transparent;
}

.modal-footer .button {
  border-radius: 14px;
  font-size: 1.1rem;
  font-weight: 700;
  padding: 0.5rem 1.5rem;
  border: none;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.1s;
  box-shadow: 0 4px 16px rgba(128,0,32,0.13);
  letter-spacing: 0.7px;
  cursor: pointer;
  outline: none;
}

.modal-footer .button.primary {
  background: linear-gradient(90deg, #800020 60%, #a8324a 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(128,0,32,0.10);
  text-transform: uppercase;
  font-size: 1rem;
  font-weight: 700;
  letter-spacing: 1px;
}

.modal-footer .button.primary:hover {
  background: linear-gradient(90deg, #a8324a 60%, #800020 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(128,0,32,0.13);
  transform: translateY(-2px) scale(1.04);
}

.modal-footer .button.secondary {
  background: #fff;
  color: #800020;
  border: 2px solid #800020;
  box-shadow: 0 2px 8px rgba(128,0,32,0.06);
  text-transform: uppercase;
  font-size: 1rem;
  font-weight: 700;
  letter-spacing: 0.7px;
}

.modal-footer .button.secondary:hover {
  background: #ffeaea;
  color: #a8324a;
  border-color: #a8324a;
  box-shadow: 0 4px 16px rgba(168,50,74,0.10);
  transform: translateY(-2px) scale(1.04);
}
</style>
