<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/components/agenda/AgendaQuickAddDialog.vue
| Data: 2026
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, watch, nextTick } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';
import { useToast } from 'primevue/usetoast';
import { useServices } from '@/features/agenda/composables/useServices';
import { useInsurancePlans } from '@/features/agenda/composables/useInsurancePlans';

const props = defineProps({
    modelValue: { type: Boolean, default: false },
    type: { type: String, default: 'servico' },
    procedurePlanId: { type: String, default: null }
});

const emit = defineEmits(['update:modelValue', 'created']);
const toast = useToast();
const tenantStore = useTenantStore();

const { load: loadServices, save: saveService } = useServices();
const { plans, save: savePlan, savePlanService, load: loadInsurancePlans } = useInsurancePlans();

const visible = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v)
});

const ownerId = ref(null);
const saving = ref(false);
const addingProcedures = ref(false);
const selectedPlan = ref(null);
const newPlanId = ref(null);

const isServico = computed(() => props.type === 'servico');
const isConvenio = computed(() => props.type === 'convenio');
const isProcedureOnly = computed(() => !!props.procedurePlanId);

const servicoForm = ref({ name: '', price: null });
const convenioForm = ref({ name: '', notes: '' });
const proceduresForm = ref({ name: '', value: null });

async function loadOwnerId() {
    if (ownerId.value) return;
    const uid = tenantStore.user?.id || (await supabase.auth.getUser()).data?.user?.id;
    if (uid) ownerId.value = uid;
}

async function resetForms() {
    servicoForm.value = { name: '', price: null };
    convenioForm.value = { name: '', notes: '' };
    proceduresForm.value = { name: '', value: null };
    selectedPlan.value = null;
    newPlanId.value = null;
    addingProcedures.value = false;
}

watch(
    () => props.modelValue,
    async (open) => {
        if (!open) return;
        await nextTick();
        await loadOwnerId();
        resetForms();
        if (isServico.value) {
            await loadServices(ownerId.value);
        } else if (isConvenio.value || isProcedureOnly.value) {
            await loadInsurancePlans(ownerId.value);
            if (isProcedureOnly.value) {
                selectedPlan.value = plans.value.find((p) => p.id === props.procedurePlanId);
            }
        }
    }
);

async function handleSaveServico() {
    if (!servicoForm.value.name?.trim()) {
        toast.add({ severity: 'warn', summary: 'Campo obrigatório', detail: 'Nome do serviço é obrigatório.', life: 3000 });
        return;
    }
    if (servicoForm.value.price == null) {
        toast.add({ severity: 'warn', summary: 'Campo obrigatório', detail: 'Preço é obrigatório.', life: 3000 });
        return;
    }
    saving.value = true;
    try {
        await saveService({
            owner_id: ownerId.value,
            tenant_id: tenantStore.activeTenantId || null,
            name: servicoForm.value.name.trim(),
            description: null,
            price: servicoForm.value.price,
            duration_min: null
        });
        toast.add({ severity: 'success', summary: 'Criado', detail: 'Serviço criado com sucesso.', life: 3000 });
        emit('created', { type: 'servico' });
        visible.value = false;
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao criar.', life: 4000 });
    } finally {
        saving.value = false;
    }
}

async function handleSaveConvenio() {
    if (!convenioForm.value.name?.trim()) {
        toast.add({ severity: 'warn', summary: 'Campo obrigatório', detail: 'Nome do convênio é obrigatório.', life: 3000 });
        return;
    }
    saving.value = true;
    try {
        const newPlan = await savePlan({
            owner_id: ownerId.value,
            tenant_id: tenantStore.activeTenantId || null,
            name: convenioForm.value.name.trim(),
            notes: convenioForm.value.notes?.trim() || null
        });
        toast.add({ severity: 'success', summary: 'Criado', detail: 'Convênio criado com sucesso.', life: 3000 });
        newPlanId.value = newPlan?.id || null;
        selectedPlan.value = plans.value.find((p) => p.id === newPlan?.id);
        await loadInsurancePlans(ownerId.value);
        if (selectedPlan.value) {
            addingProcedures.value = true;
        } else {
            emit('created', { type: 'convenio' });
            visible.value = false;
        }
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao criar.', life: 4000 });
    } finally {
        saving.value = false;
    }
}

async function handleSaveProcedure() {
    if (!proceduresForm.value.name?.trim()) {
        toast.add({ severity: 'warn', summary: 'Campo obrigatório', detail: 'Nome do procedimento é obrigatório.', life: 3000 });
        return;
    }
    if (proceduresForm.value.value == null) {
        toast.add({ severity: 'warn', summary: 'Campo obrigatório', detail: 'Valor é obrigatório.', life: 3000 });
        return;
    }
    const planId = selectedPlan.value?.id || newPlanId.value;
    if (!planId) {
        toast.add({ severity: 'error', summary: 'Erro', detail: 'Convênio não encontrado.', life: 4000 });
        return;
    }
    saving.value = true;
    try {
        await savePlanService({
            insurance_plan_id: planId,
            name: proceduresForm.value.name.trim(),
            value: proceduresForm.value.value
        });
        toast.add({ severity: 'success', summary: 'Adicionado', detail: 'Procedimento adicionado.', life: 3000 });
        emit('created', { type: 'convenio' });
        visible.value = false;
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao adicionar.', life: 4000 });
    } finally {
        saving.value = false;
    }
}

function skipProcedures() {
    emit('created', { type: 'convenio' });
    visible.value = false;
}
</script>

<template>
    <Dialog
        v-model:visible="visible"
        modal
        :draggable="false"
        :closable="!saving"
        :dismissableMask="!saving"
        maximizable
        class="dc-dialog w-[36rem]"
        :breakpoints="{ '1199px': '90vw', '768px': '94vw' }"
        :pt="{
            header: { class: '!p-3 !rounded-t-[12px] border-b border-[var(--surface-border)] bg-[var(--surface-ground)]' },
            content: { class: '!p-3' },
            footer: { class: '!p-0 !rounded-b-[12px] border-t border-[var(--surface-border)] bg-[var(--surface-ground)]' },
            pcCloseButton: { root: { class: '!rounded-md hover:!text-red-500' } },
            pcMaximizeButton: { root: { class: '!rounded-md hover:!text-primary' } }
        }"
        pt:mask:class="backdrop-blur-xs"
    >
        <template #header>
            <div class="flex w-full items-center justify-between gap-3 px-1">
                <div class="flex items-center gap-3 min-w-0">
                    <div class="w-9 h-9 rounded-lg flex items-center justify-center text-white font-bold text-sm shrink-0" :style="{ background: isServico ? '#6366f1' : isProcedureOnly ? '#f59e0b' : '#22c55e' }">
                        <i :class="isServico ? 'pi pi-tag' : isProcedureOnly ? 'pi pi-list' : 'pi pi-id-card'" />
                    </div>
                    <div class="min-w-0">
                        <div class="text-base font-semibold truncate">
                            {{ isServico ? 'Novo Serviço' : addingProcedures || isProcedureOnly ? 'Adicionar Procedimento' : 'Novo Convênio' }}
                        </div>
                        <div class="text-xs opacity-50">
                            {{ isServico ? 'Cadastro rápido de serviço' : addingProcedures || isProcedureOnly ? 'Do convênio ' + (selectedPlan?.name || '') : 'Cadastro rápido de convênio' }}
                        </div>
                    </div>
                </div>
            </div>
        </template>

        <!-- ── Formulário Serviço ─────────────────────────────── -->
        <div v-if="isServico" class="flex flex-col gap-4">
            <FloatLabel variant="on">
                <IconField>
                    <InputIcon class="pi pi-tag" />
                    <InputText id="qadd-svc-name" v-model="servicoForm.name" class="w-full" variant="filled" :disabled="saving" />
                </IconField>
                <label for="qadd-svc-name">Nome do serviço *</label>
            </FloatLabel>

            <FloatLabel variant="on">
                <InputNumber id="qadd-svc-price" v-model="servicoForm.price" mode="currency" currency="BRL" locale="pt-BR" :min="0" :minFractionDigits="2" fluid :disabled="saving" />
                <label for="qadd-svc-price">Preço (R$) *</label>
            </FloatLabel>

            <Message severity="info" :closable="false">
                <span class="text-sm">O serviço estará disponível para seleção na agenda após ser criado.</span>
            </Message>
        </div>

        <!-- ── Formulário Convênio / Procedimento ─────────────── -->
        <div v-else-if="isConvenio || isProcedureOnly" class="flex flex-col gap-4">
            <template v-if="!addingProcedures && !isProcedureOnly">
                <FloatLabel variant="on">
                    <IconField>
                        <InputIcon class="pi pi-id-card" />
                        <InputText id="qadd-cnv-name" v-model="convenioForm.name" class="w-full" variant="filled" :disabled="saving" />
                    </IconField>
                    <label for="qadd-cnv-name">Nome do convênio *</label>
                </FloatLabel>

                <FloatLabel variant="on">
                    <InputText id="qadd-cnv-notes" v-model="convenioForm.notes" class="w-full" variant="filled" :disabled="saving" />
                    <label for="qadd-cnv-notes">Observações (opcional)</label>
                </FloatLabel>

                <Message severity="info" :closable="false">
                    <span class="text-sm">Após criar o convênio, você pode adicionar procedimentos.</span>
                </Message>
            </template>

            <template v-if="addingProcedures || isProcedureOnly">
                <div v-if="!isProcedureOnly" class="flex items-center gap-2 p-3 rounded-lg bg-surface-100">
                    <i class="pi pi-check-circle text-green-500" />
                    <span class="text-sm"
                        >Convênio <strong>{{ selectedPlan?.name || convenioForm.name }}</strong> criado!</span
                    >
                </div>

                <FloatLabel variant="on">
                    <InputText id="qadd-proc-name" v-model="proceduresForm.name" class="w-full" variant="filled" :disabled="saving" />
                    <label for="qadd-proc-name">Nome do procedimento *</label>
                </FloatLabel>

                <FloatLabel variant="on">
                    <InputNumber id="qadd-proc-value" v-model="proceduresForm.value" mode="currency" currency="BRL" locale="pt-BR" :min="0" :minFractionDigits="2" fluid :disabled="saving" />
                    <label for="qadd-proc-value">Valor (R$) *</label>
                </FloatLabel>

                <div v-if="!isProcedureOnly" class="flex items-center gap-2">
                    <Button label="Pular" severity="secondary" text size="small" :disabled="saving" @click="skipProcedures" />
                </div>
            </template>
        </div>

        <template #footer>
            <div class="flex items-center justify-end gap-2 px-3 py-3">
                <Button label="Cancelar" severity="secondary" text class="rounded-full hover:!text-red-500" :disabled="saving" @click="visible = false" />
                <Button v-if="isServico" label="Criar Serviço" icon="pi pi-check" class="rounded-full" :loading="saving" @click="handleSaveServico" />
                <template v-else-if="isConvenio || isProcedureOnly">
                    <Button v-if="!addingProcedures && !isProcedureOnly" label="Criar Convênio" icon="pi pi-check" class="rounded-full" :loading="saving" @click="handleSaveConvenio" />
                    <Button v-else label="Adicionar" icon="pi pi-check" class="rounded-full" :loading="saving" @click="handleSaveProcedure" />
                </template>
            </div>
        </template>
    </Dialog>
</template>
