<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal-content">
      <div class="modal-header">
        <h2>{{ product ? 'Edit Global Product' : 'Add Global Product' }}</h2>
        <button @click="$emit('close')" class="close-btn">×</button>
      </div>
      <form @submit.prevent="handleSubmit" class="modal-body">
        <div class="form-group">
          <label>Category *</label>
          <select v-model="form.category_id" required class="form-input">
            <option value="">Select Category</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">{{ category.name }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>Name *</label>
          <input v-model="form.name" type="text" required class="form-input">
        </div>
        <div class="form-group">
          <label>Description</label>
          <textarea v-model="form.description" rows="3" class="form-input"></textarea>
        </div>
        <div class="form-group">
          <label>Image</label>
          <input @change="handleImageChange" type="file" accept="image/*" class="form-input">
          <img v-if="imagePreview" :src="imagePreview" alt="" class="image-preview">
        </div>
        <div class="form-actions">
          <button type="button" @click="$emit('close')" class="btn-cancel">Cancel</button>
          <button type="submit" class="btn-submit">{{ product ? 'Update' : 'Create' }}</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import api from '@/services/api'

export default {
  props: ['product'],
  emits: ['close', 'saved'],
  setup(props, { emit }) {
    const form = reactive({ category_id: '', name: '', description: '', image: null })
    const categories = ref([])
    const imagePreview = ref('')

    const loadCategories = async () => {
      const { data } = await api.get('/admin/products/categories')
      categories.value = data.data
    }

    const handleImageChange = (e) => {
      const file = e.target.files[0]
      if (file) {
        form.image = file
        imagePreview.value = URL.createObjectURL(file)
      }
    }

    const handleSubmit = async () => {
      try {
        const formData = new FormData()
        Object.keys(form).forEach(key => {
          if (form[key]) formData.append(key, form[key])
        })

        if (props.product) {
          await api.post(`/admin/global-products/${props.product.id}`, formData, { headers: { 'Content-Type': 'multipart/form-data' }, params: { _method: 'PUT' } })
          alert('Global product updated')
        } else {
          await api.post('/admin/global-products', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
          alert('Global product created')
        }
        emit('saved')
        emit('close')
      } catch (error) {
        alert(error.response?.data?.message || 'Failed to save')
      }
    }

    onMounted(() => {
      loadCategories()
      if (props.product) {
        Object.assign(form, props.product)
        if (props.product.image) imagePreview.value = `/storage/${props.product.image}`
      }
    })

    return { form, categories, imagePreview, handleImageChange, handleSubmit }
  }
}
</script>

<style scoped>
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal-content { background: white; border-radius: 16px; width: 90%; max-width: 600px; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; }
.modal-header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.modal-header h2 { margin: 0; font-size: 1.5rem; }
.close-btn { background: none; border: none; font-size: 2rem; cursor: pointer; color: #6b7280; }
.modal-body { padding: 1.5rem; overflow-y: auto; }
.form-group { margin-bottom: 1.5rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151; }
.form-input { width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 1rem; }
.image-preview { width: 100px; height: 100px; object-fit: cover; border-radius: 8px; margin-top: 0.5rem; }
.form-actions { display: flex; gap: 1rem; justify-content: flex-end; margin-top: 2rem; }
.btn-cancel { padding: 0.75rem 1.5rem; background: #6b7280; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; }
.btn-submit { padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; }
</style>
