<script setup>
import { ref } from 'vue';
import { useForm } from '@inertiajs/vue3';
import Modal from '@/Components/Modal.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import SecondaryButton from '@/Components/SecondaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import InputLabel from '@/Components/InputLabel.vue';
import InputError from '@/Components/InputError.vue';

const showModal = ref(false);

const form = useForm({
    name: '',
});

const openModal = () => {
    showModal.value = true;
};

const closeModal = () => {
    showModal.value = false;
    form.reset();
    form.clearErrors();
};

const submit = () => {
    form.post(route('tenants.store'), {
        preserveScroll: true,
        onSuccess: () => {
            closeModal();
            // Opcional: Se quiser resetar apenas se der sucesso
            form.reset();
        },
        onError: () => {
            // Se der erro (ex: nome duplicado), o modal continua aberto
            // e o InputError mostra a mensagem.
            document.getElementById('tenant_name').focus();
        }
    });
};
defineExpose({ openModal });
</script>

<template>
    <div>

        <Modal :show="showModal" @close="closeModal">
            <div class="p-6">
                <h2 class="text-lg font-medium text-gray-900 mb-4">
                    Cadastrar Novo Tenant
                </h2>

                <p class="text-sm text-gray-600 mb-6">
                    Informe o nome da empresa. A <strong>API Key</strong> será gerada automaticamente.
                </p>

                <form @submit.prevent="submit">

                    <div class="mb-6">
                        <InputLabel for="tenant_name" value="Nome da Empresa" />

                        <TextInput id="tenant_name" ref="nameInput" v-model="form.name" type="text"
                            class="mt-1 block w-full" placeholder="Ex: Call Center Filial Sul" required
                            @keyup.enter="submit" />

                        <InputError :message="form.errors.name" class="mt-2" />
                    </div>

                    <div class="mt-6 flex justify-end gap-3">
                        <SecondaryButton @click="closeModal">
                            Cancelar
                        </SecondaryButton>

                        <PrimaryButton class="bg-indigo-600 hover:bg-indigo-700"
                            :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
                            Gerar Tenant
                        </PrimaryButton>
                    </div>
                </form>
            </div>
        </Modal>
    </div>
</template>