<template>
    <form @submit.prevent="validateForm">
        <div class="flex items-center justify-between gap-10">
            <div>
                <h1 class="text-3xl font-bold uppercase">
                    {{ props.address ? "Modification d'une adresse" : "Ajout d'une adresse" }}
                </h1>
            </div>

            <button
                class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
                type="submit"
                :disabled="isLoading"
            >
                <Icon :name="props.address ? '' : 'mdi:plus'" size="28" />
                {{ props.address? "Valider" : "Ajouter" }}
            </button>
        </div>

        <div class="grid grid-cols-2 gap-y-16 gap-x-12 mb-16 mt-10">
            <UiTextInput id="address-label" v-model="form.label" label="Libellé" />
            <UiTextInput id="address-street" v-model="form.street" label="Rue" />
            <UiTextInput id="address-street2" v-model="form.street2" label="Complément" />
            <UiTextInput id="address-postalCode" v-model="form.postalCode" label="Code postal" />
            <UiTextInput id="address-city" v-model="form.city" label="Ville" />
            <UiTextInput id="address-country" v-model="form.countryCode" label="Pays (code)" />
        </div>
    </form>
</template>

<script setup lang="ts">
import type { AddressPayload } from "~/services/address"


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

const props = defineProps<{
    type?: "supplier" | "customer",
    address?: AddressPayload | null
}>()

const isLoading = ref(false)

const emptyForm = (): AddressPayload => ({
    label: "",
    street: "",
    street2: null,
    postalCode: "",
    city: "",
    countryCode: "",
})

const form = reactive<AddressPayload>(emptyForm())

const hydrateForm = (address?: AddressPayload | null) => {
    const data = address ?? emptyForm()
    form.label = data.label ?? ""
    form.street = data.street ?? ""
    form.street2 = data.street2 ?? null
    form.postalCode = data.postalCode ?? ""
    form.city = data.city ?? ""
    form.countryCode = data.countryCode ?? ""
}

watch(
    () => props.address,
    (addr) => {
        hydrateForm(addr)
    },
    { immediate: true }
)

const validateForm = () => {
    if (isLoading.value) return
    emit("validate", {...form})
}

const emit = defineEmits<{
    (event: 'validate', form: AddressPayload): void
}>()
</script>
