<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">{{ prospect?.name ?? '…' }}</h1>
        </div>

        <p v-if="loading">{{ $t('common.loading') }}</p>
        <template v-else-if="prospect">
            <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('prospects.fields.name')"
                                :error="infoTouched.name && !info.name.trim() ? $t('prospects.validation.nameRequired') : ''"
                                @blur="infoTouched.name = true"
                            />
                            <MalioInputText
                                v-model="info.company"
                                :label="$t('prospects.fields.company')"
                            />
                            <MalioSelect
                                v-model="info.status"
                                :label="$t('prospects.fields.status')"
                                :options="statusOptions"
                                group-class="w-full"
                            />
                            <MalioInputText
                                v-model="info.email"
                                :label="$t('prospects.fields.email')"
                            />
                            <MalioInputText
                                v-model="info.phone"
                                :label="$t('prospects.fields.phone')"
                            />
                            <MalioInputText
                                v-model="info.source"
                                class="col-span-2"
                                :label="$t('prospects.fields.source')"
                            />
                            <MalioInputTextArea
                                v-model="info.notes"
                                class="col-span-2"
                                :label="$t('prospects.fields.notes')"
                            />
                        </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 { Prospect, ProspectStatus } from '~/modules/directory/services/dto/prospect'
import { useProspectService } from '~/modules/directory/services/prospects'

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

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

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

const prospectService = useProspectService()
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 prospect = ref<Prospect | 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' },
]

const statusOptions = [
    { label: t('prospects.status.new'), value: 'new' },
    { label: t('prospects.status.contacted'), value: 'contacted' },
    { label: t('prospects.status.qualified'), value: 'qualified' },
    { label: t('prospects.status.won'), value: 'won' },
    { label: t('prospects.status.lost'), value: 'lost' },
]

// 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: string
    company: string
    email: string
    phone: string
    status: ProspectStatus
    source: string
    notes: string
}>({ name: '', company: '', email: '', phone: '', status: 'new', source: '', notes: '' })
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 {
        prospect.value = await prospectService.update(id, {
            name: info.name.trim(),
            company: info.company.trim() || null,
            email: info.email.trim() || null,
            phone: info.phone.trim() || null,
            status: info.status,
            source: info.source.trim() || null,
            notes: info.notes.trim() || null,
        })
    } finally {
        savingInfo.value = false
    }
}

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

onMounted(async () => {
    prospect.value = await prospectService.getById(id)
    info.name = prospect.value.name ?? ''
    info.company = prospect.value.company ?? ''
    info.email = prospect.value.email ?? ''
    info.phone = prospect.value.phone ?? ''
    info.status = prospect.value.status ?? 'new'
    info.source = prospect.value.source ?? ''
    info.notes = prospect.value.notes ?? ''
    await load()
    loading.value = false
})
</script>
