<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>Mis Eventos</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="my-events-container">
      <div v-if="loading">Cargando...</div>
      <div v-else-if="error">{{ error }}</div>
      <div v-else>
      <div v-if="events.length === 0" class="no-events-message">
        <i class="bi bi-calendar-x"></i>
        <p>No tiene eventos creados hasta el momento.</p>
      </div>
      <div v-else class="events-list">
        <EventCard
          v-for="event in events"
          :key="event.id"
          :event="event"
          :showEditButton="!readonly"
          :myEvents="!readonly"
          :readonly="readonly"
          @view-details="viewEventDetails"
          @event-deleted="handleEventDeleted"
        />
      </div>

      <!-- Modal para ver detalles del evento -->
      <div v-if="showEventDetails" class="modal-overlay" @click="closeEventDetails">
        <div class="modal-content" @click.stop>
          <EventDetails v-if="selectedEvent" :eventId="selectedEvent.id" :readonly="readonly" />
          <button class="close-btn" @click="closeEventDetails">
            <i class="fas fa-times"></i>
          </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import EventService from '@/services/EventServices'
import ServiceCard from './event_services/ServiceCard.vue'
import CateringServiceCard from './event_services/CateringService.vue'
import EspaiServiceCard from './event_services/EspaiService.vue'
import MobiliariServiceCard from './event_services/MobiliariService.vue'
import DecoracioServiceCard from './event_services/DecoracioService.vue'
import MusicaServiceCard from './event_services/MusicaService.vue'
import FotografiaServiceCard from './event_services/FotografiaService.vue'
import ServiceList from './event_services/ServiceList.vue'
import EventCard from './event_services/EventCard.vue'
import EventDetails from './event_services/EventDetails.vue'

export default {
  name: 'UserEvents',
  props: {
    userId: {
      type: String,
      required: true
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ServiceCard,
    CateringServiceCard,
    EspaiServiceCard,
    MobiliariServiceCard,
    DecoracioServiceCard,
    MusicaServiceCard,
    FotografiaServiceCard,
    ServiceList,
    EventCard,
    EventDetails
  },
  data () {
    return {
      logo: require('../assets/LogoEventAiTransGran.png'),
      events: [],
      showEventDetails: false,
      selectedEvent: null,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0,
      loading: true,
      error: null
    }
  },
  watch: {
    userId: {
      immediate: true,
      handler (newVal) {
        console.log('userId recibido en el componente:', newVal)
        if (newVal) {
          this.loadEvents()
        } else {
          this.events = []
          this.error = 'No se ha proporcionado el ID de usuario'
        }
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  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
      }, 100)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      this.isNavbarHidden = this.mouseY > 110
    },
    getServiceComponent (service) {
      console.log('getServiceComponent llamado con:', service)
      switch (service.type) {
        case 'catering':
          return 'CateringServiceCard'
        case 'espai':
          return 'EspaiServiceCard'
        case 'mobiliari':
          return 'MobiliariServiceCard'
        case 'decoracio':
          return 'DecoracioServiceCard'
        case 'musica':
          return 'MusicaServiceCard'
        case 'fotografia':
          return 'FotografiaServiceCard'
        default:
          return 'ServiceCard'
      }
    },
    async loadEvents () {
      if (!this.userId) {
        this.events = []
        this.error = 'No se ha proporcionado el ID de usuario'
        return
      }
      try {
        this.loading = true
        const response = await EventService.getByAccountId(this.userId)
        console.log('Respuesta de eventos:', response)
        this.events = response && response.data ? response.data : []
        this.error = null
      } catch (error) {
        this.error = 'No se pudieron cargar los eventos'
        this.events = []
      } finally {
        this.loading = false
      }
    },
    formatDateTime (dateTime) {
      console.log('formatDateTime llamado con:', dateTime)
      return new Date(dateTime).toLocaleString('es-ES', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getEventTypeLabel (type) {
      console.log('getEventTypeLabel llamado con:', type)
      const types = {
        'boda': 'Boda',
        'graduacio': 'Graduación',
        'festa': 'Fiesta',
        'celebracio': 'Celebración',
        'menjar_grup': 'Comida de Grupo',
        'altres': 'Otros'
      }
      return types[type] || type
    },
    getStatusLabel (status) {
      console.log('getStatusLabel llamado con:', status)
      const statuses = {
        'en_curso': 'En Curso',
        'guardado': 'Guardado',
        'pagado': 'Pagado',
        'expirado': 'Expirado',
        'cancelado': 'Cancelado',
        'finalizado': 'Finalizado'
      }
      return statuses[status] || status
    },
    getStatusClass (status) {
      console.log('getStatusClass llamado con:', status)
      const classes = {
        'en_curso': 'status-en_curso',
        'guardado': 'status-guardado',
        'pagado': 'status-pagado',
        'expirado': 'status-expirado',
        'cancelado': 'status-cancelado',
        'finalizado': 'status-finalizado'
      }
      return classes[status] || ''
    },
    async viewEventDetails (eventId) {
      console.log('viewEventDetails llamado con eventId:', eventId)
      try {
        const event = await EventService.getById(eventId)
        console.log('Detalles del evento cargados:', event)
        this.selectedEvent = event
        this.showEventDetails = true
      } catch (error) {
        console.error('Error al cargar los detalles del evento:', error)
      }
    },
    closeEventDetails () {
      console.log('Cerrando detalles del evento')
      this.showEventDetails = false
      this.selectedEvent = null
    },
    editEvent (eventId) {
      this.$router.push(`/eventServices/${eventId}`)
    },
    handleEventDeleted (eventId) {
      this.events = this.events.filter(event => event.id !== eventId)
    }
  }
}
</script>

<style scoped>
.bi {
  font-size: 0.5rem;
}
.bi-plus-circle {
  font-size: 1.5rem;
  padding-top: 0.5rem;
}
.page-container {
  padding-top: 70px;
  min-height: 100vh;
  background: #f8f9fa;
  background-image: url('../assets/fondoPage2.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);
}

.my-events-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.page-title {
  color: #800020;
  font-size: 2rem;
  margin-bottom: 2rem;
  text-align: center;
}

.events-list {
  display: grid;
  gap: 2rem;
  padding: 1rem;
}

.event-card {
  background: white;
  border: none;
  border-radius: 14px;
  padding: 1.5rem 2.5rem 1.2rem 2.5rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.07);
  transition: all 0.2s;
  position: relative;
  overflow: hidden;
  min-width: 600px;
  max-width: 900px;
  margin: 0 auto;
}

.event-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 100%;
  background: #800020;
  border-radius: 4px 0 0 4px;
}

.event-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.2rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #f0f0f0;
}

.event-name {
  color: #800020;
  font-size: 1.2rem;
  font-weight: 600;
  margin: 0;
  letter-spacing: -0.5px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.event-type {
  background: #f8f9fa;
  color: #800020;
  padding: 0.5rem 1.5rem;
  border-radius: 24px;
  font-size: 1.2rem;
  font-weight: 700;
  border: 1px solid rgba(128, 0, 32, 0.1);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.event-details {
  margin-bottom: 0.7rem;
  display: flex;
  flex-wrap: nowrap;
  gap: 3.5rem;
  align-items: flex-end;
  font-size: 1rem;
  justify-content: space-between;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0.3rem;
  color: #4b5563;
  font-size: 1rem;
  min-width: 120px;
}

.detail-item i {
  color: #800020;
  font-size: 1.3rem;
  margin-bottom: 0.2rem;
}

.detail-title {
  font-size: 0.92rem;
  color: #800020;
  font-weight: 500;
  margin-bottom: 0.1rem;
}

.event-status {
  margin-top: 0.2rem;
  margin-bottom: 0.2rem;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.35rem 1rem;
  border-radius: 16px;
  font-size: 0.95rem;
  font-weight: 600;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  border: none;
}

.status-cancelado {
  background: #ffeaea;
  color: #b91c1c;
  border: 1px solid #fca5a5;
}
.status-guardado {
  background: #e0e7ff;
  color: #2563eb;
  border: 1px solid #60a5fa;
}
.status-en_curso {
  background: #fff7e6;
  color: #d97706;
  border: 1px solid #fbbf24;
}
.status-pagado {
  background: #e6fbe6;
  color: #059669;
  border: 1px solid #34d399;
}
.status-expirado {
  background: #e5e7eb;
  color: #374151;
  border: 1px solid #9ca3af;
}
.status-finalizado {
  background: #ede9fe;
  color: #7c3aed;
  border: 1px solid #a78bfa;
}

.event-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.7rem;
  margin-top: 0.7rem;
  padding-top: 0.7rem;
  border-top: 1px solid #f0f0f0;
}

.edit-event-btn, .view-details-btn {
  padding: 0.5rem 1.1rem;
  border-radius: 8px;
  font-size: 0.98rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}

.edit-event-btn {
  background: #4CAF50;
  color: white;
  border: none;
  transition: all 0.2s;
}
.edit-event-btn:hover {
  background: #388e3c;
}

.view-details-btn {
  background: #800020;
  color: white;
  border: none;
  transition: all 0.2s;
}
.view-details-btn:hover {
  background: #a8324a;
}

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

.modal-content {
  background: white;
  border-radius: 12px;
  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 h2 {
  color: #800020;
  margin: 0;
}

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

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

.services-list {
  display: grid;
  gap: 1rem;
}

.compact-service-card {
  transform: scale(0.9);
  transform-origin: top left;
}

@media (max-width: 768px) {
  .event-card {
    padding: 1rem;
    min-width: unset;
    max-width: unset;
  }
  .event-actions {
    flex-direction: column;
    gap: 0.5rem;
  }
  .edit-event-btn, .view-details-btn {
    width: 100%;
    justify-content: center;
  }
}

.no-events-message {
  text-align: center;
  color: #800020;
  margin: 3rem 0 2rem 0;
  font-size: 1.2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.2rem;
}
.no-events-message i {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}
.create-event-btn {
  background: #800020;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 0.7rem 1.5rem;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.7rem;
  cursor: pointer;
  transition: background 0.2s;
}
.create-event-btn i {
  font-size: 1.3rem;
}
.create-event-btn:hover {
  background: #a8324a;
}
</style>
