<script setup>
  import moment from 'moment'
  import CardEvent from "./card-event.vue"

  const userData = useCookie('userData').value
  const loading = ref(false)
  const eventos = ref([])
  const totalEventos = ref(0)
  const searchQuery = ref('')

  const { setAlert } = useAlert()

  const stateFilter = ref(userData?.endereco?.state ?? 'RJ')

  const { width: windowWidth } = useWindowSize();

  const isMobile = ref(false)

  isMobile.value = windowWidth.value < 768
  onMounted(() => {
    getEvents()
  })

  const getEvents = async () => {
    loading.value = true;

    try {
      const response = await $api('/events/getAll/u', {
        method: 'GET',
        query: {
          q: searchQuery.value,
          userData: JSON.stringify(userData),
          isMyTickets: true
        }
      })

      if (!response) return

      console.log('Eventos:', response)

      eventos.value = response.eventos;
      totalEventos.value = eventos.value.reduce((acc, evento) => acc + evento.comprasEvento.length, 0);
    } catch (error) {
      console.error('Erro ao buscar eventos:', error, error.response)

      eventos.value = [];
      totalEventos.value = 0;
    }
    loading.value = false;
  }

  const helpView = ref(false)
  const viewCancelarIngresso = ref(false)
  const eventHelp = ref(null)

  const handleOpenHelp = (event) => {
    console.log('Evento:', event)
    eventHelp.value = event
    helpView.value = true
  }

  const contatoPromotor = () => {
    if (!eventHelp.value || !eventHelp.value?.promotorEvento?.phone) return
    let message = `Olá, estou com dúvidas sobre o evento ${eventHelp.value.title} no AkkiPerto.`
    message = encodeURI(message)
    window.open(`https://api.whatsapp.com/send?phone=55${eventHelp.value.promotorEvento.phone.replace(/\D/g, '')}&text=${message}`, '_blank')
  }

  const contatoAkkiPerto = () => {
    window.open(`https://api.whatsapp.com/send?phone=5522997259567&text=Olá, estou com dúvidas sobre os ingressos que comprei do evento ${eventHelp.value.title} no AkkiPerto.`, '_blank')
  }

  const cancelarIngresso = async (item) => {
    try {
      const res = await $api('/events/refund-ticket/' + item.id, {
        method: 'PUT',
      })

      if (!res) return

      console.log('Res cancelar', res)

      setAlert('Ingresso cancelado com sucesso', 'success', 'tabler-alert-triangle', 6000);
      getEvents()
    } catch (error) {
      console.error('Erro ao cancelar ingresso', error, error.response)
      setAlert(error?.response?._data?.message || 'Erro ao cancelar ingresso', 'error', 'tabler-alert-triangle', 6000);
    }
  }

  const formatValue = (value) => {
    if (!value) return 'R$ 0,00'
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value)
  }

  const calculateDiff7Dias = (data) => {
    const dateNow = moment()
    const dateEvent = moment(data)

    const diffTime = Math.abs(moment(dateEvent).valueOf() - moment(dateNow).valueOf())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    return diffDays <= 7
  }
</script>

<template>

  <VCard class="mb-6">
    <VCardText class="py-5">
      <v-row class="d-flex align-center py-0 pl-0">
        <v-col class="v-col-12 v-col-md-3">
          <h3>Meus Ingresos</h3>
          <p class="mb-0">{{ loading ? '' : `Você possuí ${totalEventos} ingressos.` }}</p>

        </v-col>

        <v-col class="v-col-12 v-col-md-7 pl-0">
          <v-text-field class="select-filter-eventos" v-model="searchQuery" label="Busque seus ingressos..."
            :disabled="loading" clearable prepend-inner-icon="tabler-search" />
        </v-col>

        <v-col class="v-col-12 v-col-md-2 pl-0">
          <VBtn variant="elevated" class="select-filter-eventos w-100" color="primary" @click="getEvents"
            :loading="loading">
            Buscar
          </VBtn>
        </v-col>

      </v-row>
    </VCardText>
  </VCard>

  <template v-if="loading">
    <v-row>
      <div class="v-col-xl-3 v-col-lg-3 v-col-md-4 v-col-sm" v-for="index in 6" :key="index">
        <VSkeletonLoader :elevation="5" type="image, article" />
      </div>
    </v-row>
  </template>
  <template v-else>
    <v-row>

      <template v-if="eventos && eventos.length == 0">
        <div class="text-center text-primary v-col-12 mt-15">
          <VIcon icon="tabler-mood-sad" class="text-9xl" />
          <div class="text-h4 text-primary mt-3">Você não possuí ingressos.</div>

          <div class="text-h6 text-dark font-weight-light" v-if="!searchQuery">Os seus ingressos podem demorar
            alguns minutos para aparecerem aqui. <br>Veja os eventos perto de você e garanta agora mesmo o seu ingresso!
          </div>
          <div class="text-h6 text-dark font-weight-light" v-if="searchQuery">Revise os dados e faça a busca
            novamente</div>


          <v-btn class="mt-8" variant="elevated" @click="router.push('/eventos')" v-if="!searchQuery">
            Ver eventos
          </v-btn>

          <v-btn class="mt-8" variant="elevated" @click="searchQuery = ''" v-if="searchQuery">
            Limpar busca
          </v-btn>
        </div>
      </template>

      <template v-else>
        <div class="v-col v-col-12 v-col-md-4" v-for="(event, index) in eventos" :key="index" :class="isMobile ? 'mb-4 mx-auto' : ''">
          <CardEvent :event="event" :isMyTicketsPage="true" @openHelp="handleOpenHelp" />
        </div>

        <VDialog v-model="helpView" max-width="600" @update:model-value="viewCancelarIngresso = false">
          <VCard v-if="eventHelp">
            <VCardText>
              <p class="mb-2 text-h5 text-center font-weight-medium w-100 position-relative">
                <VIcon icon="tabler-help" class="mr-1" />
                {{ !viewCancelarIngresso ? "Ajuda" : "Cancelar Ingresso" }}

                <VIcon icon="tabler-x" class="position-absolute cursor-pointer" style="right: 10px; top: 0px;"
                  @click="helpView = false; viewCancelarIngresso = false" />

              </p>

              <p class="mb-2 text-center" v-if="viewCancelarIngresso">
                Escolha o ingresso que deseja cancelar do evento <strong>{{ eventHelp.title }}</strong>
              </p>

              <p class="mb-3 text-center" v-else>
                Ajuda com o evento <strong>{{ eventHelp.title }}</strong>
              </p>

              <div v-if="viewCancelarIngresso">
                <VList>
                  <template v-for="(item, index) in eventHelp.comprasEvento" :key="index">
                    <VListItem @click="cancelarIngresso(item)" v-if="calculateDiff7Dias(item.pagoDate)">
                      <div class="d-flex flex-row gap-2">

                        <VIcon icon="tabler-ticket" size="20" class="mr-2" />
                        <p class="mb-0"><strong>N° #{{ item.numberTicket }}</strong></p>
                        <p class="mb-0">- {{ item.dadosIngresso?.name }}</p>
                        <p class="mb-0">- {{ formatValue(item.dadosIngresso?.buyData?.total) }}</p>

                      </div>
                    </VListItem>
                  </template>
                </VList>
              </div>

              <template v-if="!viewCancelarIngresso">
                <VBtn class="mt-3 w-100" color="primary" variant="outlined" style="height: 50px;"
                  @click="contatoPromotor()">
                  <VIcon icon="tabler-user" class="mr-1" />
                  <span class="text-none">Entrar em contato com o promotor</span>
                </VBtn>
                <VBtn class="mt-3 w-100" color="primary" variant="tonal" style="height: 50px;"
                  @click="contatoAkkiPerto()">
                  <VIcon icon="tabler-message" class="mr-1" />
                  <span class="text-none">Falar com o AkkiPerto</span>
                </VBtn>
                <VBtn class="mt-3 w-100" color="error" variant="tonal" style="height: 50px;"
                  @click="viewCancelarIngresso = true">
                  <VIcon icon="tabler-circle-x" class="mr-1" />
                  <span class="text-none">Cancelar Compra</span>
                </VBtn>
              </template>

              <template v-else>
                <VBtn class="mt-3 w-100" color="primary" variant="outlined" style="height: 50px;"
                  @click="helpView = false; viewCancelarIngresso = false">
                  <VIcon icon="tabler-x" class="mr-1" />
                  <span class="text-none">Fechar</span>
                </VBtn>
              </template>
            </VCardText>
          </VCard>
        </VDialog>
      </template>

    </v-row>
  </template>

</template>
<style>
  .select-filter-eventos {
    height: 60px !important;
    align-items: center;
  }

  .select-filter-eventos .v-field__field {
    height: 60px !important;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
  }
</style>