<template>
    <form :class="{ submitted }" @submit.prevent="validate">
        <div class="grid grid-cols-2 h-[461px] items-start gap-y-8 gap-x-40 mb-16">
            <div class="flex items-center justify-between gap-10 relative col-start-1 row-start-1">
                <div class="flex flex-row absolute -left-[60px] justify-between">
                    <Icon @click="router.push('/shipment/finish-shipment')" name="gg:arrow-left-o" size="44" class="cursor-pointer text-primary-500"/>
                </div>
                <h1 class="font-bold text-4xl col-start-1 row-start-1 text-primary-500 uppercase">Expédition {{ form.identificationNumber }}</h1>
                <div class="bg-primary-500 p-1 rounded-md flex items-center" title="Imprimer" @click="printReceipt">
                    <Icon name="mdi:printer-outline" size="32" class="cursor-pointer text-white"/>
                </div>
            </div>

            <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"
                required
            />

            <UiDateInput
                id="shipment-date"
                v-model="form.shipmentDate"
                label="Date d'expédition"
                wrapper-class="col-start-1 row-start-3"
                required
            />

            <div class="col-start-1 row-start-4 h-[64px]">
                <div class="flex w-full items-end gap-[104px]">
                    <UiRadioGroup
                        id="shipment-type"
                        name="shipment-type"
                        label="Type d'expédition bovine"
                        input-class="accent-primary-700 focus:ring-primary-700"
                        group-class="flex flex-row gap-[104px] w-[160px_160px] h-[32px]"
                        v-model="selectedShipmentTypeId"
                        :options="bovineShipment.map((type) => ({
                            value: String(type.id),
                            label: type.label
                        }))"
                        required
                    />
                    <UiNumberInput
                        id="shipment-type-quantity"
                        v-model="shipmentQuantity"
                        :placeholder="0"
                        :min="0"
                        :max="1200"
                        :disabled="!selectedShipmentTypeId"
                    />
                </div>
            </div>

            <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"
                required
            />

            <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"
                required
            />

            <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"
                required
            />

            <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"
                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="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"
                required
            />

            <div class="col-start-2 row-start-5 min-h-[72px]">
                <UiSelect
                    v-if="isLiotCarrier"
                    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"
                    required
                />
            </div>
        </div>

        <div v-if="formIsLoading">
            <div class="flex justify-evenly gap-y-8 gap-x-41 mb-10 border-b border-primary-500/60">
                <h1
                    class="font-bold text-3xl uppercase px-12 col-start-1 row-start-1 cursor-pointer"
                    :class="[
                        activeTab === 'weights' ? 'border-b-[6px] border-primary-500 text-primary-500' : 'text-primary-500/50',
                        hasGrossWeightError ? '!text-red-500 !border-red-500' : ''
                    ]"
                    @click="activeTab = 'weights'"
                >
                    pesée à plein
                </h1>
                <h1
                    class="font-bold text-3xl uppercase col-start-1 row-start-1 px-12 cursor-pointer"
                    :class="[
                        activeTab === 'weightsEmpty' ? 'border-b-[6px] border-primary-500 text-primary-500' : 'text-primary-500/50',
                        hasTareWeightError ? '!text-red-500 !border-red-500' : ''
                    ]"
                    @click="activeTab = 'weightsEmpty'"
                >
                    pesée à vide
                </h1>
            </div>
            <div class="mb-12">
                <update-weight
                    v-show="activeTab === 'weights'"
                    v-model="grossWeight"
                    v-if="grossWeight"
                    :isAdmin="authStore.isAdmin"
                />
                <update-weight
                    v-show="activeTab === 'weightsEmpty'"
                    v-model="tareWeight"
                    v-if="tareWeight"
                    :isAdmin="authStore.isAdmin"
                />
            </div>
        </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 { usePdfPrinter } from '#imports'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import UpdateWeight from '~/components/commun/update-weight.vue'
import { getUsers } from '~/services/auth'
import { getCarrierList } from '~/services/carrier'
import { getCustomerList } from '~/services/customer'
import type { AddressData } from '~/services/dto/address-data'
import type { CarrierData } from '~/services/dto/carrier-data'
import type { CustomerData } from '~/services/dto/customer-data'
import type { DriverData } from '~/services/dto/driver-data'
import type { ShipmentData, ShipmentFormData } from '~/services/dto/shipment-data'
import type { ShipmentTypeData } from '~/services/dto/shipment-type-data'
import type { TruckData } from '~/services/dto/truck-data'
import type { UserData } from '~/services/dto/user-data'
import type { VehicleData } from '~/services/dto/vehicle-data'
import type { WeightEntryData } from '~/services/dto/weight-data'
import { getDriverList } from '~/services/driver'
import { getShipment, updateShipment } from '~/services/shipment'
import { getShipmentTypeList } from '~/services/shipment-type'
import { getTruckList } from '~/services/truck'
import { getVehicleList } from '~/services/vehicle'
import { createWeight, updateWeight } from '~/services/weight'
import { useAuthStore } from '~/stores/auth'
import { SUPPLIER_CODE } from '~/utils/constants'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { printPdf } = usePdfPrinter()

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 bovineShipment = ref<ShipmentTypeData[]>([])
const currentShipment = ref<ShipmentData | null>(null)

const selectedShipmentTypeId = ref('')
const shipmentQuantity = ref<number | null>(0)
const allowAnyLicensePlate = ref(false)
const submitted = ref(false)

const hasGrossWeightError = computed(() =>
    submitted.value && (grossWeight.value.weight === null || grossWeight.value.weighedAt === null || grossWeight.value.dsd === null)
)
const hasTareWeightError = computed(() =>
    submitted.value && (tareWeight.value.weight === null || tareWeight.value.weighedAt === null || tareWeight.value.dsd === null)
)

const activeTab = ref<'weightsEmpty' | 'weights'>('weights')
const grossWeight = ref<WeightEntryData>(createEmptyWeightEntry('gross'))
const tareWeight = ref<WeightEntryData>(createEmptyWeightEntry('tare'))
const formIsLoading = ref(false)

const isLoadingUsers = ref(false)
const isLoadingShipmentTypes = ref(false)
const isLoadingCustomers = ref(false)
const isLoadingTrucks = ref(false)
const isLoadingCarriers = ref(false)
const isLoadingVehicles = ref(false)
const isLoadingDrivers = ref(false)
const isHydrating = ref(false)

const form = reactive<ShipmentFormData & { identificationNumber: string | null }>({
    identificationNumber: null,
    userId: '',
    shipmentDate: new Date().toISOString().slice(0, 10),
    customerId: '',
    addressId: '',
    truckId: '',
    carrierId: '',
    driverId: '',
    vehicleId: '',
    licensePlate: ''
})

const shipmentId = computed(() => {
    const id = Number(route.params.id)
    return Number.isFinite(id) ? id : null
})

const selectedCarrier = computed(() =>
    carriers.value.find((carrier) => String(carrier.id) === form.carrierId) ?? null
)
const isLiotCarrier = computed(() => selectedCarrier.value?.code === SUPPLIER_CODE.LIOT)
const isAddressData = (value: unknown): value is AddressData =>
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    'fullAddress' in value

const customerAddresses = computed<AddressData[]>(() => {
    if (!form.customerId) return []
    const customerId = Number(form.customerId)
    if (!Number.isFinite(customerId) || customerId <= 0) return []

    const addresses = customers.value.find((c) => c.id === customerId)?.addresses ?? []
    return addresses.filter(isAddressData)
})

const customerAddressOptions = computed(() =>
    customerAddresses.value.map((address) => ({
        value: String(address.id),
        label: address.fullAddress
    }))
)

const filteredDrivers = computed<DriverData[]>(() => {
    if (!form.carrierId) {
        return []
    }
    return drivers.value.filter((driver) => String(driver.carrier?.id) === form.carrierId)
})

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)
    )
})

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
    }
}

function setDefaultUser() {
    if (form.userId) {
        return
    }
    if (authStore.user?.id) {
        form.userId = String(authStore.user.id)
    }
}

function hydrateFromShipment(shipment: ShipmentData | null) {
    if (!shipment) {
        return
    }

    isHydrating.value = true
    form.identificationNumber = shipment.identificationNumber ?? null
    form.licensePlate = shipment.licensePlate ?? ''
    form.shipmentDate = shipment.shipmentDate?.slice(0, 10) ?? 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) : ''
    selectedShipmentTypeId.value = shipment.shipmentType?.id ? String(shipment.shipmentType.id) : ''
    shipmentQuantity.value = shipment.nbBovinSend ?? 0
    const gross = shipment.weights?.find((weight) => weight.type === 'gross') ?? null
    const tare = shipment.weights?.find((weight) => weight.type === 'tare') ?? null
    grossWeight.value = gross ? { ...gross } : createEmptyWeightEntry('gross')
    tareWeight.value = tare ? { ...tare } : createEmptyWeightEntry('tare')
    isHydrating.value = false
}

async function printReceipt() {
    if (!import.meta.client || shipmentId.value === null || shipmentId.value <= 0) {
        return
    }

    const customerName =
        customers.value.find((customer) => String(customer.id) === form.customerId)?.name ??
        'client'
    const filename = `${form.identificationNumber || shipmentId.value}_${customerName}_${form.licensePlate || 'immat'}.pdf`
    await printPdf(`/shipments/${shipmentId.value}/receipt`, filename)
    await new Promise((resolve) => setTimeout(resolve, 600))
}

async function loadShipmentForUpdate() {
    if (shipmentId.value === null) {
        return
    }
    const shipment = await getShipment(shipmentId.value)
    currentShipment.value = shipment
    hydrateFromShipment(shipment)
}

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 }
)

function 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()
        }
    }
)

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 }
)

watch(
    () => [form.vehicleId, form.carrierId, vehicles.value],
    () => {
        if (!isLiotCarrier.value || 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, form.vehicleId, 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)
        }
    }
)

function buildPayload() {
    const normalizedLicensePlate = form.licensePlate.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 normalizedShipmentTypeId = selectedShipmentTypeId.value.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
    const shipmentTypeIri = normalizedShipmentTypeId
        ? `/api/shipment_types/${normalizedShipmentTypeId}`
        : null

    const rawQuantity = Number(shipmentQuantity.value ?? 0)
    const normalizedQuantity = Number.isFinite(rawQuantity)
        ? Math.max(0, Math.trunc(rawQuantity))
        : 0

    return {
        licensePlate: normalizedLicensePlate,
        shipmentDate: normalizedShipmentDate,
        customer: customerIri,
        truck: truckIri,
        carrier: carrierIri,
        driver: driverIri,
        user: userIri,
        address: addressIri,
        shipmentType: shipmentTypeIri,
        nbBovinSend: normalizedQuantity
    }
}

function createEmptyWeightEntry(type: 'gross' | 'tare'): WeightEntryData {
    return {
        type,
        dsd: null,
        weight: null,
        weighedAt: null
    }
}

async function saveWeightEntry(entry: WeightEntryData) {
    if (!shipmentId.value || entry.weight === null) {
        return
    }

    const payload = {
        type: entry.type,
        dsd: entry.dsd ?? null,
        weight: entry.weight,
        weighedAt: entry.weighedAt ?? null
    }

    if (entry.id) {
        await updateWeight(entry.id, payload)
        return
    }

    await createWeight({
        shipment: `api/shipments/${shipmentId.value}`,
        ...payload
    })
}

async function validate() {
    if (shipmentId.value === null) {
        return
    }

    const hasInvalidWeights =
        grossWeight.value.weight === null || grossWeight.value.weighedAt === null || grossWeight.value.dsd === null ||
        tareWeight.value.weight === null || tareWeight.value.weighedAt === null || tareWeight.value.dsd === null

    if (hasInvalidWeights) {
        return
    }

    await updateShipment(shipmentId.value, {
        currentStep: currentShipment.value?.currentStep ?? 0,
        ...buildPayload()
    })
    await saveWeightEntry(grossWeight.value)
    await saveWeightEntry(tareWeight.value)

    await loadShipmentForUpdate()
}

onMounted(async () => {
    await loadShipmentType()
    await loadUsers()
    await loadCustomers()
    await loadTrucks()
    await loadCarriers()
    await loadVehicles()
    await loadDrivers()
    await authStore.ensureSession()
    formIsLoading.value = true
    setDefaultUser()
    await loadShipmentForUpdate()
})
</script>
