<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">Tambah Sales</h2>

        <form @submit.prevent="handleSubmit" class="space-y-4">
          <!-- Nama -->
          <div>
            <label class="block text-sm font-medium text-gray-700">Nama Sales</label>
            <InputField v-model="form.nama" type="text" placeholder="Masukkan nama sales" required />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">No HP</label>
            <InputField v-model="form.no_hp" type="text" placeholder="Masukkan nomor HP" required />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">Alamat</label>
            <textarea
              v-model="form.alamat"
              placeholder="Masukkan 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/80"
            >
              Simpan
            </button>
          </div>
        </form>
      </div>
    </div>
  </template>

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

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

  const emit = defineEmits(["close", "saved"])

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

  const resetForm = () => {
    form.value = { nama: "", no_hp: "", alamat: "" }
  }

  const handleSubmit = async () => {
    try {
      await axios.post("/api/sales", form.value, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
        });
      resetForm()
      emit("saved")
      emit("close")
    } catch (error) {
      console.error("Error creating sales:", error)
    }
  }
  </script>
