<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/agenda/components/InsurancePlanQuickCreateDialog.vue
| Data: 2026-05-04
|
| Mini-dialog pra cadastrar convênio SEM sair do AgendaEventDialog.
| Mesmo pattern do ServiceQuickCreateDialog — emite `created` com a row
| inserida, parent pré-seleciona.
|
| Campos mínimos (obrigatórios no schema):
|   name, owner_id, tenant_id
| Opcionais:
|   default_value (valor base sugerido), notes
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, watch } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useInsurancePlans } from '@/features/insurance/composables/useInsurancePlans';

const props = defineProps({
    modelValue: { type: Boolean, default: false },
    // ownerId mantido por compat — repository sempre injeta owner_id = auth.uid() logado.
    // Nos fluxos atuais (AgendaEventDialog), o usuário logado já é o owner.
    ownerId: { type: String, default: '' },
    initialName: { type: String, default: '' }
});
const emit = defineEmits(['update:modelValue', 'created']);

const toast = useToast();
const insuranceStore = useInsurancePlans();

const visible = ref(props.modelValue);
watch(() => props.modelValue, (v) => { visible.value = v; });
watch(visible, (v) => emit('update:modelValue', v));

const form = ref({
    name: '',
    default_value: null,
    notes: ''
});
const saving = ref(false);

watch(() => props.modelValue, (v) => {
    if (v) {
        form.value = {
            name: props.initialName || '',
            default_value: null,
            notes: ''
        };
    }
});

const canSave = () => !!form.value.name?.trim();

async function onSave() {
    if (!canSave()) return;
    saving.value = true;
    try {
        // Repository injeta owner_id + tenant_id, sanitiza, e faz uniqueness check.
        const data = await insuranceStore.create({
            name: form.value.name,
            default_value: form.value.default_value,
            notes: form.value.notes
        });
        toast.add({ severity: 'success', summary: 'Convênio criado', life: 2200 });
        emit('created', data);
        visible.value = false;
    } catch (e) {
        const isDup = /existe um convênio/i.test(e?.message || '');
        toast.add({
            severity: isDup ? 'warn' : 'error',
            summary: isDup ? 'Nome em uso' : 'Falha ao criar convênio',
            detail: e?.message || 'Erro inesperado',
            life: 4000
        });
    } finally {
        saving.value = false;
    }
}
</script>

<template>
    <Dialog
        v-model:visible="visible"
        modal
        :draggable="false"
        :closable="!saving"
        header="Novo convênio"
        class="w-[94vw] max-w-md"
    >
        <div class="flex flex-col gap-3 pt-1">
            <FloatLabel variant="on">
                <InputText id="ins-name" v-model="form.name" class="w-full" autofocus maxlength="120" />
                <label for="ins-name">Nome do convênio *</label>
            </FloatLabel>

            <FloatLabel variant="on">
                <InputNumber
                    id="ins-value"
                    v-model="form.default_value"
                    mode="currency"
                    currency="BRL"
                    locale="pt-BR"
                    :min="0"
                    :max="999999"
                    class="w-full"
                />
                <label for="ins-value">Valor base sugerido (opcional)</label>
            </FloatLabel>

            <FloatLabel variant="on">
                <Textarea id="ins-notes" v-model="form.notes" class="w-full" rows="2" autoResize maxlength="500" />
                <label for="ins-notes">Observações (opcional)</label>
            </FloatLabel>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" outlined class="rounded-full" :disabled="saving" @click="visible = false" />
            <Button
                label="Criar convênio"
                icon="pi pi-check"
                :loading="saving"
                :disabled="!canSave()"
                class="rounded-full"
                @click="onSave"
            />
        </template>
    </Dialog>
</template>
