<!--
|--------------------------------------------------------------------------
| Agência PSI — Editor de emails polimórfico
|--------------------------------------------------------------------------
| Uso:
|   <ContactEmailsEditor entity-type="patient" :entity-id="patient.id" />
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, onMounted, watch, reactive } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { useContactEmails } from '@/composables/useContactEmails';

const props = defineProps({
    entityType: { type: String, required: true },
    entityId: { type: String, required: false, default: null },
    readonly: { type: Boolean, default: false },
    confirmGroup: { type: String, default: '' }
});

const emit = defineEmits(['change']);

const toast = useToast();
const confirm = useConfirm();
const api = useContactEmails();

const showAddForm = ref(false);
const newForm = reactive({ contact_email_type_id: null, email: '', notes: '' });

function openAddForm() {
    const defaultType = api.typeBySlug('principal') || api.types.value[0];
    newForm.contact_email_type_id = defaultType?.id || null;
    newForm.email = '';
    newForm.notes = '';
    showAddForm.value = true;
}

function cancelAddForm() {
    showAddForm.value = false;
}

async function submitAddForm() {
    if (!newForm.contact_email_type_id || !newForm.email.trim()) return;
    const res = await api.addEmail(props.entityType, props.entityId, {
        contact_email_type_id: newForm.contact_email_type_id,
        email: newForm.email,
        is_primary: api.emails.value.length === 0,
        notes: newForm.notes || null
    });
    if (res.ok) {
        showAddForm.value = false;
        toast.add({ severity: 'success', summary: 'Email adicionado', life: 1800 });
        emit('change', api.emails.value);
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

const editingId = ref(null);
const editForm = reactive({ contact_email_type_id: null, email: '', notes: '' });

function startEdit(email) {
    editingId.value = email.id;
    editForm.contact_email_type_id = email.contact_email_type_id;
    editForm.email = email.email;
    editForm.notes = email.notes || '';
}

function cancelEdit() {
    editingId.value = null;
}

async function saveEdit(email) {
    const res = await api.updateEmail(props.entityType, props.entityId, email.id, {
        contact_email_type_id: editForm.contact_email_type_id,
        email: editForm.email,
        notes: editForm.notes.trim() || null
    });
    if (res.ok) {
        editingId.value = null;
        toast.add({ severity: 'success', summary: 'Email atualizado', life: 1800 });
        emit('change', api.emails.value);
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

async function setPrimary(email) {
    if (email.is_primary) return;
    const res = await api.setPrimary(props.entityType, props.entityId, email.id);
    if (res.ok) {
        toast.add({ severity: 'success', summary: 'Email principal atualizado', life: 1800 });
        emit('change', api.emails.value);
    }
}

function confirmRemove(email) {
    const typeName = api.typeById(email.contact_email_type_id)?.name || 'email';
    confirm.require({
        group: props.confirmGroup || undefined,
        message: `Remover este ${typeName}${email.is_primary ? ' (principal)' : ''}?`,
        header: 'Remover email',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        acceptLabel: 'Remover',
        rejectLabel: 'Cancelar',
        accept: async () => {
            const res = await api.removeEmail(props.entityType, props.entityId, email.id);
            if (res.ok) {
                toast.add({ severity: 'success', summary: 'Removido', life: 1800 });
                emit('change', api.emails.value);
            } else {
                toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
            }
        }
    });
}

onMounted(async () => {
    await api.loadTypes();
    if (props.entityId) await api.loadEmails(props.entityType, props.entityId);
});

watch(() => props.entityId, async (v) => {
    if (v) await api.loadEmails(props.entityType, v);
    else api.emails.value = [];
});
</script>

<template>
    <div class="flex flex-col gap-2">
        <div class="text-[0.7rem] text-[var(--text-color-secondary)] flex items-start gap-1.5 px-1">
            <i class="pi pi-info-circle text-sky-500 mt-0.5 shrink-0" />
            <span>
                Marque um email como <strong>principal</strong> — ele é usado pra
                <strong>envio de faturas, templates e notificações por email</strong>.
            </span>
        </div>

        <div v-if="api.loading.value" class="text-xs text-center py-3 text-[var(--text-color-secondary)]">
            <i class="pi pi-spin pi-spinner mr-1" /> Carregando…
        </div>

        <div v-else-if="!api.emails.value.length && !showAddForm" class="text-xs text-center py-4 italic text-[var(--text-color-secondary)] border border-dashed border-[var(--surface-border)] rounded-md">
            Nenhum email cadastrado.
        </div>

        <div v-else class="flex flex-col gap-1.5">
            <div
                v-for="email in api.emails.value"
                :key="email.id"
                class="flex items-center gap-2 p-2 rounded-md border border-[var(--surface-border)]"
                :class="email.is_primary ? 'bg-[var(--primary-color)]/5 border-[var(--primary-color)]/30' : 'bg-[var(--surface-card)]'"
            >
                <template v-if="editingId !== email.id">
                    <div class="w-8 h-8 rounded grid place-items-center shrink-0 bg-[var(--surface-ground)]">
                        <i :class="api.typeById(email.contact_email_type_id)?.icon || 'pi pi-envelope'" class="text-sm text-[var(--text-color-secondary)]" />
                    </div>

                    <div class="flex-1 min-w-0 flex flex-col gap-0.5">
                        <div class="flex items-center gap-1.5 flex-wrap">
                            <span class="text-xs font-semibold text-[var(--text-color-secondary)]">{{ api.typeById(email.contact_email_type_id)?.name || 'Email' }}</span>
                            <span v-if="email.is_primary" class="inline-flex items-center px-1.5 py-px rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-[var(--primary-color)] text-white">Principal</span>
                        </div>
                        <a :href="`mailto:${email.email}`" class="text-sm font-mono truncate text-[var(--primary-color)] hover:underline" @click.stop>{{ email.email }}</a>
                        <span v-if="email.notes" class="text-[0.7rem] italic text-[var(--text-color-secondary)]">{{ email.notes }}</span>
                    </div>

                    <div v-if="!readonly" class="flex items-center gap-0.5 shrink-0">
                        <Button v-if="!email.is_primary" icon="pi pi-star" text size="small" class="h-7 w-7" v-tooltip.top="'Marcar como principal'" :disabled="api.saving.value" @click="setPrimary(email)" />
                        <Button icon="pi pi-pencil" text size="small" class="h-7 w-7" v-tooltip.top="'Editar'" :disabled="api.saving.value" @click="startEdit(email)" />
                        <Button icon="pi pi-trash" text severity="danger" size="small" class="h-7 w-7" v-tooltip.top="'Remover'" :disabled="api.saving.value" @click="confirmRemove(email)" />
                    </div>
                </template>

                <template v-else>
                    <div class="flex flex-col gap-1.5 flex-1 min-w-0">
                        <div class="flex items-center gap-1.5 flex-wrap">
                            <Select
                                v-model="editForm.contact_email_type_id"
                                :options="api.types.value"
                                optionLabel="name"
                                optionValue="id"
                                class="text-xs"
                                style="width: 140px"
                                appendTo="body"
                            >
                                <template #option="slotProps">
                                    <div class="flex items-center gap-1.5">
                                        <i :class="slotProps.option.icon || 'pi pi-envelope'" class="text-xs" />
                                        <span>{{ slotProps.option.name }}</span>
                                    </div>
                                </template>
                            </Select>
                            <InputText v-model="editForm.email" type="email" class="flex-1 text-sm font-mono" style="min-width: 200px" />
                        </div>
                        <InputText v-model="editForm.notes" placeholder="Observação (opcional)" class="w-full text-xs" :maxlength="200" />
                    </div>
                    <div class="flex items-center gap-0.5 shrink-0">
                        <Button icon="pi pi-check" severity="primary" size="small" class="h-7 w-7" v-tooltip.top="'Salvar'" :loading="api.saving.value" @click="saveEdit(email)" />
                        <Button icon="pi pi-times" severity="secondary" text size="small" class="h-7 w-7" v-tooltip.top="'Cancelar'" :disabled="api.saving.value" @click="cancelEdit" />
                    </div>
                </template>
            </div>
        </div>

        <div v-if="showAddForm" class="flex flex-col gap-2 p-2 rounded-md border border-dashed border-[var(--primary-color)]/50 bg-[var(--primary-color)]/5">
            <div class="flex items-center gap-1.5 flex-wrap">
                <Select
                    v-model="newForm.contact_email_type_id"
                    :options="api.types.value"
                    optionLabel="name"
                    optionValue="id"
                    class="text-xs"
                    style="width: 140px"
                    appendTo="body"
                >
                    <template #option="slotProps">
                        <div class="flex items-center gap-1.5">
                            <i :class="slotProps.option.icon || 'pi pi-envelope'" class="text-xs" />
                            <span>{{ slotProps.option.name }}</span>
                        </div>
                    </template>
                </Select>
                <InputText v-model="newForm.email" type="email" placeholder="nome@exemplo.com" class="flex-1 text-sm font-mono" style="min-width: 200px" autofocus />
            </div>
            <InputText v-model="newForm.notes" placeholder="Observação (opcional)" class="w-full text-xs" :maxlength="200" />
            <div class="flex items-center gap-1 justify-end">
                <Button label="Cancelar" severity="secondary" text size="small" :disabled="api.saving.value" @click="cancelAddForm" />
                <Button label="Adicionar" icon="pi pi-check" size="small" :loading="api.saving.value" :disabled="!newForm.contact_email_type_id || !newForm.email.trim()" @click="submitAddForm" />
            </div>
        </div>

        <Button
            v-if="!readonly && !showAddForm"
            label="Adicionar email"
            icon="pi pi-plus"
            severity="secondary"
            outlined
            size="small"
            class="self-start rounded-full"
            :disabled="!props.entityId"
            v-tooltip.right="!props.entityId ? 'Salve o cadastro primeiro pra adicionar emails' : null"
            @click="openAddForm"
        />
    </div>
</template>
