<template>
    <div class="flex flex-col gap-6">
        <div class="flex items-center gap-3 pt-4">
            <MalioButtonIcon icon="mdi:arrow-left" :aria-label="$t('common.back')" @click="goBack" />
            <h1 class="text-2xl font-bold text-neutral-900">{{ client?.name ?? '…' }}</h1>
        </div>

        <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="relative grid grid-cols-2 gap-x-[44px] gap-y-4 rounded-lg bg-white px-7 py-5 shadow-[0_4px_4px_0_rgba(0,0,0,0.10)]">
                            <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"
                            />
                            <MalioInputText
                                v-model="info.email"
                                :label="$t('directory.info.fields.email')"
                            />
                            <MalioInputText
                                v-model="info.phone"
                                :label="$t('directory.info.fields.phone')"
                            />
                        </div>
                        <div class="flex justify-center pt-2">
                            <MalioButton
                                button-class="w-auto px-6"
                                :label="$t('common.save')"
                                :disabled="savingInfo"
                                @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"
                            @update:model-value="(v) => onContactInput(i, v)"
                            @remove="removeContact(i)"
                        />
                        <div class="flex justify-center gap-3 pt-2">
                            <MalioButton
                                variant="tertiary"
                                icon-name="mdi:plus"
                                icon-position="left"
                                button-class="w-auto px-4"
                                :label="$t('directory.contacts.add')"
                                @click="addContact"
                            />
                            <MalioButton
                                button-class="w-auto px-6"
                                :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"
                            @update:model-value="(v) => onAddressInput(i, v)"
                            @remove="removeAddress(i)"
                        />
                        <div class="flex justify-center gap-3 pt-2">
                            <MalioButton
                                variant="tertiary"
                                icon-name="mdi:plus"
                                icon-position="left"
                                button-class="w-auto px-4"
                                :label="$t('directory.addresses.add')"
                                @click="addAddress"
                            />
                            <MalioButton
                                button-class="w-auto px-6"
                                :label="$t('common.save')"
                                :disabled="savingAddresses"
                                @click="saveAddresses"
                            />
                        </div>
                    </div>
                </template>

                <template #report>
                    <CommercialReportTab :owner="owner" :is-admin="isAdmin" />
                </template>
            </MalioTabList>
        </template>
    </div>
</template>

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

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,
    removeContact,
    saveContacts,
    onAddressInput,
    addAddress,
    removeAddress,
    saveAddresses,
    load,
} = useDirectoryDetail(owner)

const authStore = useAuthStore()
const isAdmin = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN') ?? false)

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: '' })
const infoTouched = reactive({ name: false })
const savingInfo = ref(false)

async function saveInfo(): Promise<void> {
    infoTouched.name = true
    if (!info.name.trim() || 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,
        })
    } finally {
        savingInfo.value = false
    }
}

function goBack(): void {
    router.push('/directory')
}

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