<template>
    <form @submit.prevent="validate">
        <div class="flex items-center justify-between gap-10">
            <h1 class="text-3xl font-bold uppercase">
                {{ supplierId ? "Modifications du fournisseur" : "Ajout d'un fournisseur" }}
            </h1>

            <button
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
                type="submit"
                :disabled="isLoading"
            >
                {{ supplierId ? "Sauvegarder" : "Ajouter" }}
            </button>
        </div>

        <div class="grid gap-y-16 gap-x-40 mb-16">

            <UiTextInput
                id="supplier-name"
                v-model="form.name"
                label="Nom du fournisseur"
            />

            <UiTextInput
                id="supplier-email"
                v-model="form.email"
                label="Email"
            />

            <UiTextInput
                id="supplier-phone"
                v-model="form.phone"
                label="Téléphone"
            />

            <UiTextInput
                id="supplier-street"
                v-model="form.addresses[0].street"
                label="Rue"
            />

            <UiTextInput
                id="supplier-street2"
                v-model="form.addresses[0].street2"
                label="Complément"
            />

            <UiTextInput
                id="supplier-postalCode"
                v-model="form.addresses[0].postalCode"
                label="Code postal"
            />

            <UiTextInput
                id="supplier-city"
                v-model="form.addresses[0].city"
                label="Ville"
            />

            <UiTextInput
                id="supplier-country"
                v-model="form.addresses[0].country"
                label="Pays"
            />
        </div>
    </form>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue"
import { createSupplier, getSupplier, updateSupplier } from "~/services/supplier"
import type { SupplierData, SupplierFormData } from "~/services/dto/supplier-data"

definePageMeta({ layout: "admin" })

const route = useRoute()
const router = useRouter()

const resolveId = (param: unknown) => {
    const idStr = Array.isArray(param) ? param[0] : param
    if (!idStr) return null
    const id = Number(idStr)
    return Number.isFinite(id) ? id : null
}

const supplierId = computed(() => resolveId(route.params.id))

const isLoading = ref(false)
const isHydrating = ref(false)

const form = reactive<SupplierFormData>({
    name: "",
    email: "",
    phone: "",
    addresses: [
        {
            id: null,
            street: "",
            street2: "",
            postalCode: "",
            city: "",
            country: ""
        }
    ]
})

const hydrateFromSupplier = (supplier: SupplierData | null) => {
    if (!supplier) return

    isHydrating.value = true

    form.name = supplier.name ?? ""
    form.email = supplier.email ?? ""
    form.phone = supplier.phone ?? ""

    const a0 = supplier.addresses?.[0] ?? null

    form.addresses[0].id = a0?.id ?? null
    form.addresses[0].street = a0?.street ?? ""
    form.addresses[0].street2 = a0?.street2 ?? ""
    form.addresses[0].postalCode = a0?.postalCode ?? ""
    form.addresses[0].city = a0?.city ?? ""
    form.addresses[0].country = a0?.country ?? ""

    isHydrating.value = false
}

watch(
    () => supplierId.value,
    async (id) => {
        if (id === null) return

        isLoading.value = true
        try {
            const supplier = await getSupplier(id)
            hydrateFromSupplier(supplier)
        } finally {
            isLoading.value = false
        }
    },
    { immediate: true }
)

async function validate() {

    const name = form.name.trim()
    const email = form.email.trim()
    const phone = form.phone.trim()

    const a0 = form.addresses[0]
    const street = a0.street.trim()
    const street2 = (a0.street2 ?? "").trim()
    const postalCode = a0.postalCode.trim()
    const city = a0.city.trim()
    const country = a0.country.trim()

    const payload = {
        name,
        email,
        phone,
        addresses: [
            {
                id: a0.id ?? undefined,
                street,
                street2: street2 || undefined,
                postalCode,
                city,
                country
            }
        ]
    }

    if (supplierId.value !== null) {
        await updateSupplier(supplierId.value, payload)
        await router.push("/admin/supplier/supplier-list")
        return
    }

    await createSupplier(payload)
    await router.push("/admin/supplier/supplier-list")
}
</script>
