<template>
  <div class="payment-container">
    <!-- 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>Pago del Evento</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="payment-content">
      <div class="payment-grid">
        <!-- Resumen del evento -->
        <div class="event-summary">
          <h2>Resumen del Evento</h2>
          <div v-if="event" class="summary-content">
            <div class="summary-item">
              <span class="label">Nombre del evento:</span>
              <span class="value">{{ event.name }}</span>
            </div>
            <div class="summary-item">
              <span class="label">Tipo:</span>
              <span class="value">{{ getEventTypeLabel(event.tipus) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">Fecha de inicio:</span>
              <span class="value">{{ formatDateTime(event.data_inici) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">Fecha de fin:</span>
              <span class="value">{{ formatDateTime(event.data_fi) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">Número de invitados:</span>
              <span class="value">{{ event.num_invitats }}</span>
            </div>
            <div class="summary-item total">
              <span class="label">Total a pagar:</span>
              <span class="value">{{ event.pressupost }} €</span>
            </div>
          </div>
          <div v-else class="loading">
            <i class="bi bi-arrow-repeat"></i> Cargando información del evento...
          </div>
        </div>

        <!-- Formulario de pago -->
        <div class="payment-form">
          <h2>Datos de Pago</h2>
          <form @submit.prevent="processPayment">
            <div class="form-group">
              <label for="cardName">Nombre en la tarjeta</label>
              <input
                type="text"
                id="cardName"
                v-model="paymentData.cardName"
                required
                placeholder="Nombre completo de la tarjeta"
              />
            </div>

            <div class="form-group">
              <label for="cardNumber">Número de tarjeta</label>
              <div class="card-input">
                <input
                  type="text"
                  id="cardNumber"
                  v-model="paymentData.cardNumber"
                  required
                  placeholder="1234 5678 9012 3456"
                  maxlength="19"
                  @input="formatCardNumber"
                />
                <i class="bi bi-credit-card"></i>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="expiryDate">Fecha de expiración</label>
                <input
                  type="text"
                  id="expiryDate"
                  v-model="paymentData.expiryDate"
                  required
                  placeholder="MM/AA"
                  maxlength="5"
                  @input="formatExpiryDate"
                />
              </div>

              <div class="form-group">
                <label for="cvv">CVV</label>
                <input
                  type="text"
                  id="cvv"
                  v-model="paymentData.cvv"
                  required
                  placeholder="123"
                  maxlength="3"
                  @input="formatCVV"
                />
              </div>
            </div>

            <div class="form-group">
              <label for="email">Email para el recibo</label>
              <input
                type="email"
                id="email"
                v-model="paymentData.email"
                required
                placeholder="tu@email.com"
              />
            </div>

            <div class="payment-actions">
              <button type="button" class="cancel-btn" @click="$router.back()">
                <i class="bi bi-arrow-left"></i>
                Volver
              </button>
              <button type="submit" class="pay-btn" :disabled="isProcessing">
                <i class="bi bi-credit-card"></i>
                {{ isProcessing ? 'Procesando...' : 'Pagar ' + (event ? event.pressupost : '0') + ' €' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Información detallada del evento -->
      <div class="event-info-section">
        <h2><i class="bi bi-info-circle"></i> Información del evento</h2>
        <div class="event-details-grid">
          <div class="event-detail-row">
            <i class="bi bi-card-text"></i>
            <span class="label">Nombre:</span>
            <span class="value">{{ event ? event.name : 'Sin nombre' }}</span>
          </div>
          <div class="event-detail-row">
            <i class="bi bi-tag"></i>
            <span class="label">Tipo:</span>
            <span class="value">{{ event ? getEventTypeLabel(event.tipus) : 'Sin tipo' }}</span>
          </div>
          <div class="event-detail-row">
            <i class="bi bi-people"></i>
            <span class="label">Invitados:</span>
            <span class="value">{{ event ? event.num_invitats : 'Sin invitados' }}</span>
          </div>
          <div class="event-detail-row">
            <i class="bi bi-clock-history"></i>
            <span class="label">Precio total:</span>
            <span class="value">{{ event ? event.pressupost + ' €' : 'Sin precio' }}</span>
          </div>
          <div class="event-detail-row">
            <i class="bi bi-calendar-event"></i>
            <span class="label">Fecha inicio:</span>
            <span class="value">{{ event ? formatDateTime(event.data_inici) : 'Sin fecha' }}</span>
          </div>
          <div class="event-detail-row">
            <i class="bi bi-clock"></i>
            <span class="label">Fecha fin:</span>
            <span class="value">{{ event ? formatDateTime(event.data_fi) : 'Sin fecha' }}</span>
          </div>
        </div>

        <!-- Servicios seleccionados -->
        <div class="services-section">
          <h3><i class="bi bi-list-check"></i> Servicios seleccionados</h3>
          <div class="services-grid">
            <GeneralEventServiceCard
              v-for="service in services"
              :key="service.id"
              :service="service.service"
              :eventId="event.id"
              :numInvitats="event.num_invitats"
              :event="event"
              :reserva="service"
              :showEditButton="false"
              :onRemove="handleServiceDeleted"
              :onEdit="handleServiceUpdated"
              @updated="handleServiceUpdated"
              @update-event-info="loadEvent"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Navbar from '@/components/event_services/EventCard.vue'
import EventService from '@/services/EventServices'
import EventServiceServices from '@/services/EventServiceServices'
import GeneralEventServiceCard from '@/components/event_services/GeneralEventServiceCard.vue'
import Swal from 'sweetalert2'

export default {
  name: 'Payment',
  components: {
    Navbar,
    GeneralEventServiceCard
  },
  data () {
    return {
      logo: require('@/assets/LogoEventAiTransGran.png'),
      event: null,
      services: [],
      isProcessing: false,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0,
      paymentData: {
        cardName: '',
        cardNumber: '',
        expiryDate: '',
        cvv: '',
        email: ''
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  async created () {
    await this.loadEvent()
  },
  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 loadEvent () {
      try {
        const eventId = this.$route.params.uid
        const eventData = await EventService.getById(eventId)
        this.event = eventData
        console.log('Evento cargado:', this.event)

        // Cargar los servicios del evento
        const servicesData = await EventServiceServices.getEventServices(eventId)
        console.log('Servicios cargados:', servicesData)
        this.services = servicesData || []
      } catch (error) {
        console.error('Error al cargar el evento:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo cargar la información del evento',
          icon: 'error',
          confirmButtonColor: '#800020'
        }).then(() => {
          this.$router.back()
        })
      }
    },
    formatDateTime (dateTime) {
      return new Date(dateTime).toLocaleString('es-ES', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getEventTypeLabel (type) {
      const types = {
        'boda': 'Boda',
        'graduacio': 'Graduación',
        'festa': 'Fiesta',
        'celebracio': 'Celebración',
        'menjar_grup': 'Comida de Grupo',
        'altres': 'Otros'
      }
      return types[type] || type
    },
    getServiceTypeLabel (type) {
      const types = {
        'espai': 'Espacio',
        'catering': 'Catering',
        'mobiliari': 'Mobiliario',
        'decoracio': 'Decoración',
        'musica': 'Música',
        'fotografia': 'Fotografía'
      }
      return types[type] || type
    },
    getServiceIcon (type) {
      const icons = {
        'espai': 'bi bi-house',
        'catering': 'bi bi-cup-hot',
        'mobiliari': 'bi bi-lamp',
        'decoracio': 'bi bi-flower1',
        'musica': 'bi bi-music-note-beamed',
        'fotografia': 'bi bi-camera'
      }
      return icons[type] || 'bi bi-box'
    },
    formatCardNumber (event) {
      let value = event.target.value.replace(/\D/g, '')
      value = value.replace(/(\d{4})/g, '$1 ').trim()
      this.paymentData.cardNumber = value
    },
    formatExpiryDate (event) {
      let value = event.target.value.replace(/\D/g, '')
      if (value.length >= 2) {
        value = value.slice(0, 2) + '/' + value.slice(2)
      }
      this.paymentData.expiryDate = value
    },
    formatCVV (event) {
      let value = event.target.value.replace(/\D/g, '')
      this.paymentData.cvv = value
    },
    async processPayment () {
      this.isProcessing = true
      try {
        // Aquí iría la lógica de integración con el gateway de pago
        // Por ahora simulamos un pago exitoso
        await new Promise(resolve => setTimeout(resolve, 2000))

        // Actualizar el estado del evento a pagado
        await EventService.update(this.event.id, { estat: 'pagado' })

        Swal.fire({
          title: '¡Pago exitoso!',
          text: 'Tu evento ha sido confirmado correctamente',
          icon: 'success',
          confirmButtonColor: '#800020'
        }).then(() => {
          this.$router.push('/myEvents')
        })
      } catch (error) {
        console.error('Error al procesar el pago:', error)
        Swal.fire({
          title: 'Error',
          text: 'Hubo un problema al procesar el pago. Por favor, inténtalo de nuevo.',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      } finally {
        this.isProcessing = false
      }
    },
    async handleServiceUpdated (updatedService) {
      console.log('handleServiceUpdated llamado con:', updatedService)
      try {
        // Actualizar el servicio en la lista
        const index = this.services.findIndex(s => s.id === updatedService.id)
        if (index !== -1) {
          this.services[index] = updatedService
          console.log('Servicio actualizado en la lista:', this.services[index])
        } else {
          console.warn('No se encontró el servicio a actualizar:', updatedService)
        }
        // Recargar el evento para actualizar el presupuesto
        await this.loadEvent()
        console.log('Evento recargado después de actualizar servicio')
      } catch (error) {
        console.error('Error al actualizar el servicio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo actualizar el servicio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    async handleServiceDeleted (service) {
      console.log('handleServiceDeleted llamado con servicio:', service)
      try {
        const result = await Swal.fire({
          title: '¿Estás seguro?',
          text: '¿Quieres eliminar este servicio del evento? Esta acción no se puede deshacer.',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#800020',
          cancelButtonColor: '#6c757d',
          confirmButtonText: 'Sí, eliminar',
          cancelButtonText: 'Cancelar'
        })

        if (result.isConfirmed) {
          // Eliminar el servicio usando el servicio EventServiceServices
          await EventServiceServices.removeServiceFromEvent(service.event_id, service.service.id)

          // Eliminar el servicio de la lista local
          this.services = this.services.filter(s => s.id !== service.id)
          console.log('Servicio eliminado de la lista local')

          // Recargar el evento para actualizar el presupuesto
          await this.loadEvent()
          console.log('Evento recargado después de eliminar servicio')

          Swal.fire({
            title: 'Servicio eliminado',
            text: 'El servicio ha sido eliminado correctamente',
            icon: 'success',
            confirmButtonColor: '#800020'
          })
        }
      } catch (error) {
        console.error('Error al eliminar el servicio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo eliminar el servicio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    }
  }
}
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-top: 140px;
}

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

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

.payment-header {
  text-align: center;
  margin-bottom: 3rem;
}

.payment-header h1 {
  color: #800020;
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.subtitle {
  color: #666;
  font-size: 1.1rem;
}

.payment-grid {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 2rem;
}

.event-summary, .payment-form {
  padding: 1.5rem;
}

.event-summary {
  background: #f8f9fa;
  border-radius: 8px;
}

.event-summary h2, .payment-form h2 {
  color: #800020;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
}

.summary-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #eee;
}

.summary-item .label {
  color: #666;
  font-weight: 500;
}

.summary-item .value {
  color: #333;
  font-weight: 600;
}

.summary-item.total {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 2px solid #800020;
  font-size: 1.2rem;
}

.summary-item.total .value {
  color: #800020;
  font-size: 1.4rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus {
  border-color: #800020;
  outline: none;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.card-input {
  position: relative;
}

.card-input i {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.payment-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
  gap: 1rem;
}

.cancel-btn, .pay-btn {
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.pay-btn {
  background: #800020;
  color: white;
  border: none;
  flex: 1;
  justify-content: center;
}

.pay-btn:hover:not(:disabled) {
  background: #a8324a;
}

.pay-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  color: #666;
  font-style: italic;
}

.loading i {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

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

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

  .payment-actions {
    flex-direction: column;
  }

  .cancel-btn, .pay-btn {
    width: 100%;
    justify-content: center;
  }
}

.event-info-section {
  margin-top: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  padding: 2rem;
}

.event-info-section h2 {
  color: #800020;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.event-details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.event-detail-row {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  padding: 0.8rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.event-detail-row i {
  color: #800020;
  font-size: 1.2rem;
}

.event-detail-row .label {
  color: #666;
  font-weight: 500;
  min-width: 100px;
}

.event-detail-row .value {
  color: #333;
  font-weight: 600;
}

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

.services-section {
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #eee;
}

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

.services-grid {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

@media (max-width: 768px) {
  .services-grid {
    gap: 0.8rem;
  }
}
</style>
