<script setup>

const router = useRouter();

const loading = ref(true);
const userData = useCookie('userData').value;
const candidaturas = ref([])
const vagas = ref([])
const totalVagas = ref(0)
const searchVagaText = ref('')

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

    const response = await $api(`/vagas/candidaturasAll/${userData.id}`, {
        method: 'GET'
    }).catch(error => {
        console.error('Erro ao buscar candidaturas:', error, error.response)
    });

    console.log('Candidaturas:', response)

    candidaturas.value = response;
    vagas.value = response.map(candidatura => candidatura.vaga);
    totalVagas.value = candidaturas.value.length;
    loading.value = false;
}

const windowsWidth = window.innerWidth
const isMobile = ref(false)

onMounted(async () => {
    await getCandidaturas()

    if (windowsWidth < 768) {
        isMobile.value = true
    }
})

const truncateTitle = (title) => {
    if (!title) return "";
    return title?.length > 31 ? title.substring(0, 31) + "..." : title;
};

const formatDate = (date) => {
    return new Date(date).toLocaleDateString("pt-BR");
};

const detalhesVaga = (id) => {
    console.log('Detalhes da vaga:', id)
    router.push({ name: "DetalhesVaga", params: { slug: id } });
};
//
</script>

<template>
    <VCard class="mb-6" v-if="isMobile">
        <VCardText class="py-5">
            <VBtn variant="elevated" class="w-100" color="primary" @click="router.push('/meu-curriculo')"
                :disabled="loading">
                Ver Meu Currículo
                <VIcon icon="tabler-chevron-right" class="ml-2" />
            </VBtn>

        </VCardText>
    </VCard>

    <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-2 pl-0">
                    <h3>Minhas Candidaturas</h3>
                    <p class="mb-0">{{ loading ? '' : `Você possuí ${totalVagas} candidaturas.` }}</p>

                </v-col>

                <v-col class="v-col-12 v-col-md-6 pl-0">
                    <v-text-field class="select-filter-events" v-model="searchVagaText"
                        label="Busque suas candidaturas..." :disabled="loading" clearable
                        prepend-inner-icon="tabler-search" />
                </v-col>

                <v-col class="v-col-12 v-col-md-4 pl-0 d-flex flex-row gap-2">
                    <VBtn variant="elevated" :class="`select-filter-events ${isMobile ? 'w-100' : 'w-50'}`" color="primary" @click="getCandidaturas"
                        :disabled="loading">
                        Buscar
                    </VBtn>
                    <VBtn variant="tonal" class="select-filter-events" color="primary"
                        @click="router.push('/meu-curriculo')" :disabled="loading" v-if="!isMobile">
                        Ver Currículo
                        <VIcon icon="tabler-chevron-right" class="ml-2" />
                    </VBtn>
                </v-col>

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

    <p v-if="loading">Carregando...</p>

    <VCard v-else v-for="vaga in vagas" :key="vaga.id" @click="detalhesVaga(vaga.slug)" max-width="400px">
        <VCardText>
            <VRow>

                <VCol cols="7" class="pb-0">
                    <div class="d-flex flex-row align-center">
                        <VImg :src="vaga.logo" width="40" />
                        <p class="mb-0 ml-2"><span class="text-caption font-weight-bold">Empresa: </span><br>
                            {{
                                vaga.empresa
                            }}</p>
                    </div>
                </VCol>

                <VCol cols="5" class="pb-0">
                    <p class="mb-0 ml-2"><span class="text-caption font-weight-bold">Data da Candidatura: </span><br>
                        {{ formatDate(candidaturas?.find(candidatura => candidatura.vaga.id === vaga.id).createdAt) }}
                    </p>
                </VCol>

                <VCol cols="12">
                    <VDivider class="mb-2" />

                    <p class="mb-0"><span class="text-caption font-weight-bold">Função: </span><br>{{ vaga.funcao }}</p>

                    <VDivider class="mt-2" />
                </VCol>

                <VCol cols="4" class="pt-0">
                    <p class="mb-0"><span class="text-caption font-weight-bold">Local: </span><br>{{
                        vaga.addressVaga?.city
                        + '/' + vaga.addressVaga?.state }}</p>
                </VCol>

                <VCol cols="4" class="pt-0">
                    <p class="mb-0"><span class="text-caption font-weight-bold">Tipo: </span><br>{{
                        vaga.formaContrato
                        }}</p>

                </VCol>

                <VCol cols="4" class="pt-0">
                    <p class="mb-0"><span class="text-caption font-weight-bold">Contrato: </span><br>{{ vaga.tipoVaga }}
                    </p>
                </VCol>

                <VCol cols="12" class="pt-0">
                    <VDivider class="mb-2" />

                    <p class="mb-0">
                        <span class="text-caption font-weight-bold">Status da Candidatura: </span><br>
                        <span class="text-error"
                            v-if="candidaturas?.find(candidatura => candidatura.vaga.id === vaga.id).reprovado">Reprovado</span>
                        <span class="text-success font-weight-bold"
                            v-else-if="candidaturas?.find(candidatura => candidatura.vaga.id === vaga.id).contratado">Aprovado</span>
                        <span class="text-success"
                            v-else-if="candidaturas?.find(candidatura => candidatura.vaga.id === vaga.id).entrevista">
                            Chamado para Entrevista
                            {{ candidaturas?.find(candidatura => candidatura.vaga.id === vaga.id).entrevistaData ?
                                'em ' + new Date(candidaturas?.find(candidatura => candidatura.vaga.id ===
                                    vaga.id).entrevistaData).toLocaleDateString("pt-BR") : '' }}
                        </span>
                        <span class="text-warning" v-else>Em análise</span>
                    </p>

                </VCol>

                <VCol cols="12">
                    <VBtn color="primary" class="mt-1 w-100" @click="router.push(`/vagas/${vaga.id}`)">
                        <VIcon icon="tabler-eye" class="mr-2" /> Ver vaga
                    </VBtn>
                </VCol>

            </VRow>
        </VCardText>
    </VCard>

    <div v-if="vagas?.length === 0 && !loading">
        <p>Você não possuí candidaturas</p>
        <VBtn @click="router.push('/vagas')" color="primary">
            <VIcon icon="tabler-briefcase" class="mr-2" />
            Veja as vagas disponíveis
        </VBtn>
    </div>
</template>

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

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