<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" v-if="user.role === 'client'" @click="$router.push('/mainPageClient')" />
      </div>
      <div class="navbar-center">
        <h1>Mi Perfil</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="page-background">
      <div class="profile-container">
        <!-- Cabecera editable -->
        <div class="profile-header">
          <div class="profile-photo-block">
            <img :src="user.photo || defaultAvatar" alt="Foto de perfil" class="profile-photo" />
            <button class="edit-photo-btn" @click="showEditModal = true" title="Editar foto"><i class="bi bi-camera"></i></button>
          </div>
          <div class="profile-info-block">
            <div class="profile-username-row">
              <span class="profile-username">@{{ user.username }}</span>
              <button class="edit-btn-perfil" @click="showEditModal = true" title="Editar perfil"><i class="bi icono_perfil bi-pencil"></i></button>
            </div>
            <div class="profile-fullname">{{ user.fullname }}</div>
            <div class="profile-bio">{{ user.bio }}</div>
          </div>
        </div>

        <!-- Modal de edición de perfil -->
        <div v-if="showEditModal" class="modal-overlay" @click.self="showEditModal = false">
          <div class="modal-content" @click.stop>
            <h3>Editar perfil</h3>
            <form @submit.prevent="saveProfile">
              <div class="form-group">
                <label>Username</label>
                <input v-model="editUser.username" type="text" required />
              </div>
              <div class="form-group">
                <label>Bio</label>
                <textarea v-model="editUser.bio" rows="2" />
              </div>
              <div class="form-group">
                <label>Foto de perfil</label>
                <input type="file" @change="onPhotoChange" accept="image/*" />
                <img v-if="editUser.photo" :src="editUser.photo" alt="preview" class="profile-photo preview" />
              </div>
              <div class="modal-actions">
                <button type="submit" class="save-btn">Guardar</button>
                <button type="button" class="cancel-btn" @click="showEditModal = false">Cancelar</button>
              </div>
            </form>
          </div>
        </div>

        <!-- Navegación tipo pestañas/Instagram -->
        <div class="profile-tabs">
          <button
            v-for="tab in visibleTabs"
            :key="tab.key"
            :class="['profile-tab', { active: currentTab === tab.key }]"
            @click="currentTab = tab.key"
          >
            <i :class="tab.icon"></i> {{ tab.label }}
          </button>
        </div>

        <!-- Contenido de la pestaña seleccionada -->
        <div class="profile-tab-content">
          <component
            :is="currentTabComponent"
            v-if="currentTab !== 'myEspaiPropi'"
          />
          <MyEspaisPropis v-else />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import logo from '@/assets/LogoEventAiTransGran.png'
import defaultAvatar from '@/assets/account_icon.png'
import AccountServices from '@/services/AccountServices'
import MyEvents from './myEvents.vue'
import MyServices from './myServices.vue'
import EspaiPropiDetails from './event_services/EspaiPropiDetails.vue'
import RaiderFormMusica from './raider/RaiderFormMusica.vue'
import Swal from 'sweetalert2'
import UploadServices from '@/services/UploadServices'
import EspaiPropiServices from '@/services/EspaiPropiServices'
import EventService from '@/services/EventServices'
import MyEspaisPropis from './event_services/MyEspaisPropis.vue'
import MyRaiders from './raider/MyRaiders.vue'

export default {
  name: 'MyProfile',
  components: {
    MyEvents,
    MyServices,
    EspaiPropiDetails,
    RaiderFormMusica,
    MyEspaisPropis,
    MyRaiders
  },
  data () {
    return {
      logo,
      user: {
        photo: '',
        username: '',
        fullname: '',
        bio: ''
      },
      editUser: {
        photo: '',
        username: '',
        bio: ''
      },
      currentTab: 'myEvents',
      defaultAvatar,
      role: 'client',
      showEditModal: false,
      selectedFile: null,
      espaisPropis: [],
      loading: false,
      error: null,
      eventos: [],
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0
    }
  },
  computed: {
    visibleTabs () {
      if (this.role.includes('vendor')) {
        return [
          { key: 'myEvents', label: 'Mis eventos', icon: 'bi bi-calendar-event' },
          { key: 'myServices', label: 'Mis servicios', icon: 'bi bi-briefcase' },
          { key: 'myEspaiPropi', label: 'Mis espacios propios', icon: 'bi bi-house' },
          { key: 'myRaiders', label: 'Mis raiders', icon: 'bi bi-star' }
        ]
      } else {
        return [
          { key: 'myEvents', label: 'Mis eventos', icon: 'bi bi-calendar-event' },
          { key: 'myEspaiPropi', label: 'Mis espacios propios', icon: 'bi bi-house' }
        ]
      }
    },
    currentTabComponent () {
      switch (this.currentTab) {
        case 'myEvents': return 'MyEvents'
        case 'myServices': return 'MyServices'
        case 'myEspaiPropi': return 'MyEspaisPropis'
        case 'myRaiders': return 'MyRaiders'
        default: return 'div'
      }
    }
  },
  watch: {
    currentTab (newTab) {
      localStorage.setItem('profileCurrentTab', newTab)
    }
  },
  async created () {
    // Restaurar pestaña activa si existe
    const savedTab = localStorage.getItem('profileCurrentTab')
    if (savedTab) {
      this.currentTab = savedTab
    }
    await this.loadProfile()
    if (this.currentTab === 'myEspaiPropi') {
      await this.loadEspaiPropi()
    }
  },
  beforeDestroy () {
    localStorage.setItem('profileCurrentTab', this.currentTab)
    window.removeEventListener('scroll', this.handleScroll)
  },
  mounted () {
    window.addEventListener('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
      }, 50)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      this.isNavbarHidden = this.mouseY > 110
    },
    async loadProfile () {
      try {
        const userData = JSON.parse(localStorage.getItem('user'))
        console.log('userData completo del localStorage:', userData)

        if (userData) {
          // Intentar obtener la información actualizada del servidor
          try {
            const accountInfo = await AccountServices.getActualAccount()
            console.log('Información actualizada de la cuenta:', accountInfo)
            this.role = userData.role || 'client'
            this.user = {
              photo: accountInfo.photo || defaultAvatar,
              username: accountInfo.username || '',
              id: accountInfo.id || '',
              bio: accountInfo.bio || ''
            }

            this.editUser = {
              photo: this.user.photo,
              username: this.user.username,
              bio: this.user.bio
            }

            // Actualizar localStorage con la información actualizada
            const updatedUserData = {
              ...userData,
              account: accountInfo
            }
            localStorage.setItem('user', JSON.stringify(updatedUserData))

            console.log('User data loaded:', this.user)
          } catch (error) {
            console.error('Error al obtener la información actualizada:', error)
            // Si falla, usar los datos del localStorage
            this.user = {
              photo: userData.photo || defaultAvatar,
              username: userData.username || '',
              fullname: userData.fullname || '',
              bio: userData.bio || ''
            }

            this.editUser = {
              photo: this.user.photo,
              username: this.user.username,
              bio: this.user.bio
            }
          }
        }
      } catch (error) {
        console.error('Error al cargar el perfil:', error)
      }
    },
    async onPhotoChange (e) {
      const file = e.target.files[0]
      if (!file) return

      // Validar que sea una imagen JPEG, JPG o PNG
      const validTypes = ['image/jpeg', 'image/jpg', 'image/png']
      if (!validTypes.includes(file.type)) {
        Swal.fire({
          icon: 'error',
          title: 'Formato inválido',
          text: 'Por favor selecciona una imagen en formato JPEG, JPG o PNG.',
          timer: 2000,
          showConfirmButton: false
        })
        return
      }

      // Guardar el archivo para subirlo más tarde
      this.selectedFile = file

      // Mostrar vista previa temporal
      const reader = new FileReader()
      reader.onload = e2 => {
        this.editUser.photo = e2.target.result
      }
      reader.readAsDataURL(file)
    },
    async saveProfile () {
      console.log('Iniciando saveProfile')
      try {
        const userData = JSON.parse(localStorage.getItem('user'))
        console.log('userData', userData)

        if (userData && userData.account) {
          // Mostrar popup de confirmación
          const result = await Swal.fire({
            title: '¿Estás seguro?',
            text: '¿Quieres guardar los cambios en tu perfil?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#800020',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Sí, guardar cambios',
            cancelButtonText: 'Cancelar'
          })

          if (result.isConfirmed) {
            // Mostrar loading
            Swal.fire({
              title: 'Guardando cambios...',
              text: 'Por favor, espere mientras se procesan los cambios',
              allowOutsideClick: false,
              allowEscapeKey: false,
              showConfirmButton: false,
              didOpen: () => {
                Swal.showLoading()
              }
            })

            let photoUrl = this.editUser.photo

            // Si hay una nueva imagen seleccionada, subirla a S3
            if (this.selectedFile) {
              try {
                const uniqueName = `${Date.now()}_${this.selectedFile.name}`
                const renamedFile = new File([this.selectedFile], uniqueName, { type: this.selectedFile.type })
                photoUrl = await UploadServices.uploadImage(renamedFile)
              } catch (error) {
                console.error('Error al subir la imagen:', error)
                await Swal.close()
                Swal.fire({
                  icon: 'error',
                  title: 'Error',
                  text: 'Ha ocurrido un error al subir la imagen',
                  confirmButtonColor: '#800020'
                })
                return
              }
            }

            const updateData = {
              username: this.editUser.username,
              bio: this.editUser.bio,
              photo: photoUrl
            }

            // Actualizar el estado local
            this.user = {
              ...this.user,
              username: this.editUser.username,
              bio: this.editUser.bio,
              photo: photoUrl || defaultAvatar
            }

            // Actualizar localStorage
            const updatedUserData = {
              ...userData,
              account: {
                ...userData.account,
                username: this.editUser.username,
                bio: this.editUser.bio,
                photo: photoUrl || defaultAvatar
              }
            }
            localStorage.setItem('user', JSON.stringify(updatedUserData))

            // Llamar al servicio de actualización
            console.log('Llamando a updateAccount con:', updateData)
            const response = await AccountServices.updateAccount(updateData)
            console.log('Respuesta del servidor:', response)

            // Cerrar el loading
            await Swal.close()

            this.showEditModal = false
            this.selectedFile = null // Limpiar el archivo seleccionado

            // Mostrar mensaje de éxito
            Swal.fire({
              title: '¡Guardado!',
              text: 'Tu perfil se ha actualizado correctamente',
              icon: 'success',
              confirmButtonColor: '#800020'
            })
          }
        }
      } catch (error) {
        console.error('Error al actualizar el perfil:', error)
        Swal.fire({
          title: 'Error',
          text: 'Ha ocurrido un error al actualizar tu perfil',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    async loadEspaiPropi () {
      this.loading = true
      this.error = null
      try {
        const response = await EspaiPropiServices.getMyEspaiPropis()
        this.espaisPropis = response || []
        // Cargar eventos para verificar si los espacios están en uso
        const eventosResponse = await EventService.getMyEvents()
        this.eventos = eventosResponse || []
      } catch (error) {
        console.error('Error al cargar los espacios propios:', error)
        this.error = 'No se pudieron cargar los espacios propios'
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los espacios propios',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      } finally {
        this.loading = false
      }
    },
    espaiEnUso (espaiId) {
      return this.eventos.some(evento =>
        evento.espai_propi_id === espaiId &&
        ['guardado', 'pagado', 'en_curso'].includes(evento.estat)
      )
    },
    editEspaiPropi (espai) {
      this.$router.push(`/editEspaiPropi/${espai.id}`)
    },
    async confirmDeleteEspai (espai) {
      const result = await Swal.fire({
        title: '¿Estás seguro?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#800020',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
      })

      if (result.isConfirmed) {
        try {
          await EspaiPropiServices.deleteEspaiPropi(espai.id)
          await this.loadEspaiPropi()
          Swal.fire({
            title: '¡Eliminado!',
            text: 'El espacio propio ha sido eliminado correctamente',
            icon: 'success',
            confirmButtonColor: '#800020'
          })
        } catch (error) {
          console.error('Error al eliminar el espacio propio:', error)
          Swal.fire({
            title: 'Error',
            text: 'No se pudo eliminar el espacio propio',
            icon: 'error',
            confirmButtonColor: '#800020'
          })
        }
      }
    },
    goToMainPage () {
      if (this.role.includes('client')) {
        this.$router.push('/mainPageClient')
      } else {
        this.$router.push('/mainPageVendor')
      }
    }
  }
}
</script>

<style scoped>
@import url('https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css');
.icon_propi {
  font-size: 1.2rem;
  margin-right: 0.5rem;
  color: white;
}
.edit-btn-perfil {
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
}
.edit-btn-perfil {
  background: #800020;
  color: white;
  border: none;
}

.edit-btn-perfil:hover {
  background: #a8324a;
}
.page-container {
  padding-top: 140px;
  min-height: 100vh;
  background: #f8f9fa;
  background-image:  linear-gradient(rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 0.65)), url('../assets/fondoPage3.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  background-repeat: no-repeat;
}
.profile-container {
  max-width: 1150px;
  margin: 2.5rem auto;
  margin-top: 120px;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(128,0,32,0.08);
  padding: 2.5rem 2rem 1.5rem 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.profile-header {
  display: flex;
  align-items: center;
  gap: 2.2rem;
  width: 100%;
  margin-bottom: 2.2rem;
}
.profile-photo-block {
  position: relative;
  width: 110px;
  height: 110px;
}
.profile-photo {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #800020;
  background: #f3f3f3;
  box-shadow: 0 2px 8px rgba(128,0,32,0.08);
}
.edit-photo-btn {
  position: absolute;
  bottom: -10px;
  right: -15px;
  background: #800020;
  color: #fff;
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(128,0,32,0.12);
  transition: background 0.2s;
}
.edit-photo-btn:hover {
  background: #a8324a;
}
.profile-info-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.profile-username-row {
  display: flex;
  align-items: center;
  gap: 0.7rem;
}
.profile-username {
  font-size: 1.25rem;
  font-weight: 700;
  color: #800020;
}
.edit-btn {
  background: #f3f3f3;
  color: #800020;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.1rem;
  cursor: pointer;
  transition: background 0.2s;
}
.edit-btn:hover {
  background: #f8d7da;
}
.profile-fullname {
  font-size: 1.1rem;
  font-weight: 500;
  color: #333;
}
.profile-bio {
  font-size: 1rem;
  color: #555;
  margin-top: 0.2rem;
  font-style: italic;
  min-height: 1.5rem;
}
.profile-tabs {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
  width: 100%;
  border-bottom: 2px solid #f0f0f0;
}
.profile-tab {
  background: none;
  border: none;
  color: #800020;
  font-size: 1.1rem;
  font-weight: 600;
  padding: 0.7rem 1.2rem 0.5rem 1.2rem;
  border-radius: 0;
  border-bottom: 3px solid transparent;
  cursor: pointer;
  transition: border-bottom 0.2s, color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.profile-tab.active {
  color: #fff;
  background: #800020;
  border-radius: 16px 16px 0 0;
  border-bottom: 3px solid #800020;
}
.profile-tab-content {
  width: 100%;
  min-height: 200px;
  background: #f8f9fa;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px rgba(128,0,32,0.04);
}
.modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal-content {
  background: #fff;
  border-radius: 12px;
  padding: 2rem 2.5rem;
  min-width: 320px;
  max-width: 95vw;
  box-shadow: 0 2px 16px rgba(128,0,32,0.12);
}
.form-group {
  margin-bottom: 1.2rem;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.form-group label {
  font-weight: 600;
  color: #800020;
  margin-bottom: 0.3rem;
}
.form-group input[type="text"],
.form-group textarea {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 0.5rem 0.8rem;
  font-size: 1rem;
  margin-bottom: 0.2rem;
}
.form-group input[type="file"] {
  margin-top: 0.3rem;
}
.profile-photo.preview {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-top: 0.5rem;
  border: 2px solid #800020;
}
.modal-actions {
  display: flex;
  gap: 1.2rem;
  justify-content: flex-end;
  margin-top: 1.2rem;
}
.save-btn {
  background: #800020;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0.5rem 1.2rem;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.save-btn:hover {
  background: #a8324a;
}
.cancel-btn {
  background: #f3f3f3;
  color: #800020;
  border: none;
  border-radius: 8px;
  padding: 0.5rem 1.2rem;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.cancel-btn:hover {
  background: #f8d7da;
}
.no-espai-propi {
  text-align: center;
  padding: 3rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin: 2rem auto;
  max-width: 600px;
}

.no-espai-propi i {
  font-size: 3rem;
  color: #800020;
  margin-bottom: 1rem;
}

.no-espai-propi h3 {
  color: #800020;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.no-espai-propi p {
  color: #666;
  margin-bottom: 2rem;
}

.add-espai-btn {
  background: #800020;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  font-size: 1rem;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
}

.add-espai-btn:hover {
  background: #a8324a;
  transform: translateY(-2px);
}

.add-espai-btn i {
  font-size: 1.2rem;
  margin: 0;
}

.loading, .error {
  text-align: center;
  padding: 2rem;
  color: #800020;
  font-size: 1.1rem;
}

.loading i, .error i {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.espais-propios-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 1rem;
}

.espai-propi-item {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin-bottom: 1.5rem;
  overflow: hidden;
}

.espai-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-top: 1px solid #eee;
}

.edit-btn, .delete-btn {
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-btn {
  background: #4CAF50;
  color: white;
  border: none;
}

.edit-btn:hover {
  background: #388e3c;
}

.delete-btn {
  background: #dc3545;
  color: white;
  border: none;
}

.delete-btn:hover {
  background: #c82333;
}

.add-espai-btn {
  width: 100%;
  margin-top: 1rem;
  background: #800020;
  color: white;
  border: none;
  padding: 1rem;
  border-radius: 8px;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
}

.add-espai-btn:hover {
  background: #a8324a;
  transform: translateY(-2px);
}

/* 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);
}
</style>
