<script setup>
import { usePageTitle } from '../composables/Core/usePageTitle';
usePageTitle('Edit Product Ultimate');

import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'
import { useNavigate } from '../composables/Core/useNavigate'
import { useModal } from '../composables/Core/useModal'
import LoadingSpinner from '../Components/LoadingSpinner.vue'
import CardSimple from '../Components/Core/CardSimple.vue'
import Dropzone from '../Components/Core/Dropzone.vue'
import { useFileUpload } from '../composables/useFileUpload.js'
import { useProductStore } from '../stores/product'

const productStore = useProductStore()

const props = defineProps({
  target: { type: String, default: null },
  payload: { type: Object, default: null }
})

const { navigate } = useNavigate()
const modal = useModal()
const { uploadFile, removeHash, photoHashes, setInitialHashes, isUploading: isFileUploading } = useFileUpload({ 
  category: 'ProductMarket',
  maxSizeMB: 10
})

// Form state
const productId = ref(null)
const productName = ref('')
const productDescription = ref('')
const productCategory = ref('')
const productSubcategory = ref('')
const productPrice = ref(0)
const productUnitName = ref('')
const productAvailable = ref(0)
const productBarcode = ref('')
const storeHash = ref(null)

// Data lists
const categoryList = ref([])
const subcategoryList = ref([])

// Loading state
const isLoading = ref(false)
const successMessage = ref('')
const error = ref(null)

// Initialize component
onMounted(async () => {
  document.title = 'Edit Product'
  const urlParams = new URLSearchParams(window.location.search)
  storeHash.value = urlParams.get('store_hash') || urlParams.get('store')
  await loadCategories()
  await loadProductData()
})

// Load categories
const loadCategories = async () => {
  try {
    const response = await axios.post('/Products/New/Category/Datalist', {})
    const data = response.data.categories || response.data
    if (data && Array.isArray(data)) {
      categoryList.value = data.map(item => ({
        value: typeof item === 'string' ? item : item[0],
        label: typeof item === 'string' ? item : (item[1] || item[0])
      }))
    }
  } catch (err) {
    console.error('Error loading categories:', err)
  }
}

// Load subcategories when category changes
const loadSubcategories = async () => {
  if (!productCategory.value) {
    subcategoryList.value = []
    return
  }

  try {
    const response = await axios.post('/Products/New/SubCategory/Datalist', { 
      category: productCategory.value 
    })
    const data = response.data.subcategories || response.data
    if (data && Array.isArray(data)) {
      subcategoryList.value = data.map(item => ({
        value: typeof item === 'string' ? item : item[0],
        label: typeof item === 'string' ? item : (item[1] || item[0])
      }))
    }
  } catch (err) {
    console.error('Error loading subcategories:', err)
  }
}

// Load product data
const loadProductData = async () => {
  try {
    isLoading.value = true
    
    // Extract info from props first, then from URL
    if (props.payload) {
      productId.value = props.payload.product_hashkey || props.payload.product_hash || props.payload.target;
      storeHash.value = props.payload.store_hashkey || props.payload.store_hash;
    } else {
      const urlParams = new URLSearchParams(window.location.search)
      productId.value = props.target || urlParams.get('product_id') || urlParams.get('id') || urlParams.get('hashkey')
      storeHash.value = urlParams.get('store_hash') || urlParams.get('store')
    }
    
    if (!productId.value) {
      error.value = 'Product ID not found'
      return
    }

    const response = await axios.post('/View/Product/Details/data', {
      target: productId.value,
      data: { 
        product_id: productId.value,
        store_hash: storeHash.value
      }
    })

    if (response.data && response.data.success && response.data.data) {
      const product = response.data.data
      productName.value = product.name || ''
      productDescription.value = product.description || ''
      productCategory.value = product.category || ''
      productSubcategory.value = product.subcategory || ''
      productPrice.value = product.price || 0
      productUnitName.value = product.unitname || ''
      productBarcode.value = product.barcode || ''
      productAvailable.value = product.available || 0

      // Load subcategories for the initial category
      if (productCategory.value) {
        await loadSubcategories()
        productSubcategory.value = product.subcategory || ''
      }

      // Handle photos
      if (product.photourlDropzone && Array.isArray(product.photourlDropzone)) {
          const initialFiles = product.photourlDropzone.map(f => ({
              file: { name: f.name || 'Image' },
              hashkey: f.hashkey,
              progress: 100,
              uploading: false,
              preview: f.url
          }));
          dropzoneFiles.value = initialFiles;
          setInitialHashes(product.photourlDropzone.map(f => f.hashkey));
      }
    }
  } catch (err) {
    console.error('Error loading product data:', err)
    error.value = 'Failed to load product data'
  } finally {
    isLoading.value = false
  }
}

// Dropzone handling
const dropzoneRef = ref(null)
const dropzoneFiles = ref([])

// Watch for new files in dropzone and upload them
watch(() => dropzoneFiles.value, async (newFiles, oldFiles) => {
    // Find files that are not yet uploading and don't have a hashkey
    const filesToUpload = newFiles.filter(f => !f.uploading && !f.hashkey && !f.error);
    
    for (const fileObj of filesToUpload) {
        const index = newFiles.indexOf(fileObj);
        if (index === -1) continue;

        // Set uploading status
        dropzoneRef.value.setFileStatus(index, { uploading: true, progress: 30 });
        
        const result = await uploadFile(fileObj.file);
        
        if (result && result.hashkey) {
            dropzoneRef.value.setFileStatus(index, { 
                uploading: false, 
                progress: 100, 
                hashkey: result.hashkey 
            });
        } else {
            dropzoneRef.value.setFileStatus(index, { 
                uploading: false, 
                progress: 0, 
                error: 'Upload failed' 
            });
        }
    }
}, { deep: true });

const handlePhotoRemoved = (hashkey) => {
    removeHash(hashkey);
};

const handleCategoryChange = () => {
  loadSubcategories()
}

const validateForm = () => {
  if (!productName.value) {
    error.value = 'Product name is required'
    return false
  }
  if (!productCategory.value) {
    error.value = 'Category is required'
    return false
  }
  if (productPrice.value === null || productPrice.value === undefined || productPrice.value < 0) {
    error.value = 'Valid price is required'
    return false
  }
  error.value = null
  return true
}

const handleSubmit = async () => {
  if (!validateForm()) return

  try {
    isLoading.value = true

    const response = await axios.post('/Products/Admin/Edit/', {
      target: productId.value,
      data: {
        store_hash: storeHash.value
      },
      EditProductName: productName.value,
      EditProductDescription: productDescription.value,
      EditProductCategory: productCategory.value,
      EditProductSubCategory: productSubcategory.value,
      EditProductPrice: parseFloat(productPrice.value),
      EditProductUnitName: productUnitName.value,
      EditProductAvailable: parseInt(productAvailable.value),
      EditProductBarcode: productBarcode.value,
      status: true, // Assuming active if editing, can be bound to a checkbox if needed
      photourl: dropzoneFiles.value
        .filter(f => f.hashkey)
        .map(f => f.hashkey)
    })

    if (response.data && response.data.success) {
      successMessage.value = 'Product updated successfully!'
      
      // Proactively prefetch products list
      productStore.fetchProducts()
      
      setTimeout(() => {
        navigate({ page: 'ManageProductsAdmin' })
      }, 1500)
    } else {
      error.value = response.data?.message || 'Failed to update product'
    }
  } catch (err) {
    console.error('Error updating product:', err)
    error.value = err.response?.data?.message || err.message || 'Failed to update product'
    
    // Scroll to error if it occurs
    window.scrollTo({ top: 0, behavior: 'smooth' })
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="edit-product-page pb-5">
    <div class="tf-container mt-5 mb-4 text-center">
      <h1 class="fw_8 premium-title">Edit Product</h1>
      <p class="text-muted">Update your product details and availability</p>
    </div>

    <div v-if="successMessage" class="tf-container mb-4">
      <div class="glass-alert alert-success animate-fade-in">
        <i class="fas fa-check-circle me-2"></i>
        {{ successMessage }}
      </div>
    </div>

    <div v-if="error" class="tf-container mb-4">
      <div class="glass-alert alert-danger animate-shake">
        <i class="fas fa-exclamation-triangle me-2"></i>
        {{ error }}
      </div>
    </div>

    <div class="tf-container">
      <div class="form-grid" v-if="!isLoading || productName">
        <!-- Left Column: Basic Info -->
        <div class="form-section">
          <CardSimple title="Product Details">
            <div class="premium-input-group mb-4">
              <label for="productName" class="form-label">Product Name <span class="required">*</span></label>
              <input 
                type="text" 
                id="productName"
                v-model="productName"
                class="premium-input"
                placeholder="Product Name"
              >
            </div>

            <div class="premium-input-group mb-4">
              <label for="productDescription" class="form-label">Description</label>
              <textarea 
                id="productDescription"
                v-model="productDescription"
                class="premium-input"
                rows="4"
                placeholder="Description..."
              ></textarea>
            </div>

            <div class="row">
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="category" class="form-label">Category <span class="required">*</span></label>
                  <select 
                    id="category"
                    v-model="productCategory"
                    class="premium-select"
                    @change="handleCategoryChange"
                  >
                    <option value="" disabled>Select Category</option>
                    <option v-for="cat in categoryList" :key="cat.value" :value="cat.value">
                      {{ cat.label }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="subcategory" class="form-label">Subcategory</label>
                  <select 
                    id="subcategory"
                    v-model="productSubcategory"
                    class="premium-select"
                    :disabled="subcategoryList.length === 0"
                  >
                    <option value="" disabled>Select Subcategory</option>
                    <option v-for="sub in subcategoryList" :key="sub.value" :value="sub.value">
                      {{ sub.label }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </CardSimple>
        </div>

        <!-- Right Column: Inventory & Photos -->
        <div class="form-section">
          <CardSimple title="Inventory & Pricing">
            <div class="row">
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="price" class="form-label">Price (PHP) <span class="required">*</span></label>
                  <input 
                    type="number" 
                    id="price"
                    v-model="productPrice"
                    class="premium-input"
                    step="0.01"
                  >
                </div>
              </div>
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="unit" class="form-label">Unit</label>
                  <input 
                    type="text" 
                    id="unit"
                    v-model="productUnitName"
                    class="premium-input"
                    placeholder="e.g., 25kg"
                  >
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="available" class="form-label">Available Stock</label>
                  <input 
                    type="number" 
                    id="available"
                    v-model="productAvailable"
                    class="premium-input"
                  >
                </div>
              </div>
              <div class="col-md-6">
                <div class="premium-input-group mb-4">
                  <label for="barcode" class="form-label">Barcode</label>
                  <input 
                    type="text" 
                    id="barcode"
                    v-model="productBarcode"
                    class="premium-input"
                    maxlength="12"
                  >
                </div>
              </div>
            </div>

            <div class="premium-input-group mb-2">
              <label class="form-label">Product Photos</label>
              <Dropzone 
                ref="dropzoneRef"
                v-model:files="dropzoneFiles" 
                @removed="handlePhotoRemoved"
              />
            </div>
          </CardSimple>
        </div>
      </div>

      <div v-else class="text-center py-5">
        <LoadingSpinner />
        <p class="mt-2">Loading product details...</p>
      </div>

      <div class="action-bar mt-5 text-center">
        <button 
          @click="handleSubmit"
          :disabled="isLoading || successMessage || isFileUploading"
          class="btn-premium-launch"
          :class="{ 'btn-loading': isLoading }"
        >
          <span v-if="!isLoading">Update Product</span>
          <LoadingSpinner v-else size="small" color="white" />
        </button>
        
        <div class="mt-4">
          <button 
            @click="navigate({ page: 'ManageProductsAdmin' })"
            class="btn-text"
          >
            <i class="fas fa-chevron-left me-2"></i> Cancel and Return
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.premium-title {
    font-family: 'Outfit', sans-serif;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: -0.02em;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}

@media (max-width: 992px) {
    .form-grid {
        grid-template-columns: 1fr;
    }
}

.premium-input-group {
    display: flex;
    flex-direction: column;
}

.form-label {
    font-weight: 600;
    font-size: 0.9rem;
    color: #475569;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
}

.required {
    color: #ef4444;
    margin-left: 4px;
}

.premium-input, .premium-select {
    padding: 12px 16px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
    background: #fff;
    font-size: 0.95rem;
    transition: all 0.2s;
    outline: none;
}

.premium-input:focus, .premium-select:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
}

.premium-select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2364748b'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    background-size: 16px;
}

.glass-alert {
    padding: 16px 20px;
    border-radius: 16px;
    backdrop-filter: blur(8px);
    font-weight: 500;
    display: flex;
    align-items: center;
}

.alert-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid rgba(34, 197, 94, 0.2);
    color: #15803d;
}

.alert-danger {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.2);
    color: #b91c1c;
}

.btn-premium-launch {
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: white;
    border: none;
    padding: 16px 48px;
    border-radius: 14px;
    font-weight: 700;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.3);
}

.btn-premium-launch:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 20px 25px -5px rgba(37, 99, 235, 0.4);
    filter: brightness(1.1);
}

.btn-premium-launch:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
    box-shadow: none;
}

.btn-loading {
    padding: 12px 48px;
    background: #3b82f6;
}

.btn-text {
    background: transparent;
    border: none;
    color: #64748b;
    font-weight: 500;
    cursor: pointer;
    transition: color 0.2s;
}

.btn-text:hover {
    color: #1e293b;
}

.animate-fade-in {
    animation: fadeIn 0.5s ease-out;
}

.animate-shake {
    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

@keyframes shake {
    10%, 90% { transform: translate3d(-1px, 0, 0); }
    20%, 80% { transform: translate3d(2px, 0, 0); }
    30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
    40%, 60% { transform: translate3d(4px, 0, 0); }
}

:global(.dark-mode) .premium-input, :global(.dark-mode) .premium-select {
    background: #1e293b;
    border-color: #334155;
    color: #f8fafc;
}

:global(.dark-mode) .premium-title {
    background: linear-gradient(135deg, #f8fafc 0%, #cbd5e1 100%);
    -webkit-background-clip: text;
    background-clip: text;
}

:global(.dark-mode) .form-label {
    color: #94a3b8;
}
</style>