<template>
  <!-- 標題 -->
  <h2 class="flex items-center text-xl sm:text-3xl px-3 pb-2 font-semibold text-black dark:text-white border-b-4 border-zinc-200">
    <div class="text-sm mr-2">:::</div>
    廠區管理
  </h2>
  
  <div class="sm:p-4 md:p-6">
    <!-- 搜尋框 + 按鈕區塊 -->
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4 gap-3 sm:gap-0 mt-4 sm:mt-0">
      <div>
        <button
        @click="openCreateModal"
        class="flex items-center justify-center bg-white text-lg text-blue-900 font-semibold px-2 py-1 rounded border border-blue-200  w-full sm:w-auto"
        >
        <PlusCircleIcon class=" w-7 h-7 text-blue-900 mr-1"/>新增 
        </button>
      </div>
      <div class="flex flex-col sm:flex-row gap-3 w-full sm:w-auto justify-between">
        <div class="relative w-full sm:w-64">
        <MagnifyingGlassIcon class="absolute left-2 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400"/>
        <input
          v-model="keyword"
          type="text"
          placeholder="搜尋"
          class="border rounded px-3 py-2 text-sm w-full sm:w-64 pl-8"
        />
        </div>
      </div>
    </div>

    <!-- 表格容器 -->
    <CustomTable
      :items="filteredFactory"
      :columns="[
        { label: '廠區名稱', field: 'name' },
      ]"
      v-model="selectedFactory"
      :rows="5"
      :selectable="false"
    >
      <template #action="{ data }">
        <button @click="edit(data)" class="text-blue-900 hover:underline text-sm rounded border border-gray-200 shadow px-1 py-1">
          <PencilIcon class="w-5 h-5"/>
        </button>
        <button @click="remove(data.id)" class="text-red-600 hover:underline text-sm rounded border border-gray-200 shadow px-1 py-1">
          <TrashIcon class="w-5 h-5"/>
        </button>
      </template>
    </CustomTable>


    <!-- Modal -->
    <FactoryModal
      v-model:show="showModal"
      :factory="selectedFactory"
      @saved="loadData"
    />

  </div>
</template>

<script setup>
import { MagnifyingGlassIcon , PlusCircleIcon , PencilIcon ,  } from '@heroicons/vue/24/solid'
import { TrashIcon } from '@heroicons/vue/24/outline'
import { ref, onMounted, computed, reactive } from 'vue'
import { api } from "@/global/axios";
import { useSwal } from "@/global/swal"
import CustomTable from '@/components/CustomTable.vue';
import FactoryModal from './Modal.vue'

const showModal = ref(false)
const selectedFactory = ref(null)
const keyword = ref('')
const filter = ref(false)
const search = reactive({
  name: '',
})

// 載入資料
const factory = ref([])
const loadData = async () => {
  try {
    const res = await api.get('/api/factory')
    factory.value = res.data?.data || []
  } catch (error) {
    await useSwal.error(error, '載入失敗')
  }
}

const openCreateModal = () => {
  selectedFactory.value = null
  showModal.value = true
}

// 編輯資料
const edit = (item) => {
  selectedFactory.value = { ...item }
  showModal.value = true
}

const remove = async (id) => {
  const result = await useSwal.confirm('確認刪除？')
  if (result.isConfirmed) {
    try {
      await api.delete(`/api/factory/${id}`)
      await useSwal.success('刪除成功') 
      loadData()
    } catch (error) {
      await useSwal.error(error.response.data.message)
    }
  }
}

onMounted(() => {
  loadData()
})

// 搜尋列過濾
const filteredFactory = computed(() => {
  if (!keyword.value.trim()) return factory.value
  const lowerKeyword = keyword.value.toLowerCase()
  return factory.value.filter(item =>
    item.name.toLowerCase().includes(lowerKeyword)
  )
})
</script>
