<template>

    <form @submit.prevent="validate">
        <div class="flex items-center justify-between mt-12 mb-8 ">
            <h1 class="font-bold text-5xl uppercase">Réception {{ receptionLoad?.identificationNumber }}</h1>
        </div>
        <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 mb-12">
            <!--    Nom de l'utilisateur       -->
            <UiSelect
                id="reception-user"
                :disabled="!auth.isAdmin"
                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-1"
            />
            <!--    Date de réception        -->
            <UiDateInput
                id="reception-date"
                :disabled="!auth.isAdmin"
                v-model="form.receptionDate"
                label="Date de réception"
                wrapper-class="col-start-1 row-start-2"
            />
            <!--    Fournisseur        -->
            <UiSelect
                id="reception-supplier"
                v-model="form.supplierId"
                :disabled="!auth.isAdmin"
                label="Fournisseur"
                :options="suppliers.map((supplier) => ({
                    value: String(supplier.id),
                    label: supplier.name
                }))"
                :loading="isLoadingSuppliers"
                wrapper-class="col-start-1 row-start-3"
            />
            <!--    Adresse fournisseur        -->
            <UiSelect
                id="reception-address"
                v-model="form.addressId"
                label="Adresse"
                :options="supplierAddresses.map((address) => ({
                    value: String(address.id),
                    label: address.fullAddress
                }))"
                :disabled="(isLoadingSuppliers || supplierAddresses.length === 0) && !auth.isAdmin"
                wrapper-class="col-start-1 row-start-4"
            />
            <!--    Camion        -->
            <UiSelect
                id="reception-truck"
                v-model="form.truckId"
                :disabled="!auth.isAdmin"
                label="Camion"
                :options="trucks.map((truck) => ({
                    value: String(truck.id),
                    label: truck.name
                }))"
                :loading="isLoadingTrucks"
                wrapper-class="col-start-2 row-start-1"
            />
            <!--    Transporteur        -->
            <UiSelect
                id="reception-carrier"
                v-model="form.carrierId"
                label="Transporteur"
                :disabled="!auth.isAdmin"
                :options="carriers.map((carrier) => ({
                    value: String(carrier.id),
                    label: carrier.name
                }))"
                :loading="isLoadingCarriers"
                select-class="h-[34px]"
                wrapper-class="col-start-2 row-start-2"
            />
            <!--    Chauffeur (LIOT)        -->
            <UiSelect
                id="reception-driver"
                v-model="form.driverId"
                :disabled="!auth.isAdmin"
                label="Nom du chauffeur si LIOT"
                :options="filteredDrivers.map((driver) => ({
                    value: String(driver.id),
                    label: driver.name
                }))"
                :loading="isLoadingDrivers"
                wrapper-class="col-start-2 row-start-3"
            />
            <!--    Plaque d'immatriculation       -->
            <div v-if="!isLiotCarrier" class="col-start-2 row-start-4">
                <UiLicensePlateInput
                    :disabled="!auth.isAdmin"
                    v-model="form.licensePlate"
                    v-model:allowAny="allowAnyLicensePlate"
                />
            </div>
            <!--    Immatriculation (LIOT)        -->
            <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) && !auth.isAdmin"
                wrapper-class="col-start-2 row-start-4"
            />
        </div>
        <div class="flex justify-center mb-2">
            <UiButton
                v-if="auth.isAdmin"
                type="submit"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] mb-16"

            >
                Enregistrer
            </UiButton>
        </div>
            <div class="flex justify-evenly gap-y-8 gap-x-40 mb-8 border-b border-slate-400">
                <h1
                    class="font-bold text-3xl uppercase col-start-1 row-start-1 cursor-pointer"
                    :class="activeTab === 'weights' ? 'underline' : ''"
                    @click="activeTab = 'weights'"
                >
                    pesées
                </h1>
                <h1
                    class="font-bold text-3xl uppercase col-start-2 row-start-1 cursor-pointer"
                    :class="activeTab === 'merchandise' ? 'underline' : ''"
                    @click="activeTab = 'merchandise'"
                >
                    {{ isMerchandise ? "Marchandise" : "Bovins" }}
                </h1>
            </div>

            <update-weight
                v-if="activeTab === 'weights'"
                :idReception="idReception"
                :disabled="!auth.isAdmin"
            />

            <update-merchandise
                v-else-if="activeTab === 'merchandise' && isMerchandise"
                :idReception="idReception"
                :disabled="!auth.isAdmin"
            />

            <update-bovin
                v-else
                :idReception="idReception"
                :disabled="!auth.isAdmin"
            />
    </form>
</template>

<script setup lang="ts">
import {useReceptionStore} from '~/stores/reception'
import type {UserData} from '~/services/dto/user-data'
import {getUsers} from '~/services/auth'
import {useAuthStore} from '~/stores/auth'
import type {SupplierData} from '~/services/dto/supplier-data'
import {getSupplierList} from '~/services/supplier'
import type {TruckData} from '~/services/dto/truck-data'
import {getTruckList} from '~/services/truck'
import type {CarrierData} from '~/services/dto/carrier-data'
import {getCarrierList} from '~/services/carrier'
import type {DriverData} from '~/services/dto/driver-data'
import {getDriverList} from '~/services/driver'
import type {VehicleData} from '~/services/dto/vehicle-data'
import {getVehicleList} from '~/services/vehicle'
import {SUPPLIER_CODE} from "~/utils/constants";
import {deleteReceptionBovine, getReceptionBovineList} from "~/services/reception-bovine";
import type {ReceptionData, ReceptionFormData} from "~/services/dto/reception-data";
import {getReception} from "~/services/reception";
import UpdateWeight from "~/components/reception/update-weight.vue";
import UpdateMerchandise from "~/components/reception/update-merchandise.vue";
import UpdateBovin from "~/components/reception/update-bovin.vue";

const activeTab = ref<'weights' | 'merchandise'>('weights')
const router = useRouter()
const receptionStore = useReceptionStore()
const form = reactive<ReceptionFormData>({
    licensePlate: '',
    receptionDate: new Date().toISOString().slice(0, 10),
    receptionTypeId: '',
    userId: '',
    supplierId: '',
    addressId: '',
    truckId: '',
    carrierId: '',
    driverId: '',
    vehicleId: ''
})
const allowAnyLicensePlate = ref(false)
const isLoading = ref(false)
const users = ref<UserData[]>([])
const isLoadingUsers = ref(false)
const suppliers = ref<SupplierData[]>([])
const isLoadingSuppliers = ref(false)
const trucks = ref<TruckData[]>([])
const isLoadingTrucks = ref(false)
const carriers = ref<CarrierData[]>([])
const isLoadingCarriers = ref(false)
const drivers = ref<DriverData[]>([])
const isLoadingDrivers = ref(false)
const vehicles = ref<VehicleData[]>([])
const isLoadingVehicles = ref(false)
const authStore = useAuthStore()

// Empêche les watchers de reset des champs pendant le remplissage initial
const isHydrating = ref(false)
const route = useRoute()
const idReception = Number(route.params.id)
const receptionLoad = await getReception(idReception)
const receptionType = receptionLoad.receptionType
const auth = useAuthStore()
const isBtWeight = ref(true)
const isMerchandise = ref(receptionType.code === 'MARCHANDISES')

// Transporteur sélectionné dans le formulaire
const selectedCarrier = computed(() =>
    carriers.value.find((carrier) => String(carrier.id) === form.carrierId) ?? null
)
// Indique si le transporteur est LIOT
const isLiotCarrier = computed(() => selectedCarrier.value?.code === SUPPLIER_CODE.LIOT)
// Adresses disponibles pour le fournisseur sélectionné
const supplierAddresses = computed(() => {
    const supplierId = Number(form.supplierId)
    if (!Number.isFinite(supplierId)) {
        return []
    }
    return suppliers.value.find((supplier) => supplier.id === supplierId)?.addresses ?? []
})
// Chauffeurs filtrés par transporteur (LIOT)
const filteredDrivers = computed<DriverData[]>(() => {
    if (!form.carrierId) {
        return []
    }
    return drivers.value.filter((driver) => String(driver.carrier?.id) === form.carrierId)
})
// Véhicules filtrés par transporteur + type de camion
const filteredVehicles = computed<VehicleData[]>(() => {
    if (!form.carrierId) {
        return []
    }
    return vehicles.value.filter(
        (vehicle) =>
            String(vehicle.carrier?.id) === form.carrierId &&
            (!form.truckId || String(vehicle.truck?.id) === form.truckId)
    )
})

// Supprime les données bovines si on change de type de réception
const clearReceptionBovines = async (receptionIri: string) => {
    const existing = await getReceptionBovineList(receptionIri)
    for (const selection of existing) {
        await deleteReceptionBovine(selection.id)
    }
}

const hydrateFromUser = (reception: ReceptionData | null) => {
    if (!reception) {
        return
    }
    isHydrating.value = true
    form.licensePlate = reception?.licensePlate ?? ''
    form.receptionDate = reception?.receptionDate ?? new Date().toISOString().slice(0, 10)
    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
}

watch(
    () => idReception,
    async (id) => {
        if (id === null) {
            return
        }
        isLoading.value = true
        try {
            const user = await getReception(id)
            hydrateFromUser(user)
        } finally {
            isLoading.value = false
        }
    },
    {immediate: true}
)

// Charge la liste des users pour le select
const loadUsers = async () => {
    isLoadingUsers.value = true
    try {
        users.value = await getUsers()
    } finally {
        isLoadingUsers.value = false
    }
}

// Charge la liste des fournisseurs pour le select
const loadSuppliers = async () => {
    isLoadingSuppliers.value = true
    try {
        suppliers.value = await getSupplierList()
    } finally {
        isLoadingSuppliers.value = false
    }
}

// Charge la liste des camions pour le select
const loadTrucks = async () => {
    isLoadingTrucks.value = true
    try {
        trucks.value = await getTruckList()
    } finally {
        isLoadingTrucks.value = false
    }
}

// Charge la liste des transporteurs pour le select
const loadCarriers = async () => {
    isLoadingCarriers.value = true
    try {
        carriers.value = await getCarrierList()
    } finally {
        isLoadingCarriers.value = false
    }
}

// Charge la liste des chauffeurs pour le select
const loadDrivers = async () => {
    isLoadingDrivers.value = true
    try {
        drivers.value = await getDriverList()
    } finally {
        isLoadingDrivers.value = false
    }
}

// Charge la liste des véhicules pour le select
const loadVehicles = async () => {
    isLoadingVehicles.value = true
    try {
        vehicles.value = await getVehicleList()
    } finally {
        isLoadingVehicles.value = false
    }
}

// On met le user connecté par défaut dans le select
const setDefaultUser = () => {
    if (form.userId) {
        return
    }
    if (authStore.user?.id) {
        form.userId = String(authStore.user.id)
    }
}

// On récupère toutes les données des selects au chargement du composant
onMounted(async () => {
    await loadUsers()
    await loadSuppliers()
    await loadTrucks()
    await loadCarriers()
    await loadDrivers()
    await loadVehicles()
    await authStore.ensureSession()
    setDefaultUser()
})

// Ajuste driver/vehicle quand le transporteur change (logique LIOT)
watch(
    () => [form.supplierId, form.addressId, suppliers.value],
    () => {
        if (!form.supplierId) {
            form.addressId = ''
            return
        }
        if (!form.addressId && supplierAddresses.value.length === 1) {
            form.addressId = String(supplierAddresses.value[0].id)
            return
        }
        if (!form.addressId) {
            return
        }
        const matches = supplierAddresses.value.some(
            (address) => String(address.id) === form.addressId
        )
        if (!matches) {
            if (supplierAddresses.value.length === 1) {
                form.addressId = String(supplierAddresses.value[0].id)
            } else {
                form.addressId = ''
            }
        }
    },
    {immediate: true}
)

// Valide/auto-sélectionne le véhicule selon camion + transporteur (LIOT)
watch(
    () => form.carrierId,
    () => {
        if (isHydrating.value) {
            return
        }
        if (!form.carrierId && idReception == null) {
            form.driverId = ''
            form.vehicleId = ''
            return
        }
        if (!isLiotCarrier.value && idReception == null) {
            form.driverId = ''
            form.vehicleId = ''
            return
        }
        if (filteredDrivers.value.length === 1) {
            form.driverId = String(filteredDrivers.value[0].id)
        }
        if (filteredVehicles.value.length === 1) {
            form.vehicleId = String(filteredVehicles.value[0].id)
        }
    },
    {immediate: true}
)

// Récupère la plaque depuis le véhicule choisi (LIOT)
watch(
    () => [form.truckId, form.carrierId, vehicles.value],
    () => {
        if (!isLiotCarrier.value) {
            return
        }
        if (filteredVehicles.value.length === 1) {
            form.vehicleId = String(filteredVehicles.value[0].id)
            return
        }
        if (!form.vehicleId) {
            return
        }
        const matches = filteredVehicles.value.some(
            (vehicle) => String(vehicle.id) === form.vehicleId
        )
        if (!matches) {
            form.vehicleId = ''
        }
    },
    {immediate: true}
)

// Auto-renseigne le véhicule si la plaque correspond (LIOT)
watch(
    () => [form.vehicleId, form.carrierId, vehicles.value],
    () => {
        if (!isLiotCarrier.value) {
            return
        }
        if (isHydrating.value) {
            return
        }
        const selected = filteredVehicles.value.find(
            (vehicle) => String(vehicle.id) === form.vehicleId
        )
        if (selected) {
            form.licensePlate = selected.plate
            allowAnyLicensePlate.value = false
        }
    }
)

watch(
    () => [form.licensePlate, form.carrierId, vehicles.value],
    () => {
        if (!isLiotCarrier.value || form.vehicleId) {
            return
        }
        const match = filteredVehicles.value.find(
            (vehicle) => vehicle.plate === form.licensePlate
        )
        if (match) {
            form.vehicleId = String(match.id)
        }
    }
)

// Valide le formulaire et crée/met à jour la réception
async function validate() {
    const normalizedLicensePlate = form.licensePlate.trim()
    const normalizedReceptionDate = form.receptionDate.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 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,
        user: userIri,
        supplier: supplierIri,
        address: addressIri,
        truck: truckIri,
        carrier: carrierIri
    }

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

    if (idReception) {
        const updated = await receptionStore.updateReception(idReception, {
            ...payload
        })
        if (updated) {
            await router.push(`/reception/update/${updated.id}`)
        }
        router.push("/reception/finish-reception")
        return
    }
}

</script>
