<style scoped>
@keyframes fade-in {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
.animate-fade-in {
  animation: fade-in 0.2s ease-out;
}
</style>
<template>
  <div
    v-if="show"
    class="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center"
  >
    <div
      class="bg-white rounded-xl shadow-xl w-full max-w-md animate-fade-in"
    >
      <div class=" bg-slate-600 rounded-t-xl text-white">
        <div class="text-2xl font-semibold p-4 text-center">
            {{ factory?.id ? '修改廠區' : '新增廠區' }}
        </div>
      </div>
      <div class="space-y-4 my-6 p-4">
        <div class="flex flex-row whitespace-nowrap items-center mx-6 gap-2">
          <label class="text-base font-bold text-gray-700 ">廠區名稱</label>
          <input
            v-model="form.name"
            type="text"
            class=" text-base w-full border border-gray-300 rounded-md ml-2 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400"
            placeholder="請輸入廠區名稱"
          />
        </div>
      </div>

      <div class="flex justify-center gap-2 p-4 border-t-4 shadow font-semibold">
        <button
          @click="emit('update:show', false)"
          class="w-20 h-10 px-4 py-2 text-base bg-red-600 hover:bg-red-500 text-white rounded"
        >
          取消
        </button>
        <button
          @click="save"
          class="w-20 h-10 px-4 py-2 text-base bg-blue-800 hover:bg-blue-700 text-white rounded"
        >
          儲存
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from 'vue'
import { api } from "@/global/axios";
import { useSwal } from '@/global/swal'

const props = defineProps({
  show: Boolean,
  factory: Object
})
const emit = defineEmits(['update:show', 'saved'])

const form = reactive({
  name: '',
})

watch(() => props.factory, (val) => {
  if (val) Object.assign(form, val)
  else Object.assign(form, { name: '',})
})

const save = async () => {
  if (!form.name.trim()) {
    await useSwal.error('請確認「廠區名稱」已填寫', '資料未填寫完整')
    return
  }

  try {
    if (props.factory?.id) {
      await api.put(`/api/factory/${props.factory.id}`, form)
      await useSwal.success('廠區修改成功')
    } else {
      await api.post('/api/factory', form)
      await useSwal.success('廠區新增成功')
    }
    
    emit('saved')
    emit('update:show', false)
  } catch (e) {
    await useSwal.error('請稍後再試，或聯絡管理員', '儲存失敗')
  }
}
</script>
