<template>
    <NuxtLayout :name="device" :config="config">
        <main class="seller-products">
            <aside v-if="device == 'desktop'">
                <PanelSellerProfile />
                <PanelSellerScore />
            </aside>
            <DataTable :value="products" :responsiveLayout="rl">
                <template #header>
                    <div>
                        <IconField>
                            <InputText v-model="form.q" :placeholder="$t('search')" @keypress.enter="filter()" />
                            <InputIcon class="isax isax-search-normal-1" />
                        </IconField>
                        <Dropdown v-model="form.category" :placeholder="$t('selectCategory')" showClear filter
                            :options="categories.items" optionLabel="name" optionGroupLabel="name"
                            optionGroupChildren="sub" optionValue="_id" @change="filter()">
                            <template #dropdownicon>
                                <i class="isax isax-arrow-bottom" />
                            </template>
                        </Dropdown>
                    </div>
                    <span> {{ $t('allProducts') }}: {{ products.length }}</span>
                </template>
                <Column v-for="(col, i) in columns[device]" :key="i" v-bind="col">
                    <template #body="{ data, field }">
                        <span>{{ data[field] || field(data) }}</span>
                    </template>
                </Column>
                <Column>
                    <template #body="{ data, index }">
                        <router-link :to="`/panel/seller/new-product?id=${data.id}`">
                            <Button icon="isax isax-edit" rounded link severity="secondary" />
                        </router-link>
                        <Button icon="isax isax-trash" rounded link severity="secondary" :loading="data.removing"
                            @click="remove(data, index)" />
                        <Button v-if="device == 'mobile'" :label="$t('showDetails')" icon="isax isax-arrow-left-2"
                            rounded link severity="secondary" />
                    </template>
                </Column>

                <template #empty>
                    <p>{{ $t('notFound') }}</p>
                </template>
            </DataTable>
        </main>
    </NuxtLayout>
</template>

<script setup>
const { device, t, toast } = inject('service')
const config = reactive({
    desktop: { toolbar: true, seller: true },
    mobile: { header: { back: true, toolbar: true, title: t('userPanel') } },
})
const router = useRouter()
const categories = useCategoriesStore()

const rl = computed(() => device.value == 'mobile' ? 'stack' : '')
const { meta, query, path } = useRoute()

const products = ref([])

const columns = reactive({
    desktop: [
        { header: t('row'), field: (p) => products.value.indexOf(p) + 1 },
        { header: t('code'), field: 'uid' },
        { header: t('productTitle'), field: 'title' },
        { header: t('salesPrice'), field: (p) => numberFormat(p.price) },
        { header: t('inventory'), field: (p) => numberFormat(p.stockQuantity) },
        { header: t('status'), field: (p) => [t('pending'), t('confirmed'), t('rejected')][p.status] },
    ],
    mobile: [
        { field: 'title' },
    ]
})

const { status, data, error } = await useFetch('/api/shop/products', {
    headers: {
        Authorization: useCookie('token')
    },
    params: query
})

if (status.value == 'success') {
    products.value = data.value.shop.products
    provide('data', data.value)
}
else throw createError(error.value)

const form = reactive(Object.assign({}, query))
const filter = () => {
    Object.keys(form).forEach((key) => {
        if (!form[key]) delete form[key]
    })
    router.push({ path, query: form })
}

const remove = async (data, index) => {
    data.removing = true
    const { status, error } = await useFetch('/api/products/' + data.id, {
        headers: {
            Authorization: useCookie('token')
        },
        method: "delete", body: {}
    })
    data.removing = false

    if (status.value == 'success') {
        products.value.splite(index, 1)
    } else toast.add({
        life: 3000, severity: 'error', summary: t('error'), detail: error.value.data.message
    })
}

const numberFormat = (number) =>
    new Intl.NumberFormat('fa-IR', { maximumSignificantDigits: 3 }).format(number)
</script>

<style lang="scss">
.seller-products {
    @apply container flex flex-col lg:flex-row pt-[1.9rem] pb-20 lg:pt-14 max-lg:px-6 gap-6;

    aside {
        @apply flex flex-col gap-3 lg:gap-5;
    }

    .p-datatable {
        @apply flex flex-col gap-4 lg:gap-11 rtl grow;

        .p-datatable-header {
            @apply flex max-lg:flex-col gap-9 lg:items-center bg-transparent p-0 border-none z-[1];

            &>div {
                @apply flex max-lg:flex-col gap-3 lg:gap-[1.1rem];

                .p-icon-field {
                    @apply z-0 flex items-center w-[21.4rem] h-[2.9rem] lg:w-[29.7rem] lg:h-[3.8rem] rounded-[0.6rem];
                    @apply bg-[#FAFAFA] lg:bg-[#F2F2F2] text-[#4C4C4C] lg:text-[#5D5D5D];
                    @apply text-sm lg:text-lg font-medium font-vazir;


                    input {
                        @apply rtl w-full h-full border-none bg-transparent shadow-none;
                    }
                }

                .p-dropdown {
                    @apply items-center w-[21.4rem] h-[2.9rem] lg:w-[18.3rem] lg:h-[3.8rem] bg-[#FAFAFA] lg:bg-[#F2F2F2] rounded-[0.6rem] border-none;
                    @apply z-[2] #{!important};

                    .p-dropdown-label {
                        @apply text-[#4C4C4C] lg:text-[#5D5D5D] text-xs lg:text-base font-medium font-vazir mt-3.5 lg:mt-1.5;
                    }

                    i {
                        @apply text-xl lg:text-2xl transition-transform;
                    }

                    &.p-overlay-open i {
                        @apply rotate-180;
                    }

                    .p-dropdown-clear-icon {
                        @apply left-12 right-auto;
                    }
                }

                &:has(.p-overlay-open)::after {
                    @apply content-['_'] inset-0 fixed bg-black/20 z-[1];
                }
            }

            &>span {
                @apply text-[#333333] text-sm lg:text-xl font-medium font-vazir mr-auto;
            }
        }

        .p-datatable-table {
            @apply border-separate border-spacing-y-[0.8rem] px-1;

            .p-datatable-thead {
                @apply w-full h-[3.1rem] max-lg:hidden;

                th {
                    @apply text-[#5D5D5D] text-base font-normal font-vazir bg-[#F2F2F2];
                    @apply first:rounded-r-[0.6rem] last:rounded-l-[0.6rem];
                }
            }

            .p-datatable-tbody {
                @apply lg:translate-y-1.5;

                tr {
                    @apply w-full rounded-[0.6rem] bg-transparent shadow-[0px_0px_6px_#0000001f];

                    td {
                        @apply text-[#333333] text-base font-normal font-vazir text-right;
                        @apply first:rounded-r-[0.6rem] last:rounded-l-[0.6rem] py-0 h-[3.8rem] last:text-left;

                        &:last-child:not([colspan]) {
                            @apply flex lg:justify-end gap-3 items-center;

                            .p-button {
                                @apply p-0 w-max h-max #{!important};

                                .p-button-icon {
                                    @apply text-lg lg:text-2xl text-[#333333];
                                }
                            }
                        }

                        &>span {
                            @apply max-lg:py-3 min-h-[3.8rem] flex items-center text-xs lg:text-base text-[#333333] font-vazir;
                        }

                        @media(max-width: 1024px) {
                            &>button:last-child {
                                @apply -m-3 mr-auto #{!important};

                                .p-button-label {
                                    @apply text-xs font-medium font-vazir whitespace-nowrap #{!important};
                                }

                                .p-button-icon {
                                    @apply mr-px text-[#47B556] #{!important};
                                }
                            }

                            &:first-child span {
                                @apply w-full border-b py-3;
                            }

                            .p-column-title {
                                @apply hidden #{!important};
                            }
                        }
                    }


                }

                .p-datatable-emptymessage p {
                    @apply lg:h-[3.8rem] flex justify-center items-center
                }

            }
        }
    }

}

body:has(.seller-products) {
    .p-dropdown-panel {
        @apply w-[18.3rem] h-[19rem] translate-y-3 pb-4 pt-[0.6rem] rounded-[0.6rem];

        .p-dropdown-header {
            @apply py-0 px-2.5;

            .p-dropdown-filter-container {
                @apply w-[17rem] h-[3.1rem];

                input {
                    @apply m-0 h-full rtl;
                }

                svg {
                    @apply hidden;
                }
            }
        }

        .p-dropdown-items-wrapper {
            @apply mt-3 ml-3;

            .p-dropdown-item-group {
                @apply text-[#47B556] text-xs font-medium font-vazir p-2.5;
            }

            .p-dropdown-item {
                @apply h-[2.4rem] px-2.5 text-[#333333] text-base font-medium font-vazir;
            }

            &::-webkit-scrollbar-thumb {
                @apply bg-[#47B556];
            }

            &::-webkit-scrollbar {
                @apply w-1;
            }
        }
    }
}
</style>