<script setup>
import { string, date } from 'alga-js'
import { SelectBox } from 'tedir-select'
import { DatePicker } from 'tedir-calendar'

const props = defineProps({
  modelValue: Object,
  tab: String,
  orderDefaults: Object
})

const emit = defineEmits(['update:modelValue', 'update:tab', 'save'])

const config = useRuntimeConfig()
const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const clientName = ref('')
const { getMenuType } = useRoleMenu()
const { isFbaShipper } = useFbaShipper()
// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')

onMounted(() => {
  defaultSideBarMenu.value = getMenuType()
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue?.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  name: props.modelValue.name || '',
  name2: props.modelValue.name2 || '',
  value: props.modelValue.value || '',
  description: props.modelValue.description || '',
  salesVolume: props.modelValue.salesVolume || 0,
  numberEmployees: props.modelValue.numberEmployees || 0,
  isActive: props.modelValue.isActive ?? true,
  isSummary: props.modelValue.isSummary ?? false,
  isVendor: props.modelValue.isVendor ?? false,
  isCustomer: props.modelValue.isCustomer ?? false,
  isProspect: props.modelValue.isProspect ?? false,
  soCreditLimit: props.modelValue.soCreditLimit || 0,
  soCreditUsed: props.modelValue.soCreditUsed || 0,
  acqusitionCost: props.modelValue.acqusitionCost || 0,
  potentialLifeTimeValue: props.modelValue.potentialLifeTimeValue || 0,
  actualLifeTimeValue: props.modelValue.actualLifeTimeValue || 0,
  shareOfCustomer: props.modelValue.shareOfCustomer || 0,
  isEmployee: props.modelValue.isEmployee ?? false,
  isSalesRep: props.modelValue.isSalesRep ?? false,
  isOneTime: props.modelValue.isOneTime ?? false,
  isTaxExempt: props.modelValue.isTaxExempt ?? false,
  isDiscountPrinted: props.modelValue.isDiscountPrinted ?? false,
  sendEMail: props.modelValue.sendEMail ?? false,
  EMail: props.modelValue.EMail || '',
  totalOpenBalance: props.modelValue.totalOpenBalance || 0,
  isPOTaxExempt: props.modelValue.isPOTaxExempt ?? false,
  isManufacturer: props.modelValue.isManufacturer ?? false,
  is1099Vendor: props.modelValue.is1099Vendor ?? false,
  firstSale: props.modelValue.firstSale || date.now('date'),
  poReference: props.modelValue.poReference || '',
  referenceNo: props.modelValue.referenceNo || '',
  rating: props.modelValue.rating || '',
  taxID: props.modelValue.taxID || '',
  URL: props.modelValue.URL || '',
  NAICS: props.modelValue.NAICS || '',
  DUNS: props.modelValue.DUNS || '',
  documentCopies: props.modelValue.documentCopies || 0,
  soDescription: props.modelValue.soDescription || '',
  flatDiscount: props.modelValue.flatDiscount || 0,
  shelfLifeMinPct: props.modelValue.shelfLifeMinPct || 0,
  dunningGrace: props.modelValue.dunningGrace || date.now('date'),
  isFulfillmentCustomer: props.modelValue.isFulfillmentCustomer ?? false,
  fulfillmentOrderBaseprice: props.modelValue.fulfillmentOrderBaseprice ?? 0,
  fulfillmentOrderPickprice: props.modelValue.fulfillmentOrderPickprice ?? 0,
  fulfillmentOrderQtyPickfree: props.modelValue.fulfillmentOrderQtyPickfree ?? 0,
  fulfillmentOrderBaseprice2: props.modelValue.fulfillmentOrderBaseprice2 ?? 0,
  fulfillmentOrderBaseprice3: props.modelValue.fulfillmentOrderBaseprice3 ?? 0,
  fulfillmentOrderReturnBaseprice: props.modelValue.fulfillmentOrderReturnBaseprice ?? 0,
  fulfillmentOrderReturnPickprice: props.modelValue.fulfillmentOrderReturnPickprice ?? 0,
  deliveryRule: props.modelValue.deliveryRule || '',
  deliveryRuleId: props.modelValue.deliveryRuleId || '',
  deliveryViaRule: props.modelValue.deliveryViaRule || '',
  deliveryViaRuleId: props.modelValue.deliveryViaRuleId || '',
  invoiceSchedule: props.modelValue.invoiceSchedule || '',
  invoiceScheduleId: props.modelValue.invoiceScheduleId || '',
  greeting: props.modelValue.greeting || '',
  greetingId: props.modelValue.greetingId || '',
  printFormat: props.modelValue.printFormat || '',
  printFormatId: props.modelValue.printFormatId || '',
  salesRep: props.modelValue.salesRep || user.value?.Name || '',
  salesRepId: props.modelValue.salesRepId || user.value?.id || userId.value || '',
  paymentRulePO: props.modelValue.paymentRulePO || '',
  paymentRulePOId: props.modelValue.paymentRulePOId || '',
  soCreditStatus: props.modelValue.soCreditStatus || '',
  soCreditStatusId: props.modelValue.soCreditStatusId || '',
  partnerGroup: props.modelValue.partnerGroup || '',
  partnerGroupId: props.modelValue.partnerGroupId || '',
  poPriceList: props.modelValue.poPriceList || '',
  poPriceListId: props.modelValue.poPriceListId || '',
  poPaymentTerm: props.modelValue.poPaymentTerm || '',
  poPaymentTermId: props.modelValue.poPaymentTermId || '',
  languageId: props.modelValue.languageId || '',
  orderSource: props.modelValue.orderSource || 'Manuell',
  orderSourceId: props.modelValue.orderSourceId || '1000002',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false
  }
})

const form2 = ref({
  id: '',
  uid: '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isActive: true,
  address1: '',
  address2: '',
  address3: '',
  address4: '',
  city: '',
  postal: '',
  phone: '',
  regionName: '',
  partnerLocationId: '',
  userId: '',
  isValid: true,
  country: config.public.countryvalue ?? 'Germany',
  countryId: config.public.countryid ?? '101',
  region: '',
  regionId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const form3 = ref({
  id: '',
  uid: '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isDifferentAddress: false,
  isActive: true,
  address1: '',
  address2: '',
  address3: '',
  address4: '',
  city: '',
  postal: '',
  phone: '',
  regionName: '',
  partnerLocationId: '',
  userId: '',
  isValid: true,
  country: config.public.countryvalue ?? 'Germany',
  countryId: config.public.countryid ?? '101',
  region: '',
  regionId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const form4 = ref({
  id: '',
  uid: '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  docTypeTarget: config.public.doctypevalue ?? 'Standard Order',
  docTypeTargetId: config.public.doctypeid ?? '132',
  warehouse: '',
  warehouseId: '',
  priceList: 'Verkauf Brutto',
  priceListId: '1000003',
  currency: 'EUR',
  currencyId: '102',
  user: user.value?.Name ?? '',
  userId: user.value?.id ?? userId.value ?? '',
  orderSource: 'Manuell',
  orderSourceId: '1000002',
  deliveryViaRule: props.orderDefaults?.deliveryViaRule || '',
  deliveryViaRuleId: props.orderDefaults?.deliveryViaRuleId || '',
  shipper: props.orderDefaults?.shipper || '',
  shipperId: String(props.orderDefaults?.shipperId || ''),
  isFulfillmentOrder: true,
  isRelabelByFulfillmentProvider: false,
})

console.log('Child form4 initialized with:', {
  priceListId: form4.value.priceListId,
  priceList: form4.value.priceList,
  orderSourceId: form4.value.orderSourceId,
  orderSource: form4.value.orderSource
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/

    getOptions.value[key] = res

    if(key === 'warehouses' && res?.records?.[0]) {
      form4.value.warehouseId = String(res.records[0].id || '')
      form4.value.warehouse = res.records[0].Name || ''
    }
  }
  loading.value[key] = false
}

const organizationHandler = async (val, opt) => {
  form.value.client = opt?.AD_Client_ID?.identifier || ''
  form.value.clientId = opt?.AD_Client_ID?.id || ''
  form.value.organization = opt?.Name || organization.value?.Name || ''
  form.value.organizationId = opt?.id || organizationId.value || ''

  form2.value.client = form.value.client
  form2.value.clientId = form.value.clientId
  form2.value.organization = form.value.organization
  form2.value.organizationId = form.value.organizationId

  form3.value.client = form.value.client
  form3.value.clientId = form.value.clientId
  form3.value.organization = form.value.organization
  form3.value.organizationId = form.value.organizationId

  form4.value.client = form.value.client
  form4.value.clientId = form.value.clientId
  form4.value.organization = form.value.organization
  form4.value.organizationId = form.value.organizationId

  // Fetch new defaults for the selected organization
  if (opt?.id) {
    try {
      const response = await $fetch('/api/partners/partners/org-defaults', {
        method: 'GET',
        query: { orgId: opt.id }
      })
      if (response?.status === 200 && response?.defaults) {
        const newDefaults = response.defaults
        console.log('Fetched new org defaults on org change:', newDefaults)

        // Update form with new defaults
        form.value.priceList = newDefaults.priceList || config.public.pricelistvalue || 'Standard'
        form.value.priceListId = newDefaults.priceListId || config.public.pricelistid || '101'
        form.value.orderSource = newDefaults.orderSource || ''
        form.value.orderSourceId = newDefaults.orderSourceId || ''

        // Update form4 with new defaults
        form4.value.priceList = newDefaults.priceList || config.public.pricelistvalue || 'Standard'
        form4.value.priceListId = String(newDefaults.priceListId || config.public.pricelistid || '101')
        form4.value.orderSource = newDefaults.orderSource || ''
        form4.value.orderSourceId = String(newDefaults.orderSourceId || '')
        form4.value.deliveryViaRule = newDefaults.deliveryViaRule || ''
        form4.value.deliveryViaRuleId = newDefaults.deliveryViaRuleId || ''
        form4.value.shipper = newDefaults.shipper || ''
        form4.value.shipperId = String(newDefaults.shipperId || '')
      }
    } catch (error) {
      console.error('Error fetching org defaults on org change:', error)
    }
  }
}

const priceListHandler = (val, opt) => {
  form4.value.currency = opt?.C_Currency_ID?.identifier || ''
  form4.value.currencyId = opt?.C_Currency_ID?.id || ''
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})
onMounted(() => {
  if(form.value.organizationId || props.modelValue.organizationId || organizationId.value) {
    setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${form.value.organizationId || props.modelValue.organizationId || organizationId.value}`), 'warehouses')
  }
  // Preload the Delivery Via reference list so the button picker has options
  // available immediately (no click-to-load).
  setOptions('references/delivery_via_rule', 'delivery_via_rules')
})

// Fixed order for the three supported Delivery Via options. Labels + descriptions
// come from shared.js translations (en-US / de-DE / es-ES).
const { t } = useTranslation()
const deliveryViaButtons = computed(() => ([
  { value: 'S', icon: 'ti-truck-delivery', title: t.value.delivery_via_shipper,  desc: t.value.delivery_via_shipper_desc },
  { value: 'D', icon: 'ti-package',        title: t.value.delivery_via_delivery, desc: t.value.delivery_via_delivery_desc },
  { value: 'P', icon: 'ti-building-store', title: t.value.delivery_via_pickup,   desc: t.value.delivery_via_pickup_desc }
]))
const setDeliveryVia = (btn) => {
  form4.value.deliveryViaRuleId = btn?.value || ''
  // Use the reflist name when available so the backend display stays aligned
  // with iDempiere's translation; fall back to the hardcoded title.
  const fromList = (getOptions.value?.['delivery_via_rules']?.reflist || [])
    .find(o => String(o.value) === String(btn?.value))
  form4.value.deliveryViaRule = fromList?.name || btn?.title || ''
  save()
}

const isEmailActive = ref(false)

// --- Partner search state ---
const isNewPartner = ref(false)
const partnerSearchQuery = ref('')
const partnerSearchOpen = ref(false)
const partnerSearchLoading = ref(false)
const allPartners = ref([])
let partnersLoaded = false

const loadPartners = async () => {
  if (partnersLoaded) return
  partnerSearchLoading.value = true
  try {
    const orgId = form.value.organizationId || props.modelValue.organizationId || organizationId.value
    const res = await $fetch(`/api/partners/partners/select?org=${orgId}&customer=true`, {
      headers: useRequestHeaders(['cookie'])
    })
    allPartners.value = res?.records || []
    partnersLoaded = true
  } catch (e) {
    console.error('Failed to load partners:', e)
  }
  partnerSearchLoading.value = false
}

const filteredPartners = computed(() => {
  const q = partnerSearchQuery.value.toLowerCase().trim()
  if (!q) return allPartners.value.slice(0, 50)
  return allPartners.value.filter(p => {
    const name = (p.Name || '').toLowerCase()
    const email = (p.EMail || '').toLowerCase()
    const value = (p.Value || '').toLowerCase()
    return name.includes(q) || email.includes(q) || value.includes(q)
  }).slice(0, 50)
})

const selectExistingPartner = async (partner) => {
  partnerSearchOpen.value = false
  partnerSearchQuery.value = ''
  isNewPartner.value = false

  // If partner has email, use email lookup; otherwise use partnerId lookup
  if (partner.EMail) {
    form.value.EMail = partner.EMail
    await checkEmailPartner()
  } else {
    await checkEmailPartnerById(partner.id)
  }
}

const checkEmailPartnerById = async (partnerId) => {
  const orgId = form.value.organizationId || props.modelValue.organizationId || organizationId.value
  const res = await $fetch(`/api/partners/partners/email?org=${orgId}&partnerId=${partnerId}`, {
    headers: useRequestHeaders(['cookie'])
  })
  if (res?.id) {
    populateFromResponse(res)
  }
  isEmailActive.value = true
  save()
}

const createNewPartner = () => {
  partnerSearchOpen.value = false
  isNewPartner.value = true
  isEmailActive.value = true

  // Prefill: if query looks like email, set as email; otherwise set as name
  const q = partnerSearchQuery.value.trim()
  if (q.includes('@')) {
    form.value.EMail = q
  } else if (q) {
    form.value.name = q
  }
  partnerSearchQuery.value = ''
}

const resetPartnerSearch = () => {
  isEmailActive.value = false
  isNewPartner.value = false
  partnerSearchQuery.value = ''

  // Reset form fields
  form.value.id = ''
  form.value.uid = ''
  form.value.name = ''
  form.value.name2 = ''
  form.value.value = ''
  form.value.EMail = ''

  // Reset ship address
  form2.value.id = ''
  form2.value.uid = ''
  form2.value.address1 = ''
  form2.value.address2 = ''
  form2.value.address3 = ''
  form2.value.address4 = ''
  form2.value.city = ''
  form2.value.postal = ''
  form2.value.phone = ''
  form2.value.regionName = ''
  form2.value.partnerLocationId = ''
  form2.value.userId = ''
  form2.value.country = config.public.countryvalue ?? 'Germany'
  form2.value.countryId = config.public.countryid ?? '101'
  form2.value.region = ''
  form2.value.regionId = ''

  // Reset bill address
  form3.value.id = ''
  form3.value.uid = ''
  form3.value.isDifferentAddress = false
  form3.value.address1 = ''
  form3.value.address2 = ''
  form3.value.address3 = ''
  form3.value.address4 = ''
  form3.value.city = ''
  form3.value.postal = ''
  form3.value.phone = ''
  form3.value.regionName = ''
  form3.value.partnerLocationId = ''
  form3.value.userId = ''
  form3.value.country = config.public.countryvalue ?? 'Germany'
  form3.value.countryId = config.public.countryid ?? '101'
  form3.value.region = ''
  form3.value.regionId = ''
}

const onSearchFocus = () => {
  partnerSearchOpen.value = true
  loadPartners()
}

const onSearchBlur = () => {
  // Delay to allow click on dropdown items
  setTimeout(() => {
    partnerSearchOpen.value = false
  }, 200)
}

const populateFromResponse = (res) => {
  form.value.id = res?.id || ''
  form.value.uid = res?.uid || ''
  form.value.client = res?.AD_Client_ID?.identifier || ''
  form.value.clientId = res?.AD_Client_ID?.id || ''
  form.value.organization = res?.AD_Org_ID?.identifier || ''
  form.value.organizationId = res?.AD_Org_ID?.id || ''
  form.value.name = res?.Name || ''
  form.value.name2 = res?.Name2 || ''
  form.value.value = res?.Value || ''
  form.value.description = res?.Description || ''
  form.value.salesVolume = res?.SalesVolume || 0
  form.value.numberEmployees = res?.NumberEmployees || 0
  form.value.isActive = res?.IsActive ?? true
  form.value.isSummary = res?.IsSummary ?? false
  form.value.isVendor = res?.IsVendor ?? false
  form.value.isCustomer = res?.IsCustomer ?? false
  form.value.isProspect = res?.IsProspect ?? false
  form.value.soCreditLimit = res?.SoCreditLimit || 0
  form.value.soCreditUsed = res?.SoCreditUsed || 0
  form.value.acqusitionCost = res?.AcqusitionCost || 0
  form.value.potentialLifeTimeValue = res?.PotentialLifeTimeValue || 0
  form.value.actualLifeTimeValue = res?.ActualLifeTimeValue || 0
  form.value.shareOfCustomer = res?.ShareOfCustomer || 0
  form.value.isEmployee = res?.IsEmployee ?? false
  form.value.isSalesRep = res?.IsSalesRep ?? false
  form.value.isOneTime = res?.IsOneTime ?? false
  form.value.isTaxExempt = res?.IsTaxExempt ?? false
  form.value.isDiscountPrinted = res?.IsDiscountPrinted ?? false
  form.value.sendEMail = res?.SendEMail ?? false
  form.value.EMail = res?.EMail || ''
  form.value.totalOpenBalance = res?.TotalOpenBalance || 0
  form.value.isPOTaxExempt = res?.IsPOTaxExempt ?? false
  form.value.isManufacturer = res?.IsManufacturer ?? false
  form.value.is1099Vendor = res?.Is1099Vendor ?? false
  form.value.firstSale = res?.FirstSale || date.now('date')
  form.value.poReference = res?.POReference || ''
  form.value.referenceNo = res?.ReferenceNo || ''
  form.value.rating = res?.Rating || ''
  form.value.taxID = res?.TaxID || ''
  form.value.URL = res?.URL || ''
  form.value.NAICS = res?.NAICS || ''
  form.value.DUNS = res?.DUNS || ''
  form.value.documentCopies = res?.DocumentCopies || 0
  form.value.soDescription = res?.SODescription || ''
  form.value.flatDiscount = res?.FlatDiscount || 0
  form.value.shelfLifeMinPct = res?.ShelfLifeMinPct || 0
  form.value.dunningGrace = res?.DunningGrace || date.now('date')
  form.value.isFulfillmentCustomer = res?.isFulfillmentCustomer ?? false
  form.value.fulfillmentOrderBaseprice = res?.fulfillment_order_baseprice ?? 0
  form.value.fulfillmentOrderPickprice = res?.fulfillment_order_pickprice ?? 0
  form.value.fulfillmentOrderQtyPickfree = res?.fulfillment_order_qty_pickfree ?? 0
  form.value.fulfillmentOrderBaseprice2 = res?.fulfillment_order_baseprice_2 ?? 0
  form.value.fulfillmentOrderBaseprice3 = res?.fulfillment_order_baseprice_3 ?? 0
  form.value.fulfillmentOrderReturnBaseprice = res?.fulfillment_order_return_baseprice ?? 0
  form.value.fulfillmentOrderReturnPickprice = res?.fulfillment_order_return_pickprice ?? 0
  form.value.deliveryRule = res?.DeliveryRule?.identifier || ''
  form.value.deliveryRuleId = res?.DeliveryRule?.id || ''
  form.value.deliveryViaRule = res?.DeliveryViaRule?.identifier || ''
  form.value.deliveryViaRuleId = res?.DeliveryViaRule?.id || ''
  form.value.invoiceSchedule = res?.C_InvoiceSchedule_ID?.identifier || ''
  form.value.invoiceScheduleId = res?.C_InvoiceSchedule_ID?.id || ''
  form.value.greeting = res?.C_Greeting_ID?.identifier || ''
  form.value.greetingId = res?.C_Greeting_ID?.id || ''
  form.value.printFormat = res?.Invoice_PrintFormat_ID?.identifier || ''
  form.value.printFormatId = res?.Invoice_PrintFormat_ID?.id || ''
  form.value.salesRep = res?.SalesRep_ID?.identifier || ''
  form.value.salesRepId = res?.SalesRep_ID?.id || ''
  form.value.invoiceRule = res?.InvoiceRule?.identifier || ''
  form.value.invoiceRuleId = res?.InvoiceRule?.id || ''
  form.value.paymentRule = res?.PaymentRule?.identifier || ''
  form.value.paymentRuleId = res?.PaymentRule?.id || ''
  form.value.paymentRulePO = res?.PaymentRulePO?.identifier || ''
  form.value.paymentRulePOId = res?.PaymentRulePO?.id || ''
  form.value.soCreditStatus = res?.SOCreditStatus?.identifier || ''
  form.value.soCreditStatusId = res?.SOCreditStatus?.id || ''
  form.value.partnerGroup = res?.C_BP_Group_ID?.identifier || ''
  form.value.partnerGroupId = res?.C_BP_Group_ID?.id || ''
  form.value.priceList = res?.M_PriceList_ID?.identifier || ''
  form.value.priceListId = res?.M_PriceList_ID?.id || ''
  form.value.paymentTerm = res?.C_PaymentTerm_ID?.identifier || ''
  form.value.paymentTermId = res?.C_PaymentTerm_ID?.id || ''
  form.value.languageId = res?.AD_Language?.id || res?.AD_Language?.identifier || 'en_US'


  form2.value.id = res?.ship_address?.id ?? ''
  form2.value.uid = res?.ship_address?.uid ?? ''
  form2.value.client = res?.ship_address?.AD_Client_ID?.identifier ??  ''
  form2.value.clientId = res?.ship_address?.AD_Client_ID?.id ?? ''
  form2.value.organization = res?.ship_address?.AD_Org_ID?.identifier ?? ''
  form2.value.organizationId = res?.ship_address?.AD_Org_ID?.id ?? ''
  form2.value.isActive = res?.ship_address?.IsActive ?? true
  form2.value.address1 = res?.ship_address?.Address1 ?? ''
  form2.value.address2 = res?.ship_address?.Address2 ?? ''
  form2.value.address3 = res?.ship_address?.Address3 ?? ''
  form2.value.address4 = res?.ship_address?.Address4 ?? ''
  form2.value.city = res?.ship_address?.City ?? ''
  form2.value.postal = res?.ship_address?.Postal ?? ''
  form2.value.phone = res?.ship_address?.Phone ?? ''
  form2.value.regionName = res?.ship_address?.C_Region_ID?.identifier ?? ''
  form2.value.partnerLocationId = res?.ship_partnerlocation_id ?? ''
  form2.value.userId = res?.ship_user_id ?? ''
  form2.value.isValid = res?.ship_address?.IsValid ?? true
  form2.value.country = res?.ship_address?.C_Country_ID?.identifier ?? 'Germany'
  form2.value.countryId = res?.ship_address?.C_Country_ID?.id ?? '101'
  form2.value.region = res?.ship_address?.C_Region_ID?.identifier ?? ''
  form2.value.regionId = res?.ship_address?.C_Region_ID?.id ?? ''

  // Only populate bill address if it differs from ship address
  const shipId = res?.ship_address?.id ?? ''
  const billId = res?.bill_address?.id ?? ''
  const isBillDifferent = billId && shipId && billId !== shipId

  if (isBillDifferent) {
    form3.value.id = res?.bill_address?.id ?? ''
    form3.value.uid = res?.bill_address?.uid ?? ''
    form3.value.client = res?.bill_address?.AD_Client_ID?.identifier ?? ''
    form3.value.clientId = res?.bill_address?.AD_Client_ID?.id ?? ''
    form3.value.organization = res?.bill_address?.AD_Org_ID?.identifier ?? ''
    form3.value.organizationId = res?.bill_address?.AD_Org_ID?.id ?? ''
    form3.value.isDifferentAddress = true
    form3.value.isActive = res?.bill_address?.IsActive ?? true
    form3.value.address1 = res?.bill_address?.Address1 ?? ''
    form3.value.address2 = res?.bill_address?.Address2 ?? ''
    form3.value.address3 = res?.bill_address?.Address3 ?? ''
    form3.value.address4 = res?.bill_address?.Address4 ?? ''
    form3.value.city = res?.bill_address?.City ?? ''
    form3.value.postal = res?.bill_address?.Postal ?? ''
    form3.value.phone = res?.bill_address?.Phone ?? ''
    form3.value.regionName = res?.bill_address?.C_Region_ID?.identifier ?? ''
    form3.value.partnerLocationId = res?.bill_partnerlocation_id ?? ''
    form3.value.userId = res?.bill_user_id ?? ''
    form3.value.isValid = res?.bill_address?.IsValid ?? true
    form3.value.country = res?.bill_address?.C_Country_ID?.identifier ?? 'Germany'
    form3.value.countryId = res?.bill_address?.C_Country_ID?.id ?? '101'
    form3.value.region = res?.bill_address?.C_Region_ID?.identifier ?? ''
    form3.value.regionId = res?.bill_address?.C_Region_ID?.id ?? ''
  } else {
    form3.value.isDifferentAddress = false
  }
}

const checkEmailPartner = async () => {
  const res = await $fetch(`/api/partners/partners/email?org=${form.value.organizationId || props.modelValue.organizationId || organizationId.value}&email=${form.value.EMail}`, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res?.id) {
    populateFromResponse(res)
  }
  isEmailActive.value = true
  save()
}

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => { //saveType = ''
  //form.value.alert.processing = true

  emit('update:modelValue', form.value)
  emit('save', {
    partner: form.value,
    ship: form2.value,
    bill: form3.value,
    order: form4.value
  })
  /*if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }*/
})
</script>

<template>
  <div @mouseleave.self="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <h3 class="mb-2 fw-bold">Order Info</h3>
      <div class="columns is-desktop">
<!--        <div class="columns is-desktop" v-if="defaultSideBarMenu !== 'c'">-->
        <div v-if="defaultSideBarMenu !== 'c'" class="column is-two-thirds">
          <div class="legend mt-2">
            <label class="label">Organization *</label>
            <ClientOnly>
              <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {organizationHandler(val, opt); setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${opt.id}`), 'warehouses'); save();}" :loading="loading?.['orgs'] ?? true" />
            </ClientOnly>
          </div>
        </div>
        <div v-if="defaultSideBarMenu !== 'c'" class="column is-one-third">
          <div class="legend mt-2">
            <label class="label">Warehouse *</label>
            <ClientOnly>
              <SelectBox v-if="form.organizationId" v-model="form4.warehouseId" :options="getOptions?.['warehouses']?.records || [{id: form4.warehouseId, Name: form4.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${form.organizationId}`), 'warehouses')" @change="save" :loading="loading?.['warehouses'] ?? true" />
              <SelectBox v-else v-model="form4.warehouseId" :options="warehouses" @change="(val, opt) => {form4.warehouse = opt.name; save();}" prop="name" dataprop="id" datatype="string" :size="5" />
            </ClientOnly>
          </div>
        </div>
      </div>
      <div v-if="defaultSideBarMenu !== 'c'" class="columns is-desktop">
        <div class="column is-half">
          <div class="legend mt-2">
            <label class="label">Target Document Type *</label>
            <ClientOnly>
              <SelectBox v-model="form4.docTypeTargetId" :options="getOptions?.['doc_type_targets']?.records || [{id: form4.docTypeTargetId, Name: form4.docTypeTarget}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('types/SOO', 'doc_type_targets')" @change="save" :loading="loading?.['doc_type_targets'] ?? true" />
            </ClientOnly>
          </div>
        </div>
        <div class="column is-half"></div>
      </div>
      <!-- Delivery Via: fixed order (Shipper / Delivery / Pickup) with icons.
           Shipper selection only shows when Delivery Via = 'S'. -->
      <div class="legend mt-2">
        <label class="label">Delivery Via *</label>
        <div class="dvr-btn-row">
          <button
            v-for="btn in deliveryViaButtons"
            :key="btn.value"
            type="button"
            class="dvr-btn"
            :class="{ 'is-selected': String(form4.deliveryViaRuleId) === String(btn.value) }"
            @click="setDeliveryVia(btn)"
          >
            <i class="ti dvr-btn-icon" :class="btn.icon"></i>
            <span class="dvr-btn-body">
              <span class="dvr-btn-title">{{ btn.title }}</span>
              <span class="dvr-btn-desc">{{ btn.desc }}</span>
            </span>
          </button>
        </div>
      </div>
      <div v-if="form4.deliveryViaRuleId === 'S'" class="legend mt-2">
        <label class="label">Shipper</label>
        <ClientOnly>
          <SelectBox v-model="form4.shipperId" :options="getOptions?.['shippers']?.records || [{id: form4.shipperId, Name: form4.shipper}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_shipper?$select=name', 'shippers')" @change="save" :loading="loading?.['shippers'] ?? true" />
        </ClientOnly>
      </div>

      <!-- Shown for ALL roles when the selected shipper is an Amazon-FBA shipper -->
      <div v-if="form4.deliveryViaRuleId === 'S' && isFbaShipper(form4.shipperId)" class="legend mt-2">
        <div class="check">
          <input type="checkbox" v-model="form4.isRelabelByFulfillmentProvider" class="checkInput" id="quickAddIsRelabelByFulfillmentProvider" :checked="form4.isRelabelByFulfillmentProvider" @change="save">
          <label class="checkLabel" for="quickAddIsRelabelByFulfillmentProvider">{{ t?.relabel_by_provider || 'Umetikettierung durch Fulfillment-Dienstleister (Amazon FBA)' }}</label>
        </div>
      </div>

      <div v-if="defaultSideBarMenu !== 'c'" class="legend mt-2">
        <label class="label d-block">Auftragstyp</label>
        <div class="d-flex flexDirection-column" style="padding-left: 0.5rem; gap: 3px;">
          <div class="check">
            <input type="checkbox" v-model="form4.isFulfillmentOrder" class="checkInput" id="quickAddIsFulfillmentOrder" :checked="form4.isFulfillmentOrder" @change="save">
            <label class="checkLabel" for="quickAddIsFulfillmentOrder">Fulfillment-Auftrag</label>
          </div>
        </div>
      </div>

      <!-- Partner Search / Create Section -->
      <div v-if="!isEmailActive" class="mt-4">
        <h3 class="mb-2 fw-bold">Customer</h3>
        <div class="partner-search-wrapper">
          <div class="legend mt-2">
            <label class="label">Search customer or create new</label>
            <div class="partner-search-container">
              <input
                type="text"
                v-model="partnerSearchQuery"
                class="input"
                placeholder="Search by name, email, or customer number..."
                autocomplete="off"
                @focus="onSearchFocus"
                @blur="onSearchBlur"
              />
              <div v-if="partnerSearchOpen" class="partner-search-dropdown">
                <div class="partner-search-create" @mousedown.prevent="createNewPartner">
                  <span class="icon-text">+ Create new customer</span>
                  <span v-if="partnerSearchQuery.trim()" class="partner-search-create-hint">
                    "{{ partnerSearchQuery.trim() }}"
                  </span>
                </div>
                <div v-if="partnerSearchLoading" class="partner-search-loading">
                  Loading...
                </div>
                <template v-else>
                  <div
                    v-for="partner in filteredPartners"
                    :key="partner.id"
                    class="partner-search-item"
                    @mousedown.prevent="selectExistingPartner(partner)"
                  >
                    <div class="partner-search-item-name">{{ partner.Name }}</div>
                    <div class="partner-search-item-detail">
                      <span v-if="partner.EMail">{{ partner.EMail }}</span>
                      <span v-if="partner.EMail && partner.Value"> · </span>
                      <span v-if="partner.Value">{{ partner.Value }}</span>
                    </div>
                  </div>
                  <div v-if="filteredPartners.length === 0 && !partnerSearchLoading" class="partner-search-empty">
                    No customers found
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Partner Form (shown after selection or create-new) -->
      <div v-if="isEmailActive" class="columns is-desktop mt-2">
        <div class="column is-one-third">
          <div class="d-flex align-items-center mb-2">
            <h3 class="fw-bold mr-2">{{ isNewPartner ? 'New Customer' : 'Selected Customer' }}</h3>
            <button type="button" class="button is-small is-light" @click="resetPartnerSearch">Change</button>
          </div>
          <div class="legend mt-2">
            <label class="label">Email *</label>
            <input type="text" v-model="form.EMail" class="input" @keyup="save" />
          </div>
          <div class="legend mt-2">
            <label class="label">Name *</label>
            <input type="text" v-model="form.name" class="input" @keyup="save" />
          </div>
          <div class="legend mt-2">
            <label class="label">Firma</label>
            <input type="text" v-model="form.name2" class="input" @keyup="save" />
          </div>
          <div v-if="defaultSideBarMenu !== 'c'">
          <label class="label d-block mt-2" >Business Partner Group</label>
          <ClientOnly>
            <SelectBox v-model="form.partnerGroupId" :options="getOptions?.['partner_groups']?.records || [{id: form.partnerGroupId, Name: form.partnerGroup}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_bp_group', 'partner_groups')" @change="save" :loading="loading?.['partner_groups'] ?? true" />
          </ClientOnly>
          <label class="label d-block mt-2">Status</label>
          <div class="d-flex flexDirection-column px-3 gap-5px">
            <div class="check">
              <input type="checkbox" v-model="form.isCustomer" class="checkInput" id="isCustomer" :checked="form.isCustomer" @change="save">
              <label class="checkLabel" for="isCustomer">Customer</label>
            </div>
          </div>
          </div>
        </div>
        <div class="column is-one-third">
          <h3 class="mb-2 fw-bold">Address</h3>
          <div class="legend mt-2">
            <label class="label">Strasse *</label>
            <input type="text" v-model="form2.address1" class="input" @input="form3.address1 = form2.address1" />
          </div>

          <div class="legend mt-2">
            <label class="label d-block mt-2">City</label>
            <input type="text" v-model="form2.city" class="input" @input="form3.city = form2.city" />
          </div>
          <div class="legend mt-2">
            <label class="label">ZIP</label>
            <input type="text" v-model="form2.postal" class="input" @input="form3.postal = form2.postal" />
          </div>
          <div class="legend mt-2">
            <label class="label">Country *</label>
            <ClientOnly>
              <SelectBox v-model="form2.countryId" :options="getOptions?.['countries']?.records || [{id: form2.countryId, Name: form2.country}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'countries')" @change="(val, opt) => {setOptions('settings/regions/countries/'+opt.id, 'regions'); form2.country = opt.Name; form3.countryId = opt.id; form3.country = opt.Name;}" :loading="loading?.['countries'] ?? true" />
            </ClientOnly>
          </div>
          <div class="legend mt-2">
            <label class="label">Phone</label>
            <input type="text" v-model="form2.phone" class="input" @input="form3.phone = form2.phone" />
          </div>
        </div>
        <div v-if="form3.isDifferentAddress === false" class="column is-one-third">
          <div class="d-flex flexDirection-column px-3 gap-5px">
            <div class="check">
              <input type="checkbox" v-model="form3.isDifferentAddress" class="checkInput" id="isDifferentAddress" :checked="form3.isDifferentAddress" @change="save">
              <label class="checkLabel" for="isDifferentAddress">Different Ship-Address</label>
            </div>
          </div>
        </div>
        <div v-else class="column is-one-third">
          <h3 class="mb-2 fw-bold">Bill Address</h3>
          <div class="legend mt-2">
            <label class="label">Address 1 *</label>
            <input type="text" v-model="form3.address1" class="input" />
          </div>
          <div class="legend mt-2">
            <label class="label">Address 2</label>
            <input type="text" v-model="form3.address2" class="input" />
          </div>
          <div class="legend mt-2">
            <label class="label d-block mt-2">City</label>
            <input type="text" v-model="form3.city" class="input" />
          </div>
          <div class="legend mt-2">
            <label class="label">ZIP</label>
            <input type="text" v-model="form3.postal" class="input" />
          </div>
          <div class="legend mt-2">
            <label class="label">Country *</label>
            <ClientOnly>
              <SelectBox v-model="form3.countryId" :options="getOptions?.['countries']?.records || [{id: form3.countryId, Name: form3.country}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'countries')" @change="(val, opt) => {setOptions('settings/regions/countries/'+opt.id, 'regions'); form3.country = opt.Name;}" :loading="loading?.['countries'] ?? true" />
            </ClientOnly>
          </div>
          <div class="legend mt-2">
            <label class="label">Phone</label>
            <input type="text" v-model="form3.phone" class="input" />
          </div>
        </div>
      </div>

    </div>

  </div>
</template>

<style scoped>
.partner-search-wrapper {
  max-width: 500px;
}

.partner-search-container {
  position: relative;
}

.partner-search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 100;
  background: var(--theme-bg-primary, #fff);
  border: 1px solid var(--theme-border, #dbdbdb);
  border-top: none;
  border-radius: 0 0 4px 4px;
  max-height: 300px;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.partner-search-create {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 12px;
  cursor: pointer;
  font-weight: 600;
  color: var(--theme-primary, #3273dc);
  border-bottom: 1px solid var(--theme-border, #dbdbdb);
}

.partner-search-create:hover {
  background: var(--theme-bg-secondary, #f5f5f5);
}

.partner-search-create-hint {
  font-weight: 400;
  color: var(--theme-text-secondary, #7a7a7a);
  font-size: 0.9em;
}

.partner-search-item {
  padding: 8px 12px;
  cursor: pointer;
}

.partner-search-item:hover {
  background: var(--theme-bg-secondary, #f5f5f5);
}

.partner-search-item-name {
  font-weight: 500;
}

.partner-search-item-detail {
  font-size: 0.85em;
  color: var(--theme-text-secondary, #7a7a7a);
}

.partner-search-loading,
.partner-search-empty {
  padding: 10px 12px;
  color: var(--theme-text-secondary, #7a7a7a);
  font-style: italic;
}

/* Delivery Via button row — each button takes 1/3 of the row width */
.dvr-btn-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-top: 2px;
  width: 100%;
}
@media (max-width: 640px) {
  .dvr-btn-row { grid-template-columns: 1fr; }
}
.dvr-btn {
  display: flex; align-items: center; gap: 12px;
  padding: 12px 14px;
  width: 100%;
  background: var(--theme-bg-secondary, #f8f9fa);
  color: var(--theme-text-primary, #1f2937);
  border: 1.5px solid var(--theme-border, #e2e8f0);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.15s;
  text-align: left;
}
.dvr-btn-icon {
  flex-shrink: 0;
  font-size: 22px !important;
  color: #64748b;
}
.dvr-btn-body {
  display: flex; flex-direction: column; gap: 2px;
  min-width: 0; line-height: 1.25;
}
.dvr-btn-title { font-size: 13.5px; font-weight: 700; }
.dvr-btn-desc {
  font-size: 11.5px; font-weight: 500;
  color: var(--theme-text-secondary, #64748b);
  white-space: normal;
}
.dvr-btn:hover { border-color: #4a90e2; color: #1d4ed8; }
.dvr-btn:hover .dvr-btn-icon { color: #4a90e2; }
.dvr-btn.is-selected {
  background: rgba(74, 144, 226, 0.10);
  border-color: #4a90e2;
  color: #1d4ed8;
  box-shadow: 0 2px 8px rgba(74, 144, 226, 0.18);
}
.dvr-btn.is-selected .dvr-btn-icon { color: #4a90e2; }
.dvr-btn.is-selected .dvr-btn-desc { color: #3b82f6; }
.dvr-loading {
  display: inline-flex; align-items: center; gap: 6px;
  font-size: 13px; color: var(--theme-text-secondary, #64748b);
}
.dvr-loading i { animation: dvr-spin 1s linear infinite; }
@keyframes dvr-spin { to { transform: rotate(360deg); } }
[data-mode="dark"] .dvr-btn { background: #111827; border-color: #334155; color: #e2e8f0; }
[data-mode="dark"] .dvr-btn i { color: #94a3b8; }
[data-mode="dark"] .dvr-btn.is-selected { background: rgba(74, 144, 226, 0.16); border-color: #4a90e2; color: #93c5fd; }
</style>
