<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"
                />
                {{ prospect?.company ?? '…' }}
            </span>
        </PageHeader>

        <div class="flex flex-col gap-6">
        <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="grid grid-cols-4 gap-x-[44px] gap-y-4 pb-5">
                            <MalioInputText
                                v-model="info.company"
                                class="col-span-2"
                                :label="$t('prospects.fields.company')"
                                :error="infoTouched.company && !info.company.trim() ? $t('prospects.validation.companyRequired') : ''"
                                @blur="infoTouched.company = true"
                            />
                            <MalioSelect
                                v-model="info.status"
                                :label="$t('prospects.fields.status')"
                                :options="statusOptions"
                                group-class="w-full"
                            />
                            <MalioInputText
                                v-model="info.website"
                                :label="$t('prospects.fields.website')"
                                :error="websiteError"
                            />
                            <MalioInputEmail
                                v-model="info.email"
                                :label="$t('prospects.fields.email')"
                                :error="emailError"
                            />
                            <MalioInputPhone
                                v-model="info.phone"
                                :label="$t('prospects.fields.phone')"
                                :error="phoneError"
                            />
                            <MalioInputText
                                v-model="info.source"
                                class="col-span-2"
                                :label="$t('prospects.fields.source')"
                            />
                            <!-- Notes : 2 colonnes, hauteur fixe (~2 lignes) avec scroll
                                 interne. Pas de row-span (il déréglait l'auto-placement).
                                 !max-w-none : neutralise le max-width:640px inline du
                                 composant Malio (sinon la textarea ne remplit pas 2 colonnes). -->
                            <MalioInputTextArea
                                v-model="info.notes"
                                group-class="col-span-2"
                                text-input="!h-28 !max-w-none text-lg"
                                resize="none"
                                :reserve-message-space="false"
                                :label="$t('prospects.fields.notes')"
                            />
                        </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 { Prospect, ProspectStatus } from '~/modules/directory/services/dto/prospect'
import { useProspectService } from '~/modules/directory/services/prospects'
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/prospects/${id}`
const owner = { prospect: ownerIri }

const prospectService = useProspectService()
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.prospects.manage'))

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<{
    company: string
    email: string
    phone: string
    website: string
    status: ProspectStatus
    source: string
    notes: string
}>({ company: '', email: '', phone: '', website: '', status: 'new', source: '', notes: '' })
const infoTouched = reactive({ company: 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.company = true
    if (!info.company.trim() || !infoValid.value || savingInfo.value) return
    savingInfo.value = true
    try {
        prospect.value = await prospectService.update(id, {
            company: info.company.trim(),
            email: info.email.trim() || null,
            phone: info.phone.trim() || null,
            website: info.website.trim() || null,
            status: info.status,
            source: info.source.trim() || null,
            notes: info.notes.trim() || null,
        })
    } finally {
        savingInfo.value = false
    }
}

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

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