<template>
  <div class="product-management">
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon">📦</div>
        <div class="stat-content">
          <h3>{{ stats.total_products }}</h3>
          <p>Total Products</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">⏳</div>
        <div class="stat-content">
          <h3>{{ stats.pending_verification }}</h3>
          <p>Pending</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-content">
          <h3>{{ stats.verified_products }}</h3>
          <p>Verified</p>
        </div>
      </div>
    </div>

    <div class="search-section">
      <input v-model="searchQuery" @input="handleSearch" type="text" placeholder="🔍 Search products..." class="search-input">
      <button @click="showAddProductModal = true" class="btn-primary">+ Add Product</button>
      <button @click="downloadTemplate" class="btn-secondary">📄 Download Template</button>
      <button @click="showImportModal = true" class="btn-secondary">📥 Import</button>
      <button @click="exportProducts" class="btn-secondary">📥 Export</button>
    </div>

    <div class="filters-card">
      <div class="filter-group">
        <label>Restaurant</label>
        <select v-model="filters.restaurant_id" @change="loadData" class="filter-select">
          <option value="">All Restaurants</option>
          <option v-for="restaurant in restaurants" :key="restaurant.id" :value="restaurant.id">{{ restaurant.name }}</option>
        </select>
      </div>
      <div class="filter-group">
        <label>Status</label>
        <select v-model="filters.status" @change="loadData" class="filter-select">
          <option value="">All Status</option>
          <option value="pending">Pending</option>
          <option value="verified">Verified</option>
          <option value="rejected">Rejected</option>
        </select>
      </div>
      <button @click="clearFilters" class="btn-clear">Clear</button>
    </div>

    <div class="table-card">
      <table class="data-table">
        <thead>
          <tr>
            <th>Image</th>
            <th>Name</th>
            <th>Restaurant</th>
            <th>Price</th>
            <th>Discount Price</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="product in products" :key="product.id">
            <td><img :src="getImageUrl(product.image)" alt="" class="product-img"></td>
            <td>{{ product.name }}</td>
            <td>{{ product.restaurant?.name }}</td>
            <td>Rs. {{ product.price }}</td>
            <td>{{ product.discount ? 'Rs. ' + product.discount : '-' }}</td>
            <td><span :class="['badge', product.is_available ? 'badge-success' : 'badge-danger']">{{ product.is_available ? 'Available' : 'Unavailable' }}</span></td>
            <td>
              <div class="action-buttons">
                <button @click="viewProduct(product)" class="btn-icon" title="View">👁️</button>
                <button @click="editProduct(product)" class="btn-icon" title="Edit">✏️</button>
                <button @click="toggleAvailability(product.id)" class="btn-icon" :title="product.is_available ? 'Disable' : 'Enable'">{{ product.is_available ? '🔴' : '🟢' }}</button>
                <button v-if="product.verification_status === 'pending'" @click="verifyProduct(product.id)" class="btn-icon" title="Verify">✅</button>
                <button v-if="product.verification_status === 'pending'" @click="openRejectModal(product)" class="btn-icon" title="Reject">❌</button>
                <button @click="deleteProduct(product.id)" class="btn-icon" title="Delete">🗑️</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination">
      <div class="pagination-info">Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total }} products</div>
      <div class="pagination-controls">
        <button @click="changePage(pagination.current_page - 1)" :disabled="pagination.current_page === 1" class="btn-page">Previous</button>
        <span class="page-info">Page {{ pagination.current_page }} of {{ pagination.last_page }}</span>
        <button @click="changePage(pagination.current_page + 1)" :disabled="pagination.current_page === pagination.last_page" class="btn-page">Next</button>
      </div>
    </div>

    <!-- Modals -->
    <ConfirmModal
      :show="confirmModal.show"
      :title="confirmModal.title"
      :message="confirmModal.message"
      :icon="confirmModal.icon"
      :type="confirmModal.type"
      :confirmText="confirmModal.confirmText"
      @confirm="confirmModal.onConfirm"
      @cancel="handleConfirmModalCancel"
    />
    <AddProductModal v-if="showAddProductModal" :product="selectedProduct" @close="showAddProductModal = false; selectedProduct = null" @saved="loadData(); loadStats()" />
    <ViewProductModal v-if="showViewModal" :product="selectedProduct" @close="showViewModal = false" />
    <RejectProductModal v-if="showRejectModal" :product="selectedProduct" @close="showRejectModal = false" @rejected="loadData" />
    
    <!-- Import Modal -->
    <div v-if="showImportModal" class="modal-overlay" @click.self="showImportModal = false">
      <div class="modal-content-small">
        <div class="modal-header">
          <h2>📥 Import Products</h2>
          <button @click="showImportModal = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Select Excel File</label>
            <input type="file" @change="handleFileUpload" accept=".xlsx,.xls,.csv" class="form-control">
            <small class="form-hint">Supported formats: .xlsx, .xls, .csv</small>
          </div>
          <div class="form-actions">
            <button @click="showImportModal = false" class="btn-cancel">Cancel</button>
            <button @click="importFile" :disabled="!importFile" class="btn-save">Import</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  components: { ConfirmModal, AddProductModal, ViewProductModal, RejectProductModal },
  setup() {
    const { success: showSuccess, error: showError } = useToast()
    const stats = reactive({ total_products: 0, pending_verification: 0, verified_products: 0 })
    const products = ref([])
    const restaurants = ref([])
    const searchQuery = ref('')
    const filters = reactive({ restaurant_id: '', status: '' })
    const pagination = reactive({ current_page: 1, last_page: 1, per_page: 20, total: 0, from: 0, to: 0 })
    const showAddProductModal = ref(false)
    const showViewModal = ref(false)
    const showRejectModal = ref(false)
    const showImportModal = ref(false)
    const selectedProduct = ref(null)
    const importFileData = ref(null)
    const confirmModal = ref({
      show: false,
      title: '',
      message: '',
      icon: '',
      type: 'info',
      confirmText: 'Confirm',
      onConfirm: null
    })

    const loadData = async () => {
      try {
        const params = { page: pagination.current_page, per_page: pagination.per_page, search: searchQuery.value, ...filters }
        const { data } = await api.get('/admin/products', { params })
        products.value = data.data.data
        Object.assign(pagination, { current_page: data.data.current_page, last_page: data.data.last_page, total: data.data.total, from: data.data.from, to: data.data.to })
      } catch (error) {
        showError('Failed to load products')
      }
    }

    const loadStats = async () => {
      try {
        const { data } = await api.get('/admin/products/dashboard-stats')
        Object.assign(stats, data.data)
      } catch (error) {
        console.error('Stats error:', error)
        // Set default values if stats fail to load
        Object.assign(stats, { total_products: 0, pending_verification: 0, verified_products: 0 })
      }
    }

    const loadRestaurants = async () => {
      try {
        const { data } = await api.get('/admin/products/restaurants')
        restaurants.value = data.data
      } catch (error) {
        console.error(error)
      }
    }

    const handleSearch = () => {
      pagination.current_page = 1
      loadData()
    }

    const clearFilters = () => {
      filters.restaurant_id = ''
      filters.status = ''
      searchQuery.value = ''
      loadData()
    }

    const changePage = (page) => {
      pagination.current_page = page
      loadData()
    }

    const viewProduct = (product) => {
      selectedProduct.value = product
      showViewModal.value = true
    }

    const editProduct = (product) => {
      selectedProduct.value = product
      showAddProductModal.value = true
    }

    const verifyProduct = (id) => {
      confirmModal.value = {
        show: true,
        title: 'Verify Product',
        message: 'Are you sure you want to verify this product?',
        icon: '✅',
        type: 'success',
        confirmText: 'Verify',
        onConfirm: () => confirmVerify(id)
      }
    }

    const confirmVerify = async (id) => {
      try {
        await api.post(`/admin/products/${id}/verify`)
        showSuccess('Product verified successfully')
        loadData()
        loadStats()
      } catch (error) {
        showError('Failed to verify product')
      }
      confirmModal.value.show = false
    }

    const openRejectModal = (product) => {
      selectedProduct.value = product
      showRejectModal.value = true
    }

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

    const confirmDelete = async (id) => {
      try {
        await api.delete(`/admin/products/${id}`)
        showSuccess('Product deleted successfully')
        loadData()
        loadStats()
      } catch (error) {
        showError('Failed to delete product')
      }
      confirmModal.value.show = false
    }

    const handleConfirmModalCancel = () => {
      confirmModal.value.show = false
    }

    const toggleAvailability = async (id) => {
      try {
        await api.post(`/admin/products/${id}/toggle-availability`)
        showSuccess('Product availability updated successfully')
        loadData()
      } catch (error) {
        showError('Failed to update availability')
      }
    }

    const exportProducts = () => {
      const params = new URLSearchParams(filters).toString()
      window.open(`/api/admin/products/export?${params}`, '_blank')
    }
    
    const downloadTemplate = async () => {
      try {
        const { data } = await api.get('/admin/products/download-template', {
          responseType: 'blob'
        })
        const url = window.URL.createObjectURL(new Blob([data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `product_import_template_${new Date().toISOString().split('T')[0]}.xls`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(url)
      } catch (error) {
        showError('Failed to download template')
      }
    }
    
    const handleFileUpload = (event) => {
      importFileData.value = event.target.files[0]
    }
    
    const importFile = async () => {
      if (!importFileData.value) {
        showError('Please select a file')
        return
      }
      
      try {
        const formData = new FormData()
        formData.append('file', importFileData.value)
        
        const { data } = await api.post('/admin/products/import', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        
        showSuccess(data.message)
        if (data.errors && data.errors.length) {
          console.warn('Import errors:', data.errors)
        }
        showImportModal.value = false
        importFileData.value = null
        loadData()
        loadStats()
      } catch (error) {
        showError(error.response?.data?.message || 'Failed to import products')
      }
    }

    const getImageUrl = (image) => {
      return image ? `/storage/${image}` : '/placeholder.png'
    }

    const getVerificationClass = (status) => {
      return status === 'verified' ? 'success' : status === 'rejected' ? 'danger' : 'warning'
    }

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

    return { stats, products, restaurants, searchQuery, filters, pagination, showAddProductModal, showViewModal, showRejectModal, showImportModal, selectedProduct, confirmModal, importFileData, loadData, loadStats, handleSearch, clearFilters, changePage, viewProduct, editProduct, toggleAvailability, verifyProduct, openRejectModal, deleteProduct, handleConfirmModalCancel, exportProducts, downloadTemplate, handleFileUpload, importFile, getImageUrl, getVerificationClass }
  }
}
</script>

<style scoped>
.product-management { padding: 0; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }
.stat-card { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); display: flex; gap: 1rem; align-items: center; }
.stat-icon { font-size: 2.5rem; }
.stat-content h3 { margin: 0; font-size: 2rem; font-weight: 700; background: linear-gradient(135deg, #ff6b35, #f7931e); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.stat-content p { margin: 0.25rem 0 0; color: #6b7280; font-size: 0.875rem; }
.search-section { display: flex; gap: 1rem; margin-bottom: 1.5rem; }
.search-input { flex: 1; padding: 0.75rem 1rem; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 1rem; }
.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; }
.filters-card { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
.filter-group { flex: 1; min-width: 200px; }
.filter-group label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151; font-size: 0.875rem; }
.filter-select { width: 100%; padding: 0.625rem; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 0.875rem; }
.btn-clear { padding: 0.625rem 1.5rem; background: #ef4444; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; align-self: flex-end; }
.table-card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 1.5rem; }
.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; }
.product-img { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; }
.badge { padding: 0.25rem 0.75rem; border-radius: 12px; font-size: 0.75rem; font-weight: 600; }
.badge-success { background: #d1fae5; color: #065f46; }
.badge-danger { background: #fee2e2; color: #991b1b; }
.badge-warning { background: #fef3c7; color: #92400e; }
.badge-info { background: #dbeafe; color: #1e40af; }
.action-buttons { display: flex; gap: 0.5rem; }
.btn-icon { background: none; border: none; font-size: 1.25rem; cursor: pointer; padding: 0.25rem; }
.pagination { display: flex; justify-content: space-between; align-items: center; background: white; padding: 1rem 1.5rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
.pagination-info { color: #6b7280; font-size: 0.875rem; }
.pagination-controls { display: flex; gap: 0.5rem; align-items: center; }
.btn-page { padding: 0.5rem 1rem; background: white; border: 2px solid #e5e7eb; border-radius: 8px; cursor: pointer; font-size: 0.875rem; font-weight: 600; }
.btn-page:disabled { opacity: 0.5; cursor: not-allowed; }
.page-info { color: #374151; font-weight: 600; font-size: 0.875rem; }
.modal-content-small { background: white; border-radius: 12px; width: 100%; max-width: 400px; }
.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; }
.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-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; }
.btn-save:disabled { opacity: 0.5; cursor: not-allowed; }
.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; }
</style>
