<template>
    <div class="flex items-center justify-start gap-10">
        <Icon @click="router.push('/')" name="gg:arrow-left-o" size="44" class="cursor-pointer text-primary-500"/>
        <h1 class="text-3xl font-bold uppercase text-primary-500">listes des réceptions en attente</h1>
    </div>

    <div class="px-[86px]">
        <div class="mt-6 mb-16">
            <UiDataTable
                v-model:page="page"
                v-model:per-page="perPage"
                :columns="columns"
                :items="items"
                :total-items="totalItems"
                :loading="loading"
                :show-actions="auth.isAdmin"
                row-clickable
                @row-click="goToReception"
            >
                <template #header-receptionDate>
                    <UiDateMaskedInput v-model="receptionDateFilter" placeholder="Date" size="compact" />
                </template>
                <template #header-supplier.name>
                    <UiTextInput
                        v-model="filters['supplier.name']"
                        placeholder="Fournisseur"
                        size="compact"
                    />
                </template>
                <template #header-address.fullAddress>
                    <UiTextInput :model-value="''" placeholder="Adresse" size="compact" disabled />
                </template>
                <template #header-receptionType.label>
                    <UiSelect
                        v-model="filters['receptionType.id']"
                        placeholder="Type réception"
                        :options="receptionTypeOptions"
                        size="compact"
                    />
                </template>
                <template #header-carrier.name>
                    <UiTextInput
                        v-model="filters['carrier.name']"
                        placeholder="Transporteur"
                        size="compact"
                    />
                </template>
                <template #header-licensePlate>
                    <UiTextInput
                        v-model="filters['licensePlate']"
                        placeholder="Immatriculation"
                        size="compact"
                    />
                </template>
                <template #header-actions>
                    <UiTextInput :model-value="''" placeholder="Actions" size="compact" disabled />
                </template>
                <template #cell-receptionDate="{ item }">
                    {{ formatDate(item.receptionDate) }}
                </template>
                <template #actions="{ item }">
                    <Icon
                        name="mdi:delete-outline"
                        size="24"
                        class="cursor-pointer text-red-500 hover:text-red-700"
                        @click="confirmDelete(item)"
                    />
                </template>
            </UiDataTable>
        </div>
    </div>
</template>

<script setup lang="ts">
useHead({ title: 'Réceptions en attente' })

import type { ReceptionData } from '~/services/dto/reception-data'
import type { ReceptionTypeData } from '~/services/dto/reception-type-data'
import { deleteReception } from '~/services/reception'
import { getReceptionTypeList } from '~/services/reception-type'
import { useAuthStore } from '~/stores/auth'
import { useDataTableServerState } from '~/composables/useDataTableServerState'

const router = useRouter()
const auth = useAuthStore()
const receptionTypes = ref<ReceptionTypeData[]>([])

const receptionTypeOptions = computed(() =>
    receptionTypes.value.map(rt => ({ value: rt.id, label: rt.label }))
)

const { items, totalItems, page, perPage, filters, loading, reload } =
    useDataTableServerState<ReceptionData>(
        'receptions',
        {
            isValid: false,
            'supplier.name': '',
            'carrier.name': '',
            'licensePlate': '',
            'receptionType.id': '',
            'receptionDate[after]': '',
            'receptionDate[strictly_before]': ''
        },
        { initialPerPage: 10 }
    )

const addOneDay = (dateString: string): string => {
    const [year, month, day] = dateString.split('-').map(Number)
    const next = new Date(Date.UTC(year, month - 1, day + 1))
    return next.toISOString().slice(0, 10)
}

const receptionDateFilter = computed<string>({
    get: () => (filters.value['receptionDate[after]'] as string) ?? '',
    set: (value: string) => {
        if (!value) {
            filters.value['receptionDate[after]'] = ''
            filters.value['receptionDate[strictly_before]'] = ''
            return
        }
        filters.value['receptionDate[after]'] = value
        filters.value['receptionDate[strictly_before]'] = addOneDay(value)
    }
})

const columns = [
    { key: 'receptionDate', label: 'Date', width: '120px' },
    { key: 'supplier.name', label: 'Fournisseur', width: '1.5fr' },
    { key: 'address.fullAddress', label: 'Adresse', width: '2fr' },
    { key: 'receptionType.label', label: 'Type réception', width: '1.1fr' },
    { key: 'carrier.name', label: 'Transporteur' },
    { key: 'licensePlate', label: 'Immatriculation', width: '110px' }
]

const formatDate = (date: string | null) => {
    if (!date) return '—'
    const d = new Date(date.replace(' ', 'T'))
    if (isNaN(d.getTime())) return date
    return d.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    })
}

const goToReception = (reception: ReceptionData) => {
    router.push(`/reception/${reception.id}`)
}

const confirmDelete = async (reception: ReceptionData) => {
    const confirmed = window.confirm(
        `Êtes-vous sûr de vouloir supprimer la réception ${reception.identificationNumber ?? `#${reception.id}`} ? Toutes les données liées seront supprimées.`
    )
    if (!confirmed) return

    await deleteReception(reception.id)
    reload()
}

onMounted(async () => {
    receptionTypes.value = await getReceptionTypeList()
    reload()
})
</script>
