<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { dashIfEmpty, toCurrency, toDate } from 'src/filters';
import { useQuasar } from 'quasar';

import VnPaginate from 'src/components/ui/VnPaginate.vue';
import ModalCloseContract from 'src/pages/Customer/components/ModalCloseContract.vue';
import CustomerCreditContractsCreate from '../components/CustomerCreditContractsCreate.vue';
import VnLv from 'src/components/ui/VnLv.vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const quasar = useQuasar();

const vnPaginateRef = ref(null);
const showQPageSticky = ref(true);
const showForm = ref();

const filter = {
    order: 'finished ASC, started DESC',
    include: [
        {
            relation: 'insurances',
            scope: {
                fields: ['id', 'credit', 'created', 'grade'],
                order: 'created DESC',
                limit: 2,
            },
        },
    ],
    where: { client: `${route.params.id}` },
};

const fetch = (data) => {
    data.forEach((element) => {
        if (!element.finished) {
            showQPageSticky.value = false;
        }
    });
};

const openDialog = (item) => {
    quasar.dialog({
        component: ModalCloseContract,
        componentProps: {
            id: item.id,
            promise: async () => {
                await updateData();
                showQPageSticky.value = true;
            },
        },
    });
};

const openViewCredit = (credit) => {
    router.push({
        name: 'CustomerCreditContractsInsurance',
        params: {
            creditId: credit.id,
        },
    });
};

const updateData = async () => {
    await vnPaginateRef.value?.fetch();
};
</script>

<template>
    <section class="row justify-center">
        <QCard class="q-pa-lg" style="width: 70%">
            <VnPaginate
                :user-filter="filter"
                @on-fetch="fetch"
                auto-load
                data-key="CustomerCreditContracts"
                order="id DESC"
                ref="vnPaginateRef"
                url="CreditClassifications"
            >
                <template #body="{ rows }">
                    <div v-if="rows.length" class="q-gutter-y-md">
                        <QCard
                            v-for="(item, index) in rows"
                            :key="index"
                            :class="{ disabled: item.finished }"
                        >
                            <QCardSection
                                class="full-width"
                                :class="{ 'row justify-between': $q.screen.gt.md }"
                            >
                                <div class="width-state row no-wrap">
                                    <QIcon
                                        :style="{
                                            visibility: item.finished
                                                ? 'hidden'
                                                : 'visible',
                                        }"
                                        @click.stop="openDialog(item)"
                                        color="primary"
                                        name="lock"
                                        data-cy="closeBtn"
                                        size="md"
                                        class="fill-icon q-px-md"
                                    >
                                        <QTooltip>{{ t('Close contract') }}</QTooltip>
                                    </QIcon>

                                    <div class="column">
                                        <VnLv
                                            :label="t('Since')"
                                            :value="toDate(item.started)"
                                        />
                                        <VnLv
                                            :label="t('To')"
                                            :value="toDate(item.finished)"
                                        />
                                    </div>
                                </div>

                                <QSeparator vertical />

                                <div class="column width-data">
                                    <div
                                        class="column"
                                        v-if="item?.insurances.length"
                                        v-for="insurance in item.insurances"
                                        :key="insurance.id"
                                    >
                                        <div
                                            :class="{
                                                'row q-gutter-x-md': $q.screen.gt.sm,
                                            }"
                                            class="q-mb-sm"
                                        >
                                            <VnLv
                                                :label="t('Credit')"
                                                :value="toCurrency(insurance.credit)"
                                            />
                                            <VnLv
                                                :label="t('Grade')"
                                                :value="dashIfEmpty(insurance.grade)"
                                            />
                                            <VnLv
                                                :label="t('Date')"
                                                :value="toDate(insurance.created)"
                                            />
                                        </div>
                                    </div>
                                </div>
                                <QBtn
                                    @click.stop="openViewCredit(item)"
                                    icon="preview"
                                    size="md"
                                    :title="t('View credits')"
                                    data-cy="viewBtn"
                                    color="primary"
                                    flat
                                />
                            </QCardSection>
                        </QCard>
                    </div>
                    <h5 class="flex justify-center color-vn-label" v-else>
                        {{ t('globals.noResults') }}
                    </h5>
                </template>
            </VnPaginate>
        </QCard>
    </section>

    <QPageSticky :offset="[18, 18]" v-if="showQPageSticky">
        <QBtn
            data-cy="createBtn"
            @click.stop="showForm = !showForm"
            color="primary"
            fab
            icon="add"
            v-shortcut="'+'"
        />
        <QTooltip>
            {{ t('New contract') }}
        </QTooltip>
    </QPageSticky>

    <QDialog v-model="showForm">
        <CustomerCreditContractsCreate @on-data-saved="updateData()" />
    </QDialog>
</template>

<style lang="scss" scoped>
.width-state {
    width: 30%;
}
.width-data {
    width: 50%;
}
::v-deep(.label) {
    margin-right: 5px;
}
::v-deep(.label)::after {
    content: ':';
    color: var(--vn-label-color);
}
</style>

<i18n>
es:
    Close contract: Cerrar contrato
    Since: Desde
    To: Hasta
    Credit: Crédito
    Grade: Grade
    Date: Fecha
    View credits: Ver créditos
    Created: Fecha creación
    New contract: Nuevo contrato
</i18n>
