<script setup>
import { usePageTitle } from '../composables/Core/usePageTitle';
usePageTitle('Remove Product From Store Admin');

import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useNavigate } from '../composables/Core/useNavigate'
import { useModal } from '../composables/Core/useModal'
import { useStoreStore } from '../stores/store'

const { navigate } = useNavigate()
const modal = useModal()
const storeStore = useStoreStore()

// Form state
const productId = ref(null)
const selectedStoreId = ref('')
const productData = ref({})

// Data lists
const storeList = ref([])

// Loading state
const isLoading = ref(false)

// Initialize component
onMounted(() => {
  document.title = 'Remove Product from Store'
  loadStores()
  loadProductData()
})

// Load stores
const loadStores = async () => {
  try {
    const response = await axios.post('/ListStores/List/data')
    if (response.data && Array.isArray(response.data)) {
      storeList.value = response.data.map(store => ({
        value: store.id,
        label: store.name || store.store_name || `Store #${store.id}`
      }))
    }
  } catch (error) {
    console.error('Error loading stores:', error)
  }
}

// Load product data
const loadProductData = async () => {
  try {
    isLoading.value = true
    
    // Get product ID from route params or query params
    const urlParams = new URLSearchParams(window.location.search)
    productId.value = urlParams.get('product_id') || urlParams.get('id')
    
    if (!productId.value) {
      modal.open({
        title: 'Error',
        body: 'Product ID not found. Please select a product to remove.',
        footer: null
      })
      return
    }

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

    if (response.data && response.data.success && response.data.data) {
      const product = response.data.data
      productData.value = {
        name: product.name || '',
        price: product.price ? String(product.price) : '',
        unitname: product.unitname || '',
        barcode: product.barcode || ''
      }
    }
  } catch (error) {
    console.error('Error loading product data:', error)
    modal.open({
      title: 'Error',
      body: 'Failed to load product data.',
      footer: null
    })
  } finally {
    isLoading.value = false
  }
}

// Validate form
const validateForm = () => {
  if (!selectedStoreId.value) {
    modal.open({ title: 'Error', body: 'Please select a store', footer: null })
    return false
  }

  return true
}

// Show confirmation modal
const showConfirmationModal = () => {
  if (!validateForm()) return

  const storeName = storeList.value.find(s => s.value == selectedStoreId.value)?.label
  
  modal.yesNoModal({
    title: 'Remove Product?',
    body: `Are you sure you want to remove this product from <strong>${storeName}</strong>?`,
    onYes: removeProduct,
    yesText: 'Remove',
    noText: 'Cancel'
  })
}

// Remove product from store
const removeProduct = async () => {
  try {
    isLoading.value = true

    const response = await axios.post('/Products/Admin/RemovefronStore/', {
      product_id: productId.value,
      store_id: selectedStoreId.value
    })

    if (response.data && response.data.success) {
      modal.continueCancelModal({
        title: 'Success',
        body: 'Product removed from store successfully',
        onContinue: () => {
          navigate({ page: 'ManageProductAdmin' })
        },
        continueText: 'OK',
        continueClass: 'btn btn-primary',
        showCancel: false
      })
    } else {
      modal.open({
        title: 'Error',
        body: response.data?.message || 'Failed to remove product from store',
        footer: null
      })
    }
  } catch (error) {
    console.error('Error removing product:', error)
    modal.open({
      title: 'Error',
      body: error.response?.data?.message || 'Failed to remove product from store',
      footer: null
    })
  } finally {
    isLoading.value = false
  }
}

// Cancel and go back
const cancel = () => {
  navigate({ page: 'UserList' }) // Defaulting to UserList or another valid page
}
</script>

<template>
  <div class="remove-product-page pb-5">
    <br><br>
    
    <div class="tf-container">
      <h2 class="fw_6 text-center mb-4">Remove Product from Store</h2>
      
      <!-- Back Button -->
      <div class="text-start mb-3">
        <button 
          @click="cancel"
          class="btn btn-secondary"
        >
          <i class="fas fa-arrow-left"></i> Cancel
        </button>
      </div>

      <div class="card shadow-sm">
        <div class="card-body">
          <div class="row g-3">
            <!-- Store Selection -->
            <div class="col-12">
              <select
                class="form-select"
                id="TargetStore"
                v-model="selectedStoreId"
                required
                :disabled="isLoading || storeList.length === 0"
              >
                <option value="" disabled>Select Store</option>
                <option v-for="store in storeList" :key="store.value" :value="store.value">
                  {{ store.label }}
                </option>
              </select>
            </div>

            <!-- Product Name (Read-only) -->
            <div class="col-12">
              <input
                type="text"
                id="EditProductName"
                class="form-control"
                placeholder="Product Name"
                :value="productData.name"
                disabled
              >
            </div>

            <!-- Price (Read-only) -->
            <div class="col-12 col-md-6">
              <input
                type="number"
                id="EditProductPrice"
                class="form-control"
                placeholder="Price (PHP)"
                :value="productData.price"
                disabled
              >
            </div>

            <!-- Unit Name (Read-only) -->
            <div class="col-12 col-md-6">
              <input
                type="text"
                id="EditProductUnitName"
                class="form-control"
                placeholder="Unit (e.g., 25kg)"
                :value="productData.unitname"
                disabled
              >
            </div>

            <!-- Barcode (Read-only) -->
            <div class="col-12">
              <input
                type="text"
                id="EditProductBarcode"
                class="form-control"
                placeholder="Barcode (12-digit number)"
                :value="productData.barcode"
                maxlength="12"
                pattern="[0-9]*"
                disabled
              >
            </div>

            <!-- Submit Button -->
            <div class="col-12 mt-3">
              <button
                id="submit-btn"
                class="btn btn-danger w-100 py-2"
                @click="showConfirmationModal"
                :disabled="isLoading"
              >
                Remove Product from Store
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.card {
  border-radius: 12px;
}
</style>