<template>
    <div
        class="fixed inset-0 flex items-center justify-center bg-black/65 z-50"
    >
        <div class="bg-white rounded-lg p-6 w-96 shadow-lg">
            <h2 class="text-lg font-bold mb-4">Tambah Akun</h2>

            <form @submit.prevent="createAkun" class="space-y-3">
                <!-- Nama -->
                <div>
                    <label for="nama" class="block text-sm font-medium">Nama</label>
                    <InputField
                        v-model="form.nama"
                        id="nama"
                        type="text"
                        :required="true"
                        @input="clearError('nama')"
                    />
                    <p v-if="errors.nama" class="text-red-500 text-sm">{{ errors.nama }}</p>
                </div>

                <!-- Password -->
                <div>
                    <label for="password" class="block text-sm font-medium">Password</label>
                    <InputPassword
                        v-model="form.password"
                        id="password"
                        type="password"
                        :required="true"
                        @input="clearError('password')"
                    />
                    <p v-if="errors.password" class="text-red-500 text-sm">{{ errors.password }}</p>
                </div>

                <!-- Role -->
                <div>
                    <label for="peran" class="block text-sm font-medium">Peran</label>
                    <InputSelect
                        v-model="form.role"
                        :options="[
                            { value: 'owner', label: 'Owner' },
                            { value: 'kasir', label: 'Kasir' },
                        ]"
                        placeholder="-- Pilih Peran --"
                        @change="clearError('role')"
                    />
                    <p v-if="errors.role" class="text-red-500 text-sm">{{ errors.role }}</p>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end gap-2 mt-4">
                    <button
                        type="button"
                        @click="$emit('close')"
                        class="bg-gray-300 hover:bg-gray-400 px-4 py-2 rounded"
                    >
                        Batal
                    </button>
                    <button
                        type="submit"
                        class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded"
                    >
                        Simpan
                    </button>
                </div>
            </form>

            <!-- Error global -->
            <p v-if="errorMessage" class="text-red-500 text-sm mt-3">
                {{ errorMessage }}
            </p>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import InputField from "@/components/InputField.vue";
import InputSelect from "@/components/InputSelect.vue";
import InputPassword from "./InputPassword.vue";

export default {
    name: "CreateAkun",
    components: { InputField, InputSelect, InputPassword },
    data() {
        return {
            form: { nama: "", password: "", role: "" },
            errors: { nama: "", password: "", role: "" },
            errorMessage: "",
        };
    },
    methods: {
        clearError(field) {
            this.errors[field] = "";
            this.errorMessage = "";
        },
        validateForm() {
            let valid = true;
            this.errors = { nama: "", password: "", role: "" };

            if (!this.form.nama) {
                this.errors.nama = "Nama wajib diisi";
                valid = false;
            }
            if (!this.form.password) {
                this.errors.password = "Password wajib diisi";
                valid = false;
            } else if (this.form.password.length < 6) {
                this.errors.password = "Password minimal 6 karakter";
                valid = false;
            }
            if (!this.form.role) {
                this.errors.role = "Role wajib dipilih";
                valid = false;
            } else if (!["owner", "kasir"].includes(this.form.role)) {
                this.errors.role = "Role harus owner atau kasir";
                valid = false;
            }

            return valid;
        },
        async createAkun() {
            if (!this.validateForm()) return;

            try {
                await axios.post("/api/user", this.form, {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem("token")}`,
                    },
                });

                // reset form
                this.form = { nama: "", password: "", role: "" };
                this.$emit("refresh");
                this.$emit("close");
            } catch (err) {
                if (err.response?.status === 422 && err.response.data.errors) {
                    // tampilkan error validasi backend
                    const backendErrors = err.response.data.errors;
                    Object.keys(backendErrors).forEach((key) => {
                        this.errors[key] = backendErrors[key][0];
                    });
                } else {
                    this.errorMessage =
                        err.response?.data?.message || "Gagal menambah akun.";
                }
                console.error("Gagal tambah akun:", err);
            }
        },
    },
};
</script>
