<template>
    <div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 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">
          <!-- Nama -->
          <div class="mb-3">
            <label class="block font-medium mb-1">Nama</label>
            <input
              v-model.trim="form.nama"
              type="text"
              class="border rounded w-full p-2 focus:ring focus:ring-blue-300"
              required
            />
          </div>

          <!-- Password -->
          <div class="mb-3">
            <label class="block font-medium mb-1">Password</label>
            <input
              v-model="form.password"
              type="password"
              class="border rounded w-full p-2 focus:ring focus:ring-blue-300"
              required
            />
          </div>

          <!-- Peran -->
          <div class="mb-3">
            <label class="block font-medium mb-1">Peran</label>
            <select
              v-model="form.role"
              class="border rounded w-full p-2 focus:ring focus:ring-blue-300"
              required
            >
              <option disabled value="">-- Pilih Peran --</option>
              <option value="owner">Owner</option>
              <option value="kasir">Kasir</option>
            </select>
          </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 -->
        <p v-if="errorMessage" class="text-red-500 text-sm mt-3">
          {{ errorMessage }}
        </p>
      </div>
    </div>
  </template>

  <script>
  import axios from "axios";

  export default {
    name: "CreateAkun",
    data() {
      return {
        form: {
          nama: "",
          password: "",
          role: "",
        },
        errorMessage: "",
      };
    },
    methods: {
      async createAkun() {
        try {
          await axios.post("api/user", this.form);

          // reset form
          this.form = { nama: "", password: "", role: "" };

          // tutup modal dan refresh data
          this.$emit("refresh");
          this.$emit("close");
        } catch (err) {
          this.errorMessage =
            err.response?.data?.message || "Gagal menambah akun.";
          console.error("Gagal tambah akun:", err);
        }
      },
    },
  };
  </script>
