<template>
    <div
      v-if="isOpen"
      class="fixed inset-0 bg-black/65  flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg shadow-lg w-full max-w-lg p-6 relative">
        <h2 class="text-xl font-bold mb-4">Ubah Sales</h2>

        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">Nama Sales</label>
            <InputField v-model="form.nama" type="text" class="w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-[#c6a77d] focus:outline-none" required />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">No HP</label>
            <InputField v-model="form.no_hp" type="text" class="w-full px-3 py-2 border rounded-md focus:ring-2 focus:ring-[#c6a77d] focus:outline-none" required />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">Alamat</label>
            <textarea
              v-model="form.alamat"
              class="mt-1 block w-full rounded-md shadow-sm sm:text-sm bg-A text-D border-B focus:border-C focus:ring focus:ring-D focus:ring-opacity-50 p-2"
              required
            ></textarea>
          </div>

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

  <script setup>
  import { ref, watch } from "vue";
  import axios from "axios";
import InputField from "./InputField.vue";

  const props = defineProps({
    isOpen: Boolean,
    sales: Object,
  });

  const emit = defineEmits(["close"]);

  const form = ref({
    nama: "",
    no_hp: "",
    alamat: "",
  });

  watch(
    () => props.sales,
    (val) => {
      if (val) {
        form.value = { ...val };
      }
    },
    { immediate: true }
  );

  const handleSubmit = async () => {
    try {
      await axios.put(`/api/sales/${props.sales.id}`, form.value);
      emit("close");
    } catch (error) {
      console.error("Error updating sales:", error);
    }
  };
  </script>
