<template>
    <form :class="{ submitted }" @submit.prevent="validate">
        <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 mb-16">
            <h1 class="font-bold text-5xl uppercase col-start-1 row-start-1 text-primary-500">Réception</h1>
            <UiSelect
                id="reception-user"
                v-model="form.userId"
                label="Nom de l'utilisateur"
                :options="users.map((user) => ({
                    value: String(user.id),
                    label: user.username
                }))"
                :loading="isLoadingUsers"
                wrapper-class="col-start-1 row-start-2"
                required
            />
            <UiDateInput
                id="reception-date"
                v-model="form.receptionDate"
                label="Date de réception"
                wrapper-class="col-start-1 row-start-3"
                required
            />
            <UiSelect
                id="reception-type"
                v-model="form.receptionTypeId"
                label="Type de réception"
                :options="receptionTypes.map((type) => ({
                    value: String(type.id),
                    label: type.label
                }))"
                wrapper-class="col-start-1 row-start-4"
                required
            />
            <UiSelect
                id="reception-supplier"
                v-model="form.supplierId"
                label="Fournisseur"
                :options="suppliers.map((supplier) => ({
                    value: String(supplier.id),
                    label: supplier.name
                }))"
                :loading="isLoadingSuppliers"
                wrapper-class="col-start-1 row-start-5"
                required
            />
            <UiSelect
                id="reception-address"
                v-model="form.addressId"
                label="Adresse"
                :options="addressOptions"
                :disabled="isLoadingSuppliers || ownerAddresses.length === 0"
                wrapper-class="col-start-2 row-start-1"
                required
            />
            <UiSelect
                id="reception-truck"
                v-model="form.truckId"
                label="Camion"
                :options="trucks.map((truck) => ({
                    value: String(truck.id),
                    label: truck.name
                }))"
                :loading="isLoadingTrucks"
                wrapper-class="col-start-2 row-start-2"
                required
            />
            <UiSelect
                id="reception-carrier"
                v-model="form.carrierId"
                label="Transporteur"
                :options="carriers.map((carrier) => ({
                    value: String(carrier.id),
                    label: carrier.name
                }))"
                :loading="isLoadingCarriers"
                select-class="h-[34px]"
                wrapper-class="col-start-2 row-start-3"
                required
            />
            <div v-if="!isLiotCarrier" class="col-start-2 row-start-4">
                <UiLicensePlateInput
                    v-model="form.licensePlate"
                    v-model:allowAny="allowAnyLicensePlate"
                    required
                />
            </div>
            <UiSelect
                v-if="isLiotCarrier"
                id="reception-vehicle"
                v-model="form.vehicleId"
                label="Immatriculation"
                :options="filteredVehicles.map((vehicle) => ({
                    value: String(vehicle.id),
                    label: vehicle.plate
                }))"
                :loading="isLoadingVehicles"
                :disabled="isLoadingVehicles || filteredVehicles.length === 0"
                wrapper-class="col-start-2 row-start-4 h-[64px]"
                required
            />
            <UiSelect
                id="reception-driver"
                v-model="form.driverId"
                label="Nom du chauffeur si LIOT"
                :options="filteredDrivers.map((driver) => ({
                    value: String(driver.id),
                    label: driver.name
                }))"
                :loading="isLoadingDrivers"
                v-if="isLiotCarrier"
                wrapper-class="col-start-2 row-start-5"
                required
            />
        </div>
        <div class="flex justify-center">
            <UiButton
                type="submit"
                class="text-xl mb-16 uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
                @click="submitted = true"
            >Valider
            </UiButton>
        </div>
    </form>
</template>

<script setup lang="ts">
import { useReceptionStore } from '~/stores/reception'
import { useFormDataLoading } from '~/composables/useFormDataLoading'
import { useLiotHandling } from '~/composables/useLiotHandling'
import { useAddressSync } from '~/composables/useAddressSync'
import type { ReceptionTypeData } from '~/services/dto/reception-type-data'
import { getReceptionTypeList } from '~/services/reception-type'
import type { SupplierData } from '~/services/dto/supplier-data'
import { getSupplierList } from '~/services/supplier'
import { RECEPTION_TYPE_CODES } from '~/utils/constants'
import { deleteReceptionBovine, getReceptionBovineList } from '~/services/reception-bovine'
import type { ReceptionFormData } from '~/services/dto/reception-data'

const router = useRouter()
const receptionStore = useReceptionStore()
const isHydrating = ref(false)
const submitted = ref(false)

const form = reactive<ReceptionFormData>({
    licensePlate: '',
    receptionDate: new Date().toISOString().slice(0, 10),
    receptionTypeId: '',
    userId: '',
    supplierId: '',
    addressId: '',
    truckId: '',
    carrierId: '',
    driverId: '',
    vehicleId: ''
})

const receptionTypes = ref<ReceptionTypeData[]>([])
const suppliers = ref<SupplierData[]>([])
const isLoadingSuppliers = ref(false)

const { users, trucks, carriers, isLoadingUsers, isLoadingTrucks, isLoadingCarriers, loadCommonData } =
    useFormDataLoading(form)

const {
    isLiotCarrier, filteredDrivers, filteredVehicles,
    isLoadingDrivers, isLoadingVehicles, allowAnyLicensePlate,
    loadDrivers, loadVehicles
} = useLiotHandling(form, carriers, isHydrating)

const supplierIdRef = computed(() => form.supplierId)
const { ownerAddresses, addressOptions } = useAddressSync(form, supplierIdRef, suppliers)

const selectedReceptionType = computed(() =>
    receptionTypes.value.find((type) => String(type.id) === form.receptionTypeId) ?? null
)

const clearReceptionBovines = async (receptionIri: string) => {
    const existing = await getReceptionBovineList(receptionIri)
    for (const selection of existing) {
        await deleteReceptionBovine(selection.id)
    }
}

const loadSuppliers = async () => {
    isLoadingSuppliers.value = true
    try {
        suppliers.value = await getSupplierList()
    } finally {
        isLoadingSuppliers.value = false
    }
}

watch(
    () => receptionStore.current,
    (reception) => {
        isHydrating.value = true
        form.licensePlate = reception?.licensePlate ?? ''
        form.receptionDate = reception?.receptionDate?.slice(0, 10) ?? new Date().toISOString().slice(0, 10)
        form.receptionTypeId = reception?.receptionType?.id ? String(reception.receptionType.id) : ''
        form.userId = reception?.user?.id ? String(reception.user.id) : form.userId
        form.supplierId = reception?.supplier?.id ? String(reception.supplier.id) : ''
        form.addressId = reception?.address?.id ? String(reception.address.id) : ''
        form.truckId = reception?.truck?.id ? String(reception.truck.id) : ''
        form.carrierId = reception?.carrier?.id ? String(reception.carrier.id) : ''
        form.driverId = reception?.driver?.id ? String(reception.driver.id) : ''
        isHydrating.value = false
    },
    { immediate: true }
)

onMounted(async () => {
    receptionTypes.value = await getReceptionTypeList()
    await loadSuppliers()
    await loadCommonData()
    await loadDrivers()
    await loadVehicles()
})

async function validate() {
    const normalizedLicensePlate = form.licensePlate.trim()
    const normalizedReceptionDate = form.receptionDate.trim()
    const normalizedReceptionTypeId = form.receptionTypeId.trim()
    const normalizedUserId = form.userId.trim()
    const normalizedSupplierId = form.supplierId.trim()
    const normalizedAddressId = form.addressId.trim()
    const normalizedTruckId = form.truckId.trim()
    const normalizedCarrierId = form.carrierId.trim()
    const normalizedDriverId = form.driverId.trim()

    const receptionTypeIri = normalizedReceptionTypeId ? `/api/reception_types/${normalizedReceptionTypeId}` : null
    const userIri = normalizedUserId ? `/api/users/${normalizedUserId}` : null
    const supplierIri = normalizedSupplierId ? `/api/suppliers/${normalizedSupplierId}` : null
    const addressIri = normalizedAddressId ? `/api/addresses/${normalizedAddressId}` : null
    const truckIri = normalizedTruckId ? `/api/trucks/${normalizedTruckId}` : null
    const carrierIri = normalizedCarrierId ? `/api/carriers/${normalizedCarrierId}` : null
    const driverIri = normalizedDriverId ? `/api/drivers/${normalizedDriverId}` : null

    const basePayload = {
        licensePlate: normalizedLicensePlate,
        receptionDate: normalizedReceptionDate,
        receptionType: receptionTypeIri,
        user: userIri,
        supplier: supplierIri,
        address: addressIri,
        truck: truckIri,
        carrier: carrierIri
    }

    const payload = {
        ...basePayload,
        ...(isLiotCarrier.value && driverIri ? { driver: driverIri } : {})
    }

    if (!receptionStore.current) {
        const created = await receptionStore.createReception({
            currentStep: 1,
            ...payload
        })
        if (created) {
            await router.push(`/reception/${created.id}`)
        }
        return
    }

    const previousTypeCode = receptionStore.current.receptionType?.code ?? null
    const nextTypeCode = selectedReceptionType.value?.code ?? null
    const receptionIri = `/api/receptions/${receptionStore.current.id}`

    if (
        previousTypeCode === RECEPTION_TYPE_CODES.BOVINS &&
        nextTypeCode === RECEPTION_TYPE_CODES.MERCHANDISES
    ) {
        await clearReceptionBovines(receptionIri)
    }
    const nextStep = receptionStore.current.currentStep + 1
    await receptionStore.updateReception(receptionStore.current.id, {
        currentStep: nextStep,
        ...payload
    })
}
</script>
