<template>
    <form @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">Expédition</h1>
            <!--    Nom de l'utilisateur       -->
            <UiSelect
                id="shipment-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"
            />
            <!--    Date de l'éxpedition        -->
            <UiDateInput
                id="shipment-date"
                v-model="form.shipmentDate"
                label="Date du jour"
                wrapper-class="col-start-1 row-start-3"
            />
            <!--    Type d'expédition        -->
            <div class="col-start-1 row-start-4 h-[64px]">
                <div class="flex items-end gap-8 justify-between">
                    <UiRadioGroup
                        id="shipment-type"
                        name="shipment-type"
                        label="Type d'expédition bovine"
                        v-model="selectedShipmentTypeId"
                        :options="bovineShipment.map((type) => ({
                            value: String(type.id),
                            label: type.label
                        }))"
                    />
                    <UiNumberInput
                        id="shipment-type-quantity"
                        label="Quantité"
                        v-model="shipmentQuantity"
                        :placeholder="0"
                        :min="0"
                        :max="1200"
                        :disabled="!selectedShipmentTypeId"
                    />
                </div>
            </div>
            <!--    Client        -->
            <UiSelect
                id="shipment-customer"
                v-model="form.customerId"
                label="Client"
                :options="customers.map((customer) => ({
                    value: String(customer.id),
                    label: customer.name || `Client #${customer.id}`
                }))"
                :loading="isLoadingCustomers"
                wrapper-class="col-start-1 row-start-5"
            />
            <!--    Adresse du client        -->
            <UiSelect
                id="shipment-address"
                v-model="form.addressId"
                :options="customerAddressOptions"
                :disabled="isLoadingCustomers || customerAddresses.length === 0"
                label="Adresse"
                wrapper-class="col-start-2 row-start-1"
            />
            <!--   Camion        -->
            <UiSelect
                id="shipment-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"
            />
            <!--   Transporteur        -->
            <UiSelect
                id="shipment-carrier"
                v-model="form.carrierId"
                label="Transporteur"
                :options="carriers.map((carrier) => ({
                    value: String(carrier.id),
                    label: carrier.name
                }))"
                wrapper-class="col-start-2 row-start-3"
            />
            <!-- Plaque d'immatriculation (hors LIOT)        -->
            <div v-if="!isLiotCarrier" class="col-start-2 row-start-4">
                <UiLicensePlateInput
                    v-model="form.licencePlate"
                    v-model:allowAny="allowAnyLicensePlate"
                />
            </div>
            <!--    Immatriculation (LIOT)        -->
            <UiSelect
                v-if="isLiotCarrier"
                id="shipment-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"
            />
            <!--  Chauffeur (LIOT)        -->
            <UiSelect
                id="shipment-driver"
                v-model="form.driverId"
                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-5"
                v-if="isLiotCarrier"
            />
        </div>
        <div class="flex justify-center">
            <UiButton
                type="submit"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
            >Valider
            </UiButton>
        </div>
    </form>
</template>
<script setup lang="ts">

import type {UserData} from '~/services/dto/user-data'
import type {CustomerData} from '~/services/dto/customer-data'
import type {TruckData} from '~/services/dto/truck-data'
import type {CarrierData} from '~/services/dto/carrier-data'
import type {DriverData} from '~/services/dto/driver-data'
import type {VehicleData} from '~/services/dto/vehicle-data'
import type {AddressData} from '~/services/dto/address-data'
import {getUsers} from '~/services/auth'
import {getCustomerList} from '~/services/customer'
import {getTruckList} from '~/services/truck'
import {getCarrierList} from '~/services/carrier'
import {getVehicleList} from '~/services/vehicle'
import {getDriverList} from '~/services/driver'
import type {ShipmentFormData} from '~/services/dto/shipment-data'
import {SUPPLIER_CODE} from "~/utils/constants"
import {useAuthStore} from '~/stores/auth'
import {useShipmentStore} from '~/stores/shipment'
import { computed, reactive, ref, watch, onMounted } from 'vue'
import type {ShipmentTypeData} from "~/services/dto/shipment-type-data";
import {getShipmentTypeList} from "~/services/shipment-type";
import {
    createShipmentBovine,
    deleteShipmentBovine,
    getBovinShipmentList,
    updateShipmentBovine
} from "~/services/bovin-shipment";

const users = ref<UserData[]>([])
const customers = ref<CustomerData[]>([])
const trucks = ref<TruckData[]>([])
const carriers = ref<CarrierData[]>([])
const drivers = ref<DriverData[]>([])
const vehicles = ref<VehicleData[]>([])

const isLoadingUsers = ref(false)
const isLoadingShipmentTypes = ref(false)
const isLoadingCustomers = ref(false)
const isLoadingTrucks = ref(false)
const isLoadingCarriers = ref(false)
const isHydrating = ref(false)
const isLoadingVehicles = ref(false)
const allowAnyLicensePlate = ref(false)
const isLoadingDrivers = ref(false)
const authStore = useAuthStore()
const shipmentStore = useShipmentStore()
const router = useRouter()
const bovineShipment = ref<ShipmentTypeData[]>([])
const selectedShipmentTypeId = ref('')
const shipmentQuantity = ref<number | null>(0)
// Transporteur sélectionné dans le formulaire
const selectedCarrier = computed(() =>
    carriers.value.find((carrier) => String(carrier.id) === form.carrierId) ?? null
)
const isLiotCarrier = computed(() => selectedCarrier.value?.code === SUPPLIER_CODE.LIOT)

const form = reactive<ShipmentFormData>({
    userId: '',
    shipmentDate: new Date().toISOString().slice(0, 10),
    customerId: '',
    addressId: '',
    truckId: '',
    carrierId: '',
    driverId: '',
    vehicleId: '',
    licencePlate: '',
})
// Adresses liées au client sélectionné
const customerAddresses = computed<AddressData[]>(() => {
    const customerId = Number(form.customerId)
    if (!Number.isFinite(customerId)) {
        return []
    }
    return customers.value.find((customer) => customer.id === customerId)?.addresses ?? []
})
// Options pour le select des adresses du client
const customerAddressOptions = computed(() =>
    customerAddresses.value
        .map((address) => ({
            value: String(address.id),
            label: address.fullAddress
        }))
)
// Chauffeurs liés au transporteur sélectionné (LIOT)
const filteredDrivers = computed<DriverData[]>(() => {
    if (!form.carrierId) {
        return []
    }
    return drivers.value.filter((driver) => String(driver.carrier?.id) === form.carrierId)
})
// Véhicules liés au transporteur + camion sélectionnés (LIOT)
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)
    )
})
// Chargement des données pour les selects
const loadUsers = async () => {
    isLoadingUsers.value = true
    try {
        users.value = await getUsers()
    } finally {
        isLoadingUsers.value = false
    }
}

const loadShipmentType = async () => {
    isLoadingShipmentTypes.value = true
    try {
        bovineShipment.value = await getShipmentTypeList()
    } finally {
        isLoadingShipmentTypes.value = false
    }
}

const loadCustomers = async () => {
    isLoadingCustomers.value = true
    try {
        customers.value = await getCustomerList()
    } finally {
        isLoadingCustomers.value = false
    }

}
const loadTrucks = async () => {
    isLoadingTrucks.value = true
    try {
        trucks.value = await getTruckList()
    } finally {
        isLoadingTrucks.value = false
    }
}
const loadCarriers = async () => {
    isLoadingCarriers.value = true
    try {
        carriers.value = await getCarrierList()
    } finally {
        isLoadingCarriers.value = false
    }
}
const loadVehicles = async () => {
    isLoadingVehicles.value = true
    try {
        vehicles.value = await getVehicleList()
    } finally {
        isLoadingVehicles.value = false
    }
}
const loadDrivers = async () => {
    isLoadingDrivers.value = true
    try {
        drivers.value = await getDriverList()
    } finally {
        isLoadingDrivers.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)
    }
}
// Chargement initial des données
onMounted(async () => {
    await loadShipmentType()
    await loadUsers()
    await loadCustomers()
    await loadTrucks()
    await loadCarriers()
    await loadVehicles()
    await loadDrivers()
    await authStore.ensureSession()
    setDefaultUser()
})
// Hydrate le formulaire depuis l'expédition en cours
watch(
    () => shipmentStore.current,
    (shipment) => {
        isHydrating.value = true
        form.licencePlate = shipment?.licencePlate ?? ''
        form.shipmentDate = shipment?.shipmentDate ?? new Date().toISOString().slice(0, 10)
        form.userId = shipment?.user?.id ? String(shipment.user.id) :
            form.userId
        form.customerId = shipment?.customer?.id ?
            String(shipment.customer.id) : ''
        form.addressId = shipment?.address?.id ? String(shipment.address.id) : ''
        form.truckId = shipment?.truck?.id ? String(shipment.truck.id) : ''
        form.carrierId = shipment?.carrier?.id ? String(shipment.carrier.id) : ''
        form.driverId = shipment?.driver?.id ? String(shipment.driver.id) : ''
        form.vehicleId = shipment?.vehicle?.id ? String(shipment.vehicle.id) : ''
        if (!shipment || !shipment.bovinShipments) {
            selectedShipmentTypeId.value = ''
            shipmentQuantity.value = 0
        } else {
            const selectedEntry = shipment.bovinShipments.find((entry) => {
                const typeId = entry.shipmentType?.id
                return Boolean(typeId) && Number(entry.nbBovinSend ?? 0) > 0
            }) ?? shipment.bovinShipments.find((entry) => Boolean(entry.shipmentType?.id))

            if (!selectedEntry?.shipmentType?.id) {
                selectedShipmentTypeId.value = ''
                shipmentQuantity.value = 0
            } else {
                selectedShipmentTypeId.value = String(selectedEntry.shipmentType.id)
                shipmentQuantity.value = selectedEntry.nbBovinSend ?? 0
            }
        }
        isHydrating.value = false
    },
    {immediate: true}
)
// Ajuste driver/vehicle quand le transporteur change (logique LIOT)
watch(
    () => [form.customerId, form.addressId, customers.value],
    () => {
        if (!form.customerId) {
            form.addressId = ''
            return
        }
        if (!form.addressId && customerAddresses.value.length === 1) {
            form.addressId = String(customerAddresses.value[0].id)
            return
        }
        if (!form.addressId) {
            return
        }
        const matches = customerAddresses.value.some(
            (address) => String(address.id) === form.addressId
        )
        if (!matches) {
            if (customerAddresses.value.length === 1) {
                form.addressId = String(customerAddresses.value[0].id)
            } else {
                form.addressId = ''
            }
        }
    },
    {immediate: true}
)
// Valide/auto-sélectionne le véhicule selon camion + transporteur (LIOT)
const applyLiotDefaults = () => {
    if (isHydrating.value) {
        return
    }
    if (!form.carrierId) {
        form.driverId = ''
        form.vehicleId = ''
        return
    }
    if (!isLiotCarrier.value) {
        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)
    }
}
watch(
    () => form.carrierId,
    () => {
        applyLiotDefaults()
    },
    {immediate: true}
)
watch(
    () => isHydrating.value,
    (value) => {
        if (!value) {
            applyLiotDefaults()
        }
    }
)
// 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.licencePlate = selected.plate
            allowAnyLicensePlate.value = false
        }
    }
)
watch(
    () => [form.licencePlate, form.carrierId, vehicles.value],
    () => {
        if (!isLiotCarrier.value || form.vehicleId) {
            return
        }
        const match = filteredVehicles.value.find(
            (vehicle) => vehicle.plate === form.licencePlate
        )
        if (match) {
            form.vehicleId = String(match.id)
        }
    }
)
const buildDesiredBovinShipments = () => {
    const typeId = Number(selectedShipmentTypeId.value)
    if (!Number.isFinite(typeId)) {
        return []
    }
    const type = bovineShipment.value.find((entry) => entry.id === typeId)
    if (!type) {
        return []
    }
    const raw = shipmentQuantity.value
    const quantity = raw === null || raw === undefined ? 0 : Number(raw)
    const normalizedQuantity = Number.isFinite(quantity) ? Math.max(0, Math.trunc(quantity)) : 0
    if (normalizedQuantity <= 0) {
        return []
    }

    return [{type, quantity: normalizedQuantity}]
}
const syncBovinShipments = async (
    shipmentId: number,
    existing: Array<{ id?: number; nbBovinSend: number | null; shipmentType?: unknown }> = []
) => {
    const shipmentIri = `/api/shipments/${shipmentId}`
    const desired = buildDesiredBovinShipments()
    const desiredByTypeId = new Map<number, number>()
    for (const entry of desired) {
        desiredByTypeId.set(entry.type.id, entry.quantity)
    }
    for (const entry of existing) {
        if (!entry.id) {
            continue
        }
        const rawType = entry.shipmentType
        let typeId: number | null = null
        if (rawType && typeof rawType === 'object' && 'id' in rawType) {
            typeId = Number((rawType as { id: number }).id)
        } else if (typeof rawType === 'string') {
            const match = rawType.match(/\/shipment_types\/(\\d+)$/)
            typeId = match ? Number(match[1]) : null
        }
        if (!typeId) {
            continue
        }
        const desiredQuantity = desiredByTypeId.get(typeId)
        if (!desiredQuantity) {
            await deleteShipmentBovine(entry.id)
            continue
        }
        if (entry.nbBovinSend !== desiredQuantity) {
            await updateShipmentBovine(entry.id, {nbBovinSend: desiredQuantity})
        }
        desiredByTypeId.delete(typeId)
    }

    for (const [typeId, quantity] of desiredByTypeId.entries()) {
        await createShipmentBovine({
            shipment: shipmentIri,
            shipmentType: `/api/shipment_types/${typeId}`,
            nbBovinSend: quantity
        })
    }
}
const buildPayload = () => {
    const normalizedLicensePlate = form.licencePlate.trim()
    const normalizedShipmentDate = form.shipmentDate.trim()
    const normalizedCustomerId = form.customerId.trim()
    const normalizedTruckId = form.truckId.trim()
    const normalizedCarrierId = form.carrierId.trim()
    const normalizedDriverId = form.driverId.trim()
    const normalizedUserId = form.userId.trim()
    const normalizedAddressId = form.addressId.trim()
    const customerIri = normalizedCustomerId
        ? `/api/customers/${normalizedCustomerId}`
        : null
    const truckIri = normalizedTruckId
        ? `/api/trucks/${normalizedTruckId}`
        : null
    const carrierIri = normalizedCarrierId
        ? `/api/carriers/${normalizedCarrierId}`
        : null
    const userIri = normalizedUserId
        ? `/api/users/${normalizedUserId}`
        : null
    const driverIri = normalizedDriverId
        ? `/api/drivers/${normalizedDriverId}`
        : null
    const addressIri = normalizedAddressId
        ? `/api/addresses/${normalizedAddressId}`
        : null

    return {
        licencePlate: normalizedLicensePlate,
        shipmentDate: normalizedShipmentDate,
        customer: customerIri,
        truck: truckIri,
        carrier: carrierIri,
        driver: driverIri,
        user: userIri,
        address: addressIri
    }
}

const saveDraft = async () => {
    const payload = buildPayload()
    if (!shipmentStore.current) {
        const created = await shipmentStore.createShipment({
            currentStep: 0,
            ...payload
        })
        if (created) {
            await syncBovinShipments(created.id, [])
        }
        return
    }

    await shipmentStore.updateShipment(shipmentStore.current.id, {
        currentStep: shipmentStore.current.currentStep,
        ...payload
    })
    await syncBovinShipments(
        shipmentStore.current.id,
        shipmentStore.current?.bovinShipments ?? []
    )
}

defineExpose({saveDraft})
// Valide le formulaire et crée/met à jour l'expédition
const validate = async () => {
    const payload = buildPayload()
    if (!shipmentStore.current) {
        const created = await shipmentStore.createShipment({
            currentStep: 1,
            ...payload
        })
        if (created) {
            await shipmentStore.loadShipment(created.id)
            await syncBovinShipments(created.id, shipmentStore.current?.bovinShipments ?? [])
            await router.push(`/shipment/${created.id}`)
        }
        return
    }
    const nextStep = shipmentStore.current.currentStep + 1
    await shipmentStore.updateShipment(shipmentStore.current.id, {
        currentStep: nextStep,
        ...payload
    })
    await shipmentStore.loadShipment(shipmentStore.current.id)
    await syncBovinShipments(shipmentStore.current.id, shipmentStore.current?.bovinShipments ?? [])
}
</script>
