<template>
  <div class="category-management">
    <div class="page-header">
      <h1>🗂️ Category Management</h1>
      <div class="header-actions">
        <button @click="showProductModal = true" class="btn-secondary">+ Add Product</button>
        <button @click="showAddModal = true" class="btn-primary">+ Add Category</button>
      </div>
    </div>

    <div class="table-card">
      <table class="data-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Variations</th>
            <th>Addons</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="category in categories" :key="category.id">
            <td>{{ category.name }}</td>
            <td>
              <span v-if="category.variations && category.variations.length" class="variations">
                {{ category.variations.map(v => v.name).join(', ') }}
              </span>
              <span v-else class="no-variations">No variations</span>
            </td>
            <td>
              <span v-if="category.addons && category.addons.length" class="variations">
                {{ category.addons.map(a => a.name).join(', ') }}
              </span>
              <span v-else class="no-variations">No addons</span>
            </td>
            <td>
              <div class="action-buttons">
                <button @click="editCategory(category)" class="btn-icon" title="Edit">✏️</button>
                <button @click="manageVariations(category)" class="btn-icon" title="Manage Variations">⚙️</button>
                <button @click="manageAddons(category)" class="btn-icon" title="Manage Addons">🧩</button>
                <button @click="deleteCategory(category.id)" class="btn-icon" title="Delete">🗑️</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Add/Edit Category Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
      <div class="modal-content-small">
        <div class="modal-header">
          <h2>{{ selectedCategory ? 'Edit Category' : 'Add Category' }}</h2>
          <button @click="showAddModal = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Category Name *</label>
            <input v-model="form.name" type="text" required class="form-control" placeholder="Enter category name">
          </div>
          <div class="form-actions">
            <button @click="showAddModal = false" class="btn-cancel">Cancel</button>
            <button @click="saveCategory" class="btn-save">{{ selectedCategory ? 'Update' : 'Save' }}</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Manage Variations Modal -->
    <div v-if="showVariationsModal" class="modal-overlay" @click.self="showVariationsModal = false">
      <div class="modal-content">
        <div class="modal-header">
          <h2>⚙️ Manage Variations - {{ selectedCategory?.name }}</h2>
          <button @click="showVariationsModal = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="add-variation">
            <input v-model="newVariation.name" type="text" placeholder="Variation name" class="form-control">
            <input v-model="newVariation.price" type="number" step="0.01" placeholder="Price (Rs.)" class="form-control" style="max-width: 150px;">
            <button @click="addVariation" class="btn-add">+ Add</button>
          </div>
          <div class="variations-list">
            <div v-for="variation in variations" :key="variation.id" class="variation-item">
              <span class="variation-name">{{ variation.name }}</span>
              <span class="variation-price">Rs. {{ variation.price }}</span>
              <button @click="deleteVariation(variation.id)" class="btn-delete">×</button>
            </div>
            <div v-if="!variations.length" class="no-data">No variations added yet</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Manage Addons Modal -->
    <div v-if="showAddonsModal" class="modal-overlay" @click.self="showAddonsModal = false">
      <div class="modal-content">
        <div class="modal-header">
          <h2>🧩 Manage Addons - {{ selectedCategory?.name }}</h2>
          <button @click="showAddonsModal = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="add-variation">
            <input v-model="newAddon.name" type="text" placeholder="Addon name (e.g., Extra Cheese)" class="form-control">
            <button @click="addAddon" class="btn-add">+ Add</button>
          </div>
          <div class="variations-list">
            <div v-for="addon in addons" :key="addon.id" class="variation-item">
              <span class="variation-name">{{ addon.name }}</span>
              <button @click="deleteAddon(addon.id)" class="btn-delete">×</button>
            </div>
            <div v-if="!addons.length" class="no-data">No addons added yet</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Product Modal -->
    <div v-if="showProductModal" class="modal-overlay" @click.self="showProductModal = false">
      <div class="modal-content-large">
        <div class="modal-header">
          <h2>🍔 Add Product</h2>
          <button @click="showProductModal = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-group">
              <label>Restaurant *</label>
              <select v-model="productForm.restaurant_id" class="form-control" required>
                <option value="">Select Restaurant</option>
                <option v-for="restaurant in restaurants" :key="restaurant.id" :value="restaurant.id">
                  {{ restaurant.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>Category *</label>
              <select v-model="productForm.category_id" @change="onCategoryChange" class="form-control" required>
                <option value="">Select Category</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
            </div>
          </div>
          <div class="form-group">
            <label>Product Name *</label>
            <input v-model="productForm.name" type="text" class="form-control" placeholder="Enter product name" required>
          </div>
          <div class="form-group">
            <label>Description</label>
            <textarea v-model="productForm.description" class="form-control" rows="3" placeholder="Enter product description"></textarea>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>Base Price (Rs.) {{ categoryVariations.length ? '' : '*' }}</label>
              <input v-model="productForm.price" type="number" step="0.01" class="form-control" placeholder="0.00" :required="!categoryVariations.length">
            </div>
            <div class="form-group">
              <label>Discount (Rs.)</label>
              <input v-model="productForm.discount" type="number" step="0.01" class="form-control" placeholder="0.00">
            </div>
          </div>
          <div class="form-group">
            <label>Product Image</label>
            <input type="file" @change="handleImageUpload" accept="image/*" class="form-control">
            <small class="form-hint">Max 3MB, 800x800 recommended</small>
            <div v-if="imagePreview" class="image-preview">
              <img :src="imagePreview" alt="Preview">
              <button @click="removeImage" class="btn-remove-img" type="button">×</button>
            </div>
          </div>
          <div v-if="categoryVariations.length" class="variations-section">
            <label class="section-label">📋 Category Variations - Set Prices & Discounts</label>
            <div class="variation-prices">
              <div v-for="variation in categoryVariations" :key="variation.id" class="variation-price-group">
                <label class="variation-label">{{ variation.name }}</label>
                <div class="price-discount-row">
                  <input v-model="productForm.variation_prices[variation.id]" type="number" step="0.01" class="form-control" placeholder="Price">
                  <input v-model="productForm.variation_discounts[variation.id]" type="number" step="0.01" class="form-control" placeholder="Discount">
                </div>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button @click="showProductModal = false" class="btn-cancel">Cancel</button>
            <button @click="saveProduct" class="btn-save">Save Product</button>
          </div>
        </div>
      </div>
    </div>

    <ConfirmModal
      :show="confirmModal.show"
      :title="confirmModal.title"
      :message="confirmModal.message"
      :icon="confirmModal.icon"
      :type="confirmModal.type"
      :confirmText="confirmModal.confirmText"
      @confirm="confirmModal.onConfirm"
      @cancel="confirmModal.show = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import api from '@/services/api'
import { useToast } from '@/composables/useToast'
import ConfirmModal from '../ConfirmModal.vue'

const { success: showSuccess, error: showError } = useToast()
const categories = ref([])
const restaurants = ref([])
const variations = ref([])
const addons = ref([])
const categoryVariations = ref([])
const showAddModal = ref(false)
const showVariationsModal = ref(false)
const showAddonsModal = ref(false)
const showProductModal = ref(false)
const selectedCategory = ref(null)
const newVariation = ref({ name: '', price: '' })
const newAddon = ref({ name: '' })
const form = reactive({ name: '' })
const productForm = reactive({
  restaurant_id: '',
  category_id: '',
  name: '',
  description: '',
  price: '',
  discount: 0,
  image: null,
  variation_prices: {},
  variation_discounts: {}
})
const imagePreview = ref(null)
const confirmModal = ref({
  show: false,
  title: '',
  message: '',
  icon: '',
  type: 'danger',
  confirmText: 'Delete',
  onConfirm: null
})

const loadCategories = async () => {
  try {
    const { data } = await api.get('/admin/categories')
    categories.value = data.data || data
    // Load addons for each category
    for (const category of categories.value) {
      try {
        const { data: addonsData } = await api.get(`/admin/categories/${category.id}/addons`)
        category.addons = addonsData.data || []
      } catch (error) {
        category.addons = []
      }
    }
  } catch (error) {
    showError('Failed to load categories')
  }
}

const loadRestaurants = async () => {
  try {
    const { data } = await api.get('/admin/restaurants')
    restaurants.value = data.data || data
  } catch (error) {
    showError('Failed to load restaurants')
  }
}

const editCategory = (category) => {
  selectedCategory.value = category
  form.name = category.name
  showAddModal.value = true
}

const saveCategory = async () => {
  if (!form.name.trim()) {
    showError('Please enter category name')
    return
  }
  try {
    if (selectedCategory.value) {
      await api.put(`/admin/categories/${selectedCategory.value.id}`, { name: form.name })
      showSuccess('Category updated successfully')
    } else {
      await api.post('/admin/categories', { name: form.name })
      showSuccess('Category added successfully')
    }
    showAddModal.value = false
    selectedCategory.value = null
    form.name = ''
    loadCategories()
  } catch (error) {
    showError(error.response?.data?.message || 'Failed to save category')
  }
}

const deleteCategory = (id) => {
  confirmModal.value = {
    show: true,
    title: 'Delete Category',
    message: 'Are you sure you want to delete this category? This action cannot be undone.',
    icon: '🗑️',
    type: 'danger',
    confirmText: 'Delete',
    onConfirm: () => confirmDelete(id)
  }
}

const confirmDelete = async (id) => {
  try {
    await api.delete(`/admin/categories/${id}`)
    showSuccess('Category deleted successfully')
    loadCategories()
  } catch (error) {
    showError('Failed to delete category')
  }
  confirmModal.value.show = false
}

const manageVariations = async (category) => {
  selectedCategory.value = category
  showVariationsModal.value = true
  await loadVariations(category.id)
}

const loadVariations = async (categoryId) => {
  try {
    const { data } = await api.get(`/admin/categories/${categoryId}/variations`)
    variations.value = data.data || []
  } catch (error) {
    showError('Failed to load variations')
  }
}

const addVariation = async () => {
  if (!newVariation.value.name.trim()) {
    showError('Please enter variation name')
    return
  }
  if (!newVariation.value.price || newVariation.value.price <= 0) {
    showError('Please enter a valid price')
    return
  }
  try {
    await api.post(`/admin/categories/${selectedCategory.value.id}/variations`, { 
      name: newVariation.value.name,
      price: newVariation.value.price
    })
    showSuccess('Variation added successfully')
    newVariation.value = { name: '', price: '' }
    loadVariations(selectedCategory.value.id)
    loadCategories()
  } catch (error) {
    showError(error.response?.data?.message || 'Failed to add variation')
  }
}

const deleteVariation = async (id) => {
  try {
    await api.delete(`/admin/category-variations/${id}`)
    showSuccess('Variation deleted successfully')
    loadVariations(selectedCategory.value.id)
    loadCategories()
  } catch (error) {
    showError('Failed to delete variation')
  }
}

const manageAddons = async (category) => {
  selectedCategory.value = category
  showAddonsModal.value = true
  await loadAddons(category.id)
}

const loadAddons = async (categoryId) => {
  try {
    const { data } = await api.get(`/admin/categories/${categoryId}/addons`)
    addons.value = data.data || []
  } catch (error) {
    showError('Failed to load addons')
  }
}

const addAddon = async () => {
  if (!newAddon.value.name.trim()) {
    showError('Please enter addon name')
    return
  }
  try {
    await api.post(`/admin/categories/${selectedCategory.value.id}/addons`, { 
      name: newAddon.value.name
    })
    showSuccess('Addon added successfully')
    newAddon.value = { name: '' }
    loadAddons(selectedCategory.value.id)
    loadCategories()
  } catch (error) {
    showError(error.response?.data?.message || 'Failed to add addon')
  }
}

const deleteAddon = async (id) => {
  try {
    await api.delete(`/admin/category-addons/${id}`)
    showSuccess('Addon deleted successfully')
    loadAddons(selectedCategory.value.id)
    loadCategories()
  } catch (error) {
    showError('Failed to delete addon')
  }
}

const onCategoryChange = async () => {
  categoryVariations.value = []
  productForm.variation_prices = {}
  productForm.variation_discounts = {}
  if (productForm.category_id) {
    try {
      const { data } = await api.get(`/admin/categories/${productForm.category_id}/variations`)
      categoryVariations.value = data.data || []
    } catch (error) {
      console.error('Failed to load category variations')
    }
  }
}

const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.size > 3 * 1024 * 1024) {
      showError('Image size must be less than 3MB')
      event.target.value = ''
      return
    }
    productForm.image = file
    imagePreview.value = URL.createObjectURL(file)
  }
}

const removeImage = () => {
  productForm.image = null
  imagePreview.value = null
  const fileInput = document.querySelector('input[type="file"]')
  if (fileInput) fileInput.value = ''
}

const saveProduct = async () => {
  if (!productForm.restaurant_id || !productForm.category_id || !productForm.name) {
    showError('Please fill all required fields')
    return
  }
  
  if (categoryVariations.value.length) {
    const allPricesFilled = categoryVariations.value.every(v => productForm.variation_prices[v.id] && productForm.variation_prices[v.id] > 0)
    if (!allPricesFilled) {
      showError('Please set prices for all variations')
      return
    }
  } else {
    if (!productForm.price) {
      showError('Please enter base price')
      return
    }
  }
  
  try {
    const formData = new FormData()
    formData.append('restaurant_id', productForm.restaurant_id)
    formData.append('category_id', productForm.category_id)
    formData.append('name', productForm.name)
    formData.append('description', productForm.description || '')
    formData.append('price', productForm.price || 0)
    formData.append('discount', productForm.discount || 0)
    if (productForm.image) {
      formData.append('image', productForm.image)
    }
    if (categoryVariations.value.length) {
      formData.append('variation_prices', JSON.stringify(productForm.variation_prices))
      formData.append('variation_discounts', JSON.stringify(productForm.variation_discounts))
    }

    await api.post('/admin/products', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    showSuccess('Product added successfully')
    showProductModal.value = false
    categoryVariations.value = []
    imagePreview.value = null
    Object.assign(productForm, {
      restaurant_id: '',
      category_id: '',
      name: '',
      description: '',
      price: '',
      discount: 0,
      image: null,
      variation_prices: {},
      variation_discounts: {}
    })
  } catch (error) {
    showError(error.response?.data?.message || 'Failed to add product')
  }
}

onMounted(() => {
  loadCategories()
  loadRestaurants()
})
</script>

<style scoped>
.category-management { padding: 2rem; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; }
.page-header h1 { margin: 0; font-size: 1.75rem; font-weight: 700; color: #1f2937; }
.header-actions { display: flex; gap: 0.75rem; }
.btn-primary { padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
.btn-secondary { padding: 0.75rem 1.5rem; background: #6b7280; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
.table-card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); overflow: hidden; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table thead { background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; }
.data-table th { padding: 1rem; text-align: left; font-weight: 600; font-size: 0.875rem; }
.data-table td { padding: 1rem; border-bottom: 1px solid #f3f4f6; font-size: 0.875rem; }
.variations { color: #6b7280; font-size: 0.875rem; }
.no-variations { color: #9ca3af; font-style: italic; }
.action-buttons { display: flex; gap: 0.5rem; }
.btn-icon { background: none; border: none; font-size: 1.25rem; cursor: pointer; padding: 0.25rem; }
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; padding: 1rem; }
.modal-content-small { background: white; border-radius: 12px; width: 100%; max-width: 400px; }
.modal-content { background: white; border-radius: 12px; width: 100%; max-width: 600px; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; }
.modal-content-large { background: white; border-radius: 12px; width: 100%; max-width: 700px; 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; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; }
.modal-header h2 { margin: 0; font-size: 1.25rem; }
.btn-close { background: none; border: none; font-size: 2rem; cursor: pointer; color: white; line-height: 1; }
.modal-body { padding: 1.5rem; overflow-y: auto; }
.form-group { margin-bottom: 1.25rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151; font-size: 0.875rem; }
.form-control { width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 0.9375rem; }
.form-hint { display: block; margin-top: 0.25rem; font-size: 0.75rem; color: #6b7280; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.form-actions { display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1.5rem; }
.btn-cancel { padding: 0.75rem 1.5rem; background: #e5e7eb; color: #374151; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; }
.btn-save { padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; }
.add-variation { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.add-variation .form-control { flex: 1; }
.btn-add { padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; white-space: nowrap; }
.variations-list { display: flex; flex-direction: column; gap: 0.5rem; }
.variation-item { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem; background: #f9fafb; border-radius: 8px; gap: 1rem; }
.variation-name { flex: 1; font-weight: 500; }
.variation-price { color: #ff6b35; font-weight: 600; font-size: 0.9375rem; }
.btn-delete { background: #ef4444; color: white; border: none; border-radius: 6px; width: 28px; height: 28px; cursor: pointer; font-size: 1.25rem; line-height: 1; }
.no-data { text-align: center; padding: 2rem; color: #9ca3af; font-style: italic; }
.variations-section { margin-top: 1.5rem; padding: 1rem; background: #f9fafb; border-radius: 8px; border: 2px dashed #e5e7eb; }
.section-label { display: block; font-weight: 600; color: #374151; font-size: 0.875rem; margin-bottom: 1rem; }
.variation-prices { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 1rem; }
.variation-price-group { display: flex; flex-direction: column; gap: 0.5rem; }
.variation-label { font-size: 0.8125rem; color: #6b7280; font-weight: 500; }
.price-discount-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; }
.price-discount-row .form-control { padding: 0.5rem; font-size: 0.875rem; }
.image-preview { margin-top: 1rem; border: 2px solid #e5e7eb; border-radius: 8px; overflow: hidden; max-width: 200px; position: relative; }
.image-preview img { width: 100%; height: auto; display: block; }
.btn-remove-img { position: absolute; top: 0.5rem; right: 0.5rem; background: #ef4444; color: white; border: none; border-radius: 50%; width: 28px; height: 28px; cursor: pointer; font-size: 1.25rem; line-height: 1; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
</style>
