<template>
  <div class="p-8">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-3xl font-bold">Product Management (Admin)</h1>
      <button @click="showAddModal = true" class="bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-3 rounded-lg hover:shadow-lg">
        ➕ Add Product
      </button>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <input v-model="filters.search" @input="fetchProducts" placeholder="Search..." class="px-4 py-2 border rounded-lg">
        <select v-model="filters.category_id" @change="fetchProducts" class="px-4 py-2 border rounded-lg">
          <option value="">All Categories</option>
          <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
        </select>
        <select v-model="filters.restaurant_id" @change="fetchProducts" class="px-4 py-2 border rounded-lg">
          <option value="">All Restaurants</option>
          <option v-for="r in restaurants" :key="r.id" :value="r.id">{{ r.name }}</option>
        </select>
        <select v-model="filters.status" @change="fetchProducts" class="px-4 py-2 border rounded-lg">
          <option value="">All Status</option>
          <option value="pending">Pending Approval</option>
          <option value="approved">Approved</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
      </div>
    </div>

    <!-- Products Table -->
    <div class="bg-white rounded-lg shadow overflow-x-auto mb-4">
      <table class="w-full">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-6 py-3 text-left">Image</th>
            <th class="px-6 py-3 text-left">Product</th>
            <th class="px-6 py-3 text-left">Restaurant</th>
            <th class="px-6 py-3 text-left">Category</th>
            <th class="px-6 py-3 text-left">Price</th>
            <th class="px-6 py-3 text-left">Stock</th>
            <th class="px-6 py-3 text-left">Status</th>
            <th class="px-6 py-3 text-right">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="product in products" :key="product.id" class="border-t hover:bg-gray-50">
            <td class="px-6 py-4">
              <img v-if="product.image" :src="`/storage/${product.image}`" class="w-16 h-16 object-cover rounded">
              <div v-else class="w-16 h-16 bg-gray-200 rounded flex items-center justify-center">📷</div>
            </td>
            <td class="px-6 py-4">
              <div class="font-medium">{{ product.name }}</div>
              <div class="text-xs text-gray-500">{{ product.variations?.length || 0 }} variations</div>
            </td>
            <td class="px-6 py-4">{{ product.restaurant?.name }}</td>
            <td class="px-6 py-4">{{ product.category?.name }}</td>
            <td class="px-6 py-4">
              <div>Rs {{ product.price }}</div>
              <div v-if="product.discount_price" class="text-xs text-green-600">-Rs {{ product.discount_price }}</div>
            </td>
            <td class="px-6 py-4">{{ product.stock_quantity }}</td>
            <td class="px-6 py-4">
              <div class="flex flex-col gap-1">
                <span v-if="!product.is_approved" class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-xs">Pending</span>
                <span v-if="product.is_approved" class="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">Approved</span>
                <span :class="product.is_active ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'" class="px-2 py-1 rounded text-xs">
                  {{ product.is_active ? 'Active' : 'Inactive' }}
                </span>
              </div>
            </td>
            <td class="px-6 py-4 text-right">
              <div class="flex flex-col gap-2">
                <button v-if="!product.is_approved" @click="approveProduct(product.id)" class="text-green-600 hover:text-green-800 text-sm">✓ Approve</button>
                <button v-if="product.is_approved" @click="rejectProduct(product.id)" class="text-orange-600 hover:text-orange-800 text-sm">✗ Reject</button>
                <button @click="toggleStatus(product)" class="text-blue-600 hover:text-blue-800 text-sm">
                  {{ product.is_active ? 'Deactivate' : 'Activate' }}
                </button>
                <button @click="deleteProduct(product.id)" class="text-red-600 hover:text-red-800 text-sm">Delete</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <div v-if="pagination.last_page > 1" class="bg-white rounded-lg shadow p-4 flex justify-between items-center">
      <button @click="changePage(pagination.current_page - 1)" :disabled="pagination.current_page === 1" 
        class="px-4 py-2 bg-gray-200 rounded disabled:opacity-50">Previous</button>
      <div class="flex gap-2">
        <button v-for="page in visiblePages" :key="page" @click="changePage(page)"
          :class="page === pagination.current_page ? 'bg-blue-600 text-white' : 'bg-gray-200'"
          class="px-3 py-1 rounded">{{ page }}</button>
      </div>
      <button @click="changePage(pagination.current_page + 1)" :disabled="pagination.current_page === pagination.last_page"
        class="px-4 py-2 bg-gray-200 rounded disabled:opacity-50">Next</button>
    </div>

    <!-- Add Product Modal -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div class="bg-white rounded-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b px-6 py-4 flex justify-between items-center">
          <h2 class="text-2xl font-bold">Add Product</h2>
          <button @click="closeAddModal" class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>

        <form @submit.prevent="saveProduct" class="p-6 space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Product Name *</label>
            <input v-model="form.name" required class="w-full px-4 py-2 border rounded-lg">
          </div>

          <div>
            <label class="block text-sm font-medium mb-1">Category *</label>
            <select v-model="form.category_id" required class="w-full px-4 py-2 border rounded-lg">
              <option value="">Select Category</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium mb-1">Description</label>
            <textarea v-model="form.description" rows="3" class="w-full px-4 py-2 border rounded-lg"></textarea>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Price (Rs) *</label>
              <input v-model="form.price" type="number" step="0.01" required class="w-full px-4 py-2 border rounded-lg">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Discount Price (Rs)</label>
              <input v-model="form.discount_price" type="number" step="0.01" class="w-full px-4 py-2 border rounded-lg">
            </div>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Stock Quantity</label>
              <input v-model="form.stock_quantity" type="number" class="w-full px-4 py-2 border rounded-lg">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Prep Time (min)</label>
              <input v-model="form.preparation_time" type="number" class="w-full px-4 py-2 border rounded-lg">
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium mb-1">Product Image</label>
            <input type="file" @change="handleImageUpload" accept="image/*" class="w-full px-4 py-2 border rounded-lg">
            <div v-if="imagePreview" class="mt-2 relative inline-block">
              <img :src="imagePreview" class="w-32 h-32 object-cover rounded">
              <button type="button" @click="removeImage" class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600">&times;</button>
            </div>
          </div>

          <div class="flex gap-4">
            <label class="flex items-center gap-2">
              <input v-model="form.is_vegetarian" type="checkbox" class="w-4 h-4">
              <span class="text-sm">Vegetarian</span>
            </label>
            <label class="flex items-center gap-2">
              <input v-model="form.is_spicy" type="checkbox" class="w-4 h-4">
              <span class="text-sm">Spicy</span>
            </label>
          </div>

          <div class="border-t pt-4">
            <div class="flex justify-between items-center mb-2">
              <h3 class="font-bold">Variations</h3>
              <button type="button" @click="addVariation" class="text-blue-600 text-sm">+ Add</button>
            </div>
            <div v-for="(v, i) in form.variations" :key="i" class="flex gap-2 mb-2">
              <input v-model="v.name" placeholder="Name" class="flex-1 px-3 py-2 border rounded">
              <input v-model="v.price" type="number" step="0.01" placeholder="Price" class="w-32 px-3 py-2 border rounded">
              <button type="button" @click="form.variations.splice(i, 1)" class="text-red-600 px-3">×</button>
            </div>
          </div>

          <div class="border-t pt-4">
            <div class="flex justify-between items-center mb-2">
              <h3 class="font-bold">Add-ons</h3>
              <button type="button" @click="addAddon" class="text-blue-600 text-sm">+ Add</button>
            </div>
            <div v-for="(a, i) in form.addons" :key="i" class="flex gap-2 mb-2">
              <input v-model="a.name" placeholder="Name" class="flex-1 px-3 py-2 border rounded">
              <input v-model="a.price" type="number" step="0.01" placeholder="Price" class="w-32 px-3 py-2 border rounded">
              <button type="button" @click="form.addons.splice(i, 1)" class="text-red-600 px-3">×</button>
            </div>
          </div>

          <div class="flex gap-3 pt-4">
            <button type="button" @click="closeAddModal" class="flex-1 px-6 py-3 border rounded-lg">Cancel</button>
            <button type="submit" class="flex-1 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import api from '../../services/api';

const products = ref([]);
const categories = ref([]);
const restaurants = ref([]);
const filters = ref({ search: '', category_id: '', restaurant_id: '', status: '' });
const pagination = ref({ current_page: 1, last_page: 1 });
const showAddModal = ref(false);
const imagePreview = ref(null);
const form = ref({
  name: '', category_id: '', description: '', price: 0, discount_price: null,
  stock_quantity: 100, preparation_time: 15, image: null, is_vegetarian: false,
  is_spicy: false, variations: [], addons: []
});

const fetchProducts = async (page = 1) => {
  const { data } = await api.get('/admin/products', { params: { ...filters.value, page } });
  products.value = data.data;
  pagination.value = {
    current_page: data.current_page,
    last_page: data.last_page,
    total: data.total
  };
};

const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, pagination.value.current_page - 2);
  const end = Math.min(pagination.value.last_page, pagination.value.current_page + 2);
  for (let i = start; i <= end; i++) pages.push(i);
  return pages;
});

const changePage = (page) => {
  if (page >= 1 && page <= pagination.value.last_page) fetchProducts(page);
};

const fetchCategories = async () => {
  const { data } = await api.get('/admin/categories');
  categories.value = data.data || data;
};

const fetchRestaurants = async () => {
  const { data } = await api.get('/admin/restaurants');
  restaurants.value = data.data || data;
};

const approveProduct = async (id) => {
  await api.post(`/admin/products/${id}/approve`);
  fetchProducts();
};

const rejectProduct = async (id) => {
  await api.post(`/admin/products/${id}/reject`);
  fetchProducts();
};

const toggleStatus = async (product) => {
  await api.post(`/admin/products/${product.id}/toggle-status`);
  product.is_active = !product.is_active;
};

const deleteProduct = async (id) => {
  if (confirm('Delete this product permanently?')) {
    await api.delete(`/admin/products/${id}`);
    fetchProducts();
  }
};

const saveProduct = async () => {
  const formData = new FormData();
  Object.keys(form.value).forEach(key => {
    if (key === 'variations' || key === 'addons') {
      formData.append(key, JSON.stringify(form.value[key]));
    } else if (key === 'image' && form.value[key]) {
      formData.append(key, form.value[key]);
    } else if (form.value[key] !== null && key !== 'image') {
      formData.append(key, form.value[key]);
    }
  });

  try {
    await api.post('/manager/products', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    closeAddModal();
    fetchProducts();
  } catch (error) {
    alert(error.response?.data?.message || 'Failed to save product');
  }
};

const handleImageUpload = (e) => {
  const file = e.target.files[0];
  if (file) {
    form.value.image = file;
    const reader = new FileReader();
    reader.onload = (e) => imagePreview.value = e.target.result;
    reader.readAsDataURL(file);
  }
};

const addVariation = () => form.value.variations.push({ name: '', price: 0 });
const addAddon = () => form.value.addons.push({ name: '', price: 0 });

const removeImage = () => {
  form.value.image = null;
  imagePreview.value = null;
};

const closeAddModal = () => {
  showAddModal.value = false;
  imagePreview.value = null;
  form.value = {
    name: '', category_id: '', description: '', price: 0, discount_price: null,
    stock_quantity: 100, preparation_time: 15, image: null, is_vegetarian: false,
    is_spicy: false, variations: [], addons: []
  };
};

onMounted(() => {
  fetchProducts();
  fetchCategories();
  fetchRestaurants();
});
</script>
