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

    const { setAlert } = useAlert()

    const userData = useCookie('userData').value

    const router = useRouter()

    const { width: windowWidth } = useWindowSize();
    const isMobile = ref(false)
    isMobile.value = windowWidth.value < 768

    const loading = ref(true)
    const eventos = ref([])
    const totalEventos = ref(0)
    const categorias = ref([])

    const searchQuery = ref('')
    const stateFilter = ref('RJ')
    const categoriaQuery = ref(null)
    const distanciaQuery = ref(null)
    const dataQuery = ref(null)
    const dataAteQuery = ref(null)
    const dates = ref([])
    const page = ref(1)
    const inputDataValue = ref('')

    const getEventos = async () => {
        try {
            const res = await $api('/events/getAll/u', {
                method: 'GET',
                query: {
                    page: page.value,
                    q: searchQuery.value,
                    estado: stateFilter.value,
                    categoria: categoriaQuery.value,
                    data: dataQuery.value,
                    dataAte: dataAteQuery.value,
                    distancia: distanciaQuery.value,
                    userData: JSON.stringify(userData),
                }
            })

            if (!res) return

            console.log('Eventos resss:', res)

            eventos.value = res.eventos
            totalEventos.value = res.totalEventos
        } catch (error) {
            console.error('Erro ao buscar eventos:', error, error.response)
            eventos.value = []
            totalEventos.value = 0
        }

        loading.value = false
    }

    const getCategorias = async () => {
        try {
            const res = await $api('/events/categorias', {
                method: 'GET',
            })

            if (!res) return

            console.log('res categorias', res)

            categorias.value = res
        } catch (error) {
            console.error('Erro ao buscar categorias', error, error.response)
            categorias.value = []
            //setAlert(error?.response?._data?.message || 'Erro ao buscar categorias', 'error', 'tabler-alert-triangle', 6000);
        }
    }

    getEventos()
    getCategorias()

    const estados = [
        { value: 'RJ', text: 'Macaé' },
    ]

    const distanceItens = [
        { value: 1, title: 'Até 1km' },
        { value: 5, title: 'Até 5km' },
        { value: 10, title: 'Até 10km' },
        { value: 20, title: 'Até 20km' },
        { value: 50, title: 'Até 50km' },
        { value: 100, title: '100km ou mais' },
    ]

    watch(() => dates.value, (newValue) => {
        console.log('dates', dates.value, newValue)

        if (!newValue || newValue?.length === 0) {
            if (!newValue) {
                dates.value = []
            }
            dataQuery.value = null
            dataAteQuery.value = null
            inputDataValue.value = ''
        } else {
            dataQuery.value = moment(newValue[0]).format('YYYY-MM-DD')
            dataAteQuery.value = moment(newValue[1]).format('YYYY-MM-DD')
            inputDataValue.value = moment(newValue[0]).format('DD/MM/YYYY') + ' - ' + moment(newValue[1]).format('DD/MM/YYYY')
        }

        getEventos()
    })

    const clearFilters = () => {
        searchQuery.value = ''
        categoriaQuery.value = null
        distanciaQuery.value = null
        dates.value = []

        getEventos()
    }

    const viewFilters = ref(false)

</script>
<template>
    <VCard class="mb-6">
        <VCardText class="py-5">
            <v-row class="d-flex align-center py-0">
                <v-col class="v-col-12 v-col-md-4">
                    <VSelect v-model="stateFilter" variant="outlined" :items="estados" item-title="text"
                        item-value="value" placeholder="Escolha o estado" @update:modelValue="getEventos"
                        :loading="loading" prepend-inner-icon="tabler-map-pin" class="select-filter-events" />
                </v-col>

                <v-col class="v-col-12 v-col-md-6">
                    <v-text-field class="select-filter-events" v-model="searchQuery"
                        label="Qual evento você quer buscar?" :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-events w-100" color="primary" @click="getEventos"
                        :disabled="loading">
                        Buscar
                    </VBtn>
                </v-col>

                <v-col cols="12" :class="isMobile ? 'pt-0 pl-0' : ''">

                    <VBtn color="primary" variant="tonal" @click="viewFilters = !viewFilters"
                        class="w-100 mt-0 mb-2" v-if="isMobile">
                        {{ viewFilters ? 'Fechar Filtros' : 'Ver Filtros' }}
                        <VIcon :icon="viewFilters ? 'tabler-chevron-up' : 'tabler-chevron-down'" class="ml-2" />
                    </VBtn>

                    <v-fade-transition>
                        <VRow class="ma-0 align-center" v-if="!isMobile || viewFilters">
                            <VCol :cols="!isMobile ? 2 : 12" class="pa-md-0 pb-0">
                                <p :class="!isMobile ? 'mb-0' : 'mb-2'">
                                    Filtrar por:
                                </p>
                            </VCol>
                            <VCol :cols="!isMobile ? 3 : 12" class="pa-md-0 pt-0">
                                <VSelect v-model="categoriaQuery" :items="categorias" item-title="name" item-value="id"
                                    label="Categoria" clearable @update:modelValue="getEventos" />
                            </VCol>
                            <VCol :cols="!isMobile ? 3 : 12" class="py-md-0 pr-md-0">
                                <VueDatePicker v-model="dates" :multi-calendars="!isMobile ? 2 : false" :range="true" locale="pt-br" auto-apply
                                    placeholder="Data" teleport :time="false" :enable-time-picker="false" position="center">
                                    <template
                                        #dp-input="{ value, onInput, onEnter, onTab, onClear, onBlur, onKeypress, onPaste, isMenuOpen }">
                                        <VTextField v-model="inputDataValue" placeholder="Data" readonly
                                            class="input-data-filtro" append-inner-icon="tabler-chevron-down" />
                                    </template>
                                </VueDatePicker>
                            </VCol>
                            <VCol :cols="!isMobile ? 3 : 12" class="py-md-0 pr-md-0" v-if="userData && userData.endereco.geolocation">
                                <VSelect v-model="distanciaQuery" :items="distanceItens" item-title="title"
                                    item-value="value" label="Distância" clearable @update:modelValue="getEventos" />
                            </VCol>
                        </VRow>
                    </v-fade-transition>
                </v-col>

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


    <div class="d-flex flex-wrap gap-6 justify-center" v-if="!loading && eventos.length > 0">
        <CardEvent v-for="evento in eventos" :key="evento.uuid" :event="evento" :isMyTicketsPage="false" />
    </div>

    <VPagination v-model="page" :length="Math.ceil(totalEventos / 20)" @update:modelValue="getEventos" class="mt-10"
        v-if="!loading && eventos.length > 0 && totalEventos > 20" />

    <div class="d-flex flex-wrap gap-5 justify-center" v-if="loading">
        <v-skeleton-loader type="card" v-for="n in 8" :key="n" style="width: 300px;" />
    </div>

    <div v-if="!loading && eventos.length == 0" class="d-flex flex-column align-center justify-center w-100">
        <VIcon icon="tabler-square-rounded-x-filled" size="60" color="primary" />
        <p class="mt-3 text-h5" v-if="searchQuery || categoriaQuery || dates.length || distanciaQuery">
            Ops! Nenhum evento foi encontrado com os filtros aplicados.
        </p>
        <VBtn color="primary" variant="tonal" @click="clearFilters" class="mt-2"
            v-if="searchQuery || categoriaQuery || dates.length || distanciaQuery">
            Limpar Filtros
        </VBtn>
        <p class="mt-3 text-h5" v-else>Nenhum evento foi encontrado!</p>
    </div>

</template>

<style>
    * {
        --dp-primary-color: var(--color-akkiperto);
    }

    .input-data-filtro,
    .input-data-filtro input,
    .input-data-filtro .v-field__field {
        max-height: 40px !important;
        min-height: 40px !important;
        padding-bottom: 0 !important;
        padding-top: 0 !important;
    }
</style>