<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/agenda/components/ServiceQuickCreateDialog.vue
| Data: 2026-05-04
|
| Mini-dialog pra cadastrar um serviço SEM sair do AgendaEventDialog.
| Pattern: usuário tá agendando, percebe que falta o serviço no catálogo,
| clica "+", preenche nome/duração/valor, salva → o emit `created` retorna
| o id pra que o parent pré-selecione no select de serviços.
|
| Campos mínimos (obrigatórios no schema):
|   name, price, owner_id
| Opcionais úteis:
|   duration_min, description
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, watch } from 'vue';
import { useToast } from 'primevue/usetoast';
import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import { useTenantStore } from '@/stores/tenantStore';

const props = defineProps({
    modelValue: { type: Boolean, default: false },
    ownerId: { type: String, default: '' },
    initialName: { type: String, default: '' }
});
const emit = defineEmits(['update:modelValue', 'created']);

const toast = useToast();
const tenantStore = useTenantStore();

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

const form = ref({
    name: '',
    price: null,
    duration_min: 50,
    description: ''
});
const saving = ref(false);

watch(() => props.modelValue, (v) => {
    if (v) {
        form.value = {
            name: props.initialName || '',
            price: null,
            duration_min: 50,
            description: ''
        };
    }
});

const canSave = () => !!form.value.name?.trim() && form.value.price != null && Number(form.value.price) >= 0;

async function onSave() {
    if (!canSave()) return;
    const ownerId = props.ownerId || (await supabase.auth.getUser()).data?.user?.id;
    const tid = tenantStore.activeTenantId || tenantStore.tenantId;
    if (!ownerId || !tid) {
        toast.add({ severity: 'error', summary: 'Sem contexto', detail: 'Owner ou tenant ausentes.', life: 3500 });
        return;
    }
    saving.value = true;
    try {
        const name = form.value.name.trim().slice(0, 120);

        // Nome unico por owner (case-insensitive) — espelha a validacao
        // do useServices.save() pra impedir duplicata tambem quando o
        // cadastro vem do quick-create dentro do AgendaEventDialog.
        const { data: dups, error: dupErr } = await tenantDb().from('services').select('id').eq('owner_id', ownerId).ilike('name', name).limit(1);
        if (dupErr) throw dupErr;
        if (dups && dups.length > 0) {
            toast.add({ severity: 'warn', summary: 'Nome em uso', detail: 'Já existe um serviço com este nome.', life: 3500 });
            saving.value = false;
            return;
        }

        const payload = {
            owner_id: ownerId,
            name,
            price: Number(form.value.price),
            duration_min: form.value.duration_min ? Number(form.value.duration_min) : null,
            description: form.value.description?.trim().slice(0, 500) || null,
            active: true
        };
        const { data, error } = await tenantDb().from('services').insert(payload).select().single();
        if (error) throw error;
        toast.add({ severity: 'success', summary: 'Serviço criado', life: 2200 });
        emit('created', data);
        visible.value = false;
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Falha ao criar serviço', 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 serviço"
        class="w-[94vw] max-w-md"
    >
        <div class="flex flex-col gap-3 pt-1">
            <FloatLabel variant="on">
                <InputText id="svc-name" v-model="form.name" class="w-full" autofocus maxlength="120" />
                <label for="svc-name">Nome do serviço *</label>
            </FloatLabel>

            <div class="grid grid-cols-2 gap-3">
                <FloatLabel variant="on">
                    <InputNumber
                        id="svc-price"
                        v-model="form.price"
                        mode="currency"
                        currency="BRL"
                        locale="pt-BR"
                        :min="0"
                        :max="999999"
                        class="w-full"
                    />
                    <label for="svc-price">Valor *</label>
                </FloatLabel>
                <FloatLabel variant="on">
                    <InputNumber
                        id="svc-duration"
                        v-model="form.duration_min"
                        :min="0"
                        :max="600"
                        :step="5"
                        suffix=" min"
                        class="w-full"
                    />
                    <label for="svc-duration">Duração</label>
                </FloatLabel>
            </div>

            <FloatLabel variant="on">
                <Textarea id="svc-desc" v-model="form.description" class="w-full" rows="2" autoResize maxlength="500" />
                <label for="svc-desc">Descrição (opcional)</label>
            </FloatLabel>
        </div>

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