<script setup>
import { ref } from 'vue';
import { useForm, usePage } 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 page = usePage();

// Assumindo que você passará a lista de tenants globalmente ou na página
// Se não tiver tenants na props, retorna array vazio para não quebrar
const tenants = page.props.tenants || [];

const form = useForm({
    name: '',
    email: '',
    password: '',
    password_confirmation: '',
    role: 'supervisor', // Padrão
    tenant_id: '',
});

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

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

const submit = () => {
    form.post(route('admin.users.store'), {
        preserveScroll: true,
        onSuccess: () => closeModal(),
    });
};

// Expõe a função para o Layout Pai chamar
defineExpose({ openModal });
</script>

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

            <form @submit.prevent="submit">

                <div class="mb-4">
                    <InputLabel for="name" value="Nome Completo" />
                    <TextInput id="name" v-model="form.name" type="text" class="mt-1 block w-full" required />
                    <InputError :message="form.errors.name" class="mt-2" />
                </div>

                <div class="mb-4">
                    <InputLabel for="email" value="E-mail" />
                    <TextInput id="email" v-model="form.email" type="email" class="mt-1 block w-full" required />
                    <InputError :message="form.errors.email" class="mt-2" />
                </div>

                <div class="mb-4">
                    <InputLabel for="tenant_id" value="Vincular ao Cliente (Tenant)" />
                    <select id="tenant_id" v-model="form.tenant_id"
                        class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
                        required>
                        <option value="" disabled>Selecione uma empresa...</option>
                        <option v-for="tenant in tenants" :key="tenant.id" :value="tenant.id">
                            {{ tenant.name }}
                        </option>
                    </select>
                    <InputError :message="form.errors.tenant_id" class="mt-2" />
                    <p v-if="tenants.length === 0" class="text-xs text-red-500 mt-1">
                        Nenhum tenant encontrado. Crie um tenant primeiro.
                    </p>
                </div>

                <div class="mb-4">
                    <InputLabel for="role" value="Função / Permissão" />
                    <select id="role" v-model="form.role"
                        class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
                        <option value="supervisor">Supervisor</option>
                        <option value="admin">Administrador</option>
                    </select>
                    <InputError :message="form.errors.role" class="mt-2" />
                </div>

                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <InputLabel for="password" value="Senha" />
                        <TextInput id="password" v-model="form.password" type="password" class="mt-1 block w-full"
                            required />
                        <InputError :message="form.errors.password" class="mt-2" />
                    </div>
                    <div>
                        <InputLabel for="password_confirmation" value="Confirmar Senha" />
                        <TextInput id="password_confirmation" v-model="form.password_confirmation" type="password"
                            class="mt-1 block w-full" required />
                    </div>
                </div>

                <div class="mt-6 flex justify-end gap-3">
                    <SecondaryButton @click="closeModal"> Cancelar </SecondaryButton>
                    <PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing">
                        Criar Usuário
                    </PrimaryButton>
                </div>
            </form>
        </div>
    </Modal>
</template>