import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'

export const useSearchStore = defineStore('search', () => {
  // State for search form
  const searchForm = ref({
    product: '',
    productUuid: '', // UUID for API
    quantity: '',
    unit: 'tons',
    location: '',
    locationUuid: '' // UUID for API
  })

  // State for created request
  const currentRequest = ref(null)

  // Getters
  const isFormComplete = computed(() => {
    return searchForm.value.product && 
           searchForm.value.quantity && 
           searchForm.value.location
  })

  const getSearchUrl = computed(() => {
    if (!isFormComplete.value) return ''
    const params = new URLSearchParams({
      product: searchForm.value.product,
      quantity: searchForm.value.quantity,
      unit: searchForm.value.unit,
      location: searchForm.value.location
    })
    return `/search?${params.toString()}`
  })

  // Actions
  const setProduct = (product) => {
    searchForm.value.product = product
  }

  const setProductUuid = (uuid) => {
    searchForm.value.productUuid = uuid
  }

  const setLocation = (location) => {
    searchForm.value.location = location
  }

  const setLocationUuid = (uuid) => {
    searchForm.value.locationUuid = uuid
  }

  const setQuantity = (quantity) => {
    searchForm.value.quantity = quantity
  }

  const setUnit = (unit) => {
    searchForm.value.unit = unit
  }

  const setRequest = (request) => {
    currentRequest.value = request
  }

  const resetForm = () => {
    searchForm.value = {
      product: '',
      productUuid: '',
      quantity: '',
      unit: 'tons',
      location: '',
      locationUuid: ''
    }
    currentRequest.value = null
  }

  return {
    // State
    searchForm,
    currentRequest,

    // Getters
    isFormComplete,
    getSearchUrl,

    // Actions
    setProduct,
    setProductUuid,
    setLocation,
    setLocationUuid,
    setQuantity,
    setUnit,
    setRequest,
    resetForm
  }
})
