<template>
    <div>
        <PageHeader>
            <span class="inline-flex items-center gap-3">
                <MalioButtonIcon
                    icon="mdi:arrow-left-bold"
                    icon-size="24"
                    variant="ghost"
                    :title="$t('common.back')"
                    :aria-label="$t('common.back')"
                    @click="goBack"
                />
                {{ client?.name ?? '…' }}
            </span>
        </PageHeader>

        <div class="flex flex-col gap-6">
        <p v-if="loading">{{ $t('common.loading') }}</p>
        <template v-else-if="client">
            <MalioTabList v-model="activeTab" :tabs="tabs">
                <template #info>
                    <div class="flex flex-col gap-4 pt-6">
                        <div class="grid grid-cols-4 gap-x-[44px] gap-y-4 pb-5">
                            <MalioInputText
                                v-model="info.name"
                                class="col-span-2"
                                :label="$t('directory.info.fields.name')"
                                :error="infoTouched.name && !info.name.trim() ? $t('directory.validation.nameRequired') : ''"
                                @blur="infoTouched.name = true"
                            />
                            <MalioInputEmail
                                v-model="info.email"
                                :label="$t('directory.info.fields.email')"
                                :error="emailError"
                            />
                            <MalioInputPhone
                                v-model="info.phone"
                                :label="$t('directory.info.fields.phone')"
                                :error="phoneError"
                            />
                            <MalioInputText
                                v-model="info.website"
                                class="col-span-2"
                                :label="$t('directory.info.fields.website')"
                                :error="websiteError"
                            />
                        </div>
                        <div class="flex justify-center pt-2">
                            <MalioButton
                                :label="$t('common.save')"
                                :disabled="savingInfo || !infoValid"
                                @click="saveInfo"
                            />
                        </div>
                    </div>
                </template>

                <template #contact>
                    <div class="flex flex-col gap-4 pt-6">
                        <DirectoryContactBlock
                            v-for="(contact, i) in contacts"
                            :key="contact.id || `new-${i}`"
                            :model-value="contact"
                            :title="$t('directory.contacts.item', { n: i + 1 })"
                            :removable="contacts.length > 0"
                            :last="i === contacts.length - 1"
                            @update:model-value="(v) => onContactInput(i, v)"
                            @remove="askRemoveContact(i)"
                        />
                        <div class="flex justify-center gap-3 pt-2">
                            <MalioButton
                                variant="secondary"
                                icon-name="mdi:plus"
                                icon-position="left"
                                button-class="w-auto px-4"
                                :label="$t('directory.contacts.add')"
                                @click="addContact"
                            />
                            <MalioButton
                                :label="$t('common.save')"
                                :disabled="savingContacts"
                                @click="saveContacts"
                            />
                        </div>
                    </div>
                </template>

                <template #address>
                    <div class="flex flex-col gap-4 pt-6">
                        <DirectoryAddressBlock
                            v-for="(address, i) in addresses"
                            :key="address.id || `new-${i}`"
                            :model-value="address"
                            :title="$t('directory.addresses.item', { n: i + 1 })"
                            :removable="addresses.length > 0"
                            :last="i === addresses.length - 1"
                            @update:model-value="(v) => onAddressInput(i, v)"
                            @remove="askRemoveAddress(i)"
                        />
                        <div class="flex justify-center gap-3 pt-2">
                            <MalioButton
                                variant="secondary"
                                icon-name="mdi:plus"
                                icon-position="left"
                                button-class="w-auto px-4"
                                :label="$t('directory.addresses.add')"
                                @click="addAddress"
                            />
                            <MalioButton
                                :label="$t('common.save')"
                                :disabled="savingAddresses"
                                @click="saveAddresses"
                            />
                        </div>
                    </div>
                </template>

                <template #report>
                    <CommercialReportTab :owner="owner" :can-manage="canManage" />
                </template>
            </MalioTabList>
        </template>
        </div>

        <ConfirmModal
            v-model="removeModalOpen"
            :title="removeModalTitle"
            :message="removeModalMessage"
            @confirm="confirmRemove"
        />
    </div>
</template>

<script setup lang="ts">
import type { Client } from '~/modules/directory/services/dto/client'
import { useClientService } from '~/modules/directory/services/clients'
import { isValidEmail, isValidFrPhone, isValidUrl } from '~/modules/directory/utils/validation'

definePageMeta({ middleware: ['admin'] })

const route = useRoute()
const router = useRouter()
const { t } = useI18n()

const id = Number(route.params.id)
const ownerIri = `/api/clients/${id}`
const owner = { client: ownerIri }

const clientService = useClientService()
const {
    contacts,
    addresses,
    savingContacts,
    savingAddresses,
    onContactInput,
    addContact,
    askRemoveContact,
    saveContacts,
    onAddressInput,
    addAddress,
    askRemoveAddress,
    saveAddresses,
    load,
    removeModalOpen,
    removeModalTitle,
    removeModalMessage,
    confirmRemove,
} = useDirectoryDetail(owner)

const { can } = usePermissions()
const canManage = computed(() => can('directory.clients.manage'))

const client = ref<Client | null>(null)
const loading = ref(true)

const activeTab = ref('info')
const tabs = [
    { key: 'info', label: t('directory.tabs.info'), icon: 'mdi:information-outline' },
    { key: 'contact', label: t('directory.tabs.contact'), icon: 'mdi:account-outline' },
    { key: 'address', label: t('directory.tabs.address'), icon: 'mdi:map-marker-outline' },
    { key: 'report', label: t('directory.tabs.report'), icon: 'mdi:file-document-outline' },
]

// Champs de base de la fiche, édités en mémoire et persistés au clic sur
// « Enregistrer » (PATCH), comme les onglets Contact/Adresse.
const info = reactive({ name: '', email: '', phone: '', website: '' })
const infoTouched = reactive({ name: false })
const savingInfo = ref(false)

const emailError = computed(() => (isValidEmail(info.email) ? '' : t('directory.validation.emailInvalid')))
const phoneError = computed(() => (isValidFrPhone(info.phone) ? '' : t('directory.validation.phoneInvalid')))
const websiteError = computed(() => (isValidUrl(info.website) ? '' : t('directory.validation.urlInvalid')))
const infoValid = computed(() => !emailError.value && !phoneError.value && !websiteError.value)

async function saveInfo(): Promise<void> {
    infoTouched.name = true
    if (!info.name.trim() || !infoValid.value || savingInfo.value) return
    savingInfo.value = true
    try {
        client.value = await clientService.update(id, {
            name: info.name.trim(),
            email: info.email.trim() || null,
            phone: info.phone.trim() || null,
            website: info.website.trim() || null,
        })
    } finally {
        savingInfo.value = false
    }
}

function goBack(): void {
    // Retour sur l'onglet Clients de la liste (via history.state, hors URL).
    router.push({ path: '/directory', state: { tab: 'clients' } })
}

onMounted(async () => {
    client.value = await clientService.getById(id)
    info.name = client.value.name ?? ''
    info.email = client.value.email ?? ''
    info.phone = client.value.phone ?? ''
    info.website = client.value.website ?? ''
    await load()
    loading.value = false
})
</script>
