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

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

        <div class="grid grid-cols-2 gap-y-8 gap-x-80 mb-10 py-12">
            <UiTextInput id="supplier-name" v-model="form.name" label="Nom du fournisseur" :disabled="!auth.isAdmin"/>
            <UiTextInput id="supplier-email" v-model="form.email" label="Email" :disabled="!auth.isAdmin"/>
            <UiTextInput id="supplier-phone" v-model="form.phone" label="Téléphone" :disabled="!auth.isAdmin"/>
        </div>

        <div class="mx-24 mb-4 py-6 border-t border-black"></div>
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-3xl font-bold uppercase">Adresses fournisseur</h2>
            <UiButton
                type="button"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
                :disabled="supplierId === null || !auth.isAdmin"
                @click="goToAddAddress"
            >
                Ajouter
            </UiButton>
        </div>
        <UiDataTable
            class="mb-10"
            :columns="addressColumns"
            :url="supplierId !== null ? `suppliers/${supplierId}` : ''"
            response-path="addresses"
            :items-per-page="5"
            :row-clickable="auth.isAdmin"
            @row-click="onAddressRowClick"
        />
    </form>
</template>

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

definePageMeta({layout: "default"})

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

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 form = reactive<SupplierFormData>({
    name: "",
    email: "",
    phone: "",
    addresses: [],
})
const addressColumns: ColumnConfig[] = [
    {key: "label", label: "Libellé"},
    {key: "street", label: "Rue"},
    {key: "street2", label: "Complément"},
    {key: "postalCode", label: "Code postal"},
    {key: "city", label: "Ville"},
    {key: "countryCode", label: "Pays"},
]

const goToAddAddress = () => {
    if (supplierId.value === null || !auth.isAdmin) return
    router.push({
        path: "/admin/supplier/address",
        query: {
            supplierId: String(supplierId.value),
            fromSupplier: "1",
        },
    })
}

const goToEditAddress = (addressId: number | null) => {
    if (supplierId.value === null || addressId === null || !auth.isAdmin) return
    router.push({
        path: "/admin/supplier/address",
        query: {
            supplierId: String(supplierId.value),
            addressId: String(addressId),
            fromSupplier: "1",
        },
    })
}

const onAddressRowClick = (row: Row) => {
    const id = Number(row.id)
    goToEditAddress(Number.isFinite(id) ? id : null)
}

const hydrateFromSupplier = (supplier: SupplierData | null) => {
    if (!supplier) return
    form.name = supplier.name ?? ""
    form.email = supplier.email ?? ""
    form.phone = supplier.phone ?? ""
}

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() {
    if (isLoading.value) return
    if (!auth.isAdmin) return
    isLoading.value = true

    try {
        const name = form.name.trim()
        const email = (form.email ?? "").trim() || null
        const phone = (form.phone ?? "").trim() || null

        const supplierPayload: SupplierPayload = {
            name,
            email,
            phone,
        }
        let targetId: number | null = null

        if (supplierId.value !== null) {
            await updateSupplier(supplierId.value, supplierPayload)
            targetId = supplierId.value
        } else {
            const created = await createSupplier(supplierPayload)
            targetId = created.id
        }

        await router.push(`/admin/supplier/${targetId}`)
    } finally {
        isLoading.value = false
    }
}
</script>
