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

        <form @submit.prevent="updateAkun" class="space-y-3">
            <label for="nama">Nama</label>
          <InputField
            v-model="form.nama"
            label="nama"
            type="text"
            :required="true"
            class="mb-3"
          />

          <div>
          <label for="password">Password</label>
          <InputField
            v-model="form.password"
            label="password"
            type="password"
            :required="false"
            class="mb-1"
          />
          <p class="text-sm">Kosongkan jika tidak ingin ubah password</p>
        </div>

            <label for="peran">Peran</label>
          <InputSelect
            v-model="form.role"
            label="peran"
            :options="[
              { value: 'owner', label: 'Owner' },
              { value: 'kasir', label: 'Kasir' }
            ]"
            :required="true"
            class="mb-3"
          />

          <div class="flex justify-end gap-2 mt-4">
            <button
              type="button"
              @click="$emit('close')"
              class="bg-gray-300 px-4 py-2 rounded"
            >
              Batal
            </button>
            <button
              type="submit"
              class="bg-blue-500 text-white px-4 py-2 rounded"
            >
              Ubah
            </button>
          </div>
        </form>
      </div>
    </div>
  </template>

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

  export default {
    props: {
      akun: {
        type: Object,
        required: true,
      },
    },
    components: { InputField, InputSelect },

    data() {
      return {
        form: {
          nama: this.akun.nama || "",
          password: "",
          role: this.akun.role || "",
        },
      };
    },
    watch: {
      akun: {
        handler(newVal) {
          if (newVal) {
            this.form = {
              nama: newVal.nama || "",
              password: "",
              role: newVal.role || "",
            };
          }
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      async updateAkun() {
        try {
          const payload = { ...this.form };
          if (!payload.password) delete payload.password;

          await axios.put(`/api/user/${this.akun.id}`, payload);

          this.$emit("refresh");
          this.$emit("close");
        } catch (err) {
          console.error("Gagal update akun:", err.response?.data || err.message);
        }
      },
    },
  };
  </script>
