<script setup>
import { toast } from 'bulma-toast'

// Create a fulfiller warehouse (Lager anlegen) -> POST /api/ffn/warehouses (via Laravel, global creds).
// Schema confirmed from the live API: { name, address: { street*, city*, country*, zip, company, ... } }
const emit = defineEmits(['close', 'created'])

const submitting = ref(false)
const errorMsg = ref('')
const useRaw = ref(false)
const rawJson = ref('{\n  \n}')

const form = ref({
  name: '',
  company: '',
  firstname: '',
  lastname: '',
  street: '',
  zip: '',
  city: '',
  country: 'DE',
  email: '',
  phone: ''
})

const buildPayload = () => {
  if (useRaw.value) return JSON.parse(rawJson.value || '{}')
  const address = {
    company: form.value.company,
    firstname: form.value.firstname,
    lastname: form.value.lastname,
    street: form.value.street,
    zip: form.value.zip,
    city: form.value.city,
    country: form.value.country,
    email: form.value.email,
    phone: form.value.phone
  }
  // drop empty optionals
  Object.keys(address).forEach(k => { if (!address[k]) delete address[k] })
  return { name: form.value.name, address }
}

const submit = async () => {
  submitting.value = true
  errorMsg.value = ''
  let payload
  try { payload = buildPayload() } catch (e) { errorMsg.value = 'Invalid JSON in advanced editor'; submitting.value = false; return }
  try {
    const res = await $fetch('/api/ffn/warehouses', {
      method: 'POST', headers: useRequestHeaders(['cookie']),
      body: { warehouse: payload }
    })
    const ok = res?.success === true || (Number(res?.status || 200) < 400 && res?.success !== false)
    if (!ok) {
      const e = res?.error
      errorMsg.value = e ? (typeof e === 'string' ? e : JSON.stringify(e)) : (res?.message || 'Failed to create warehouse')
      toast({ message: errorMsg.value, type: 'is-danger', duration: 4000 })
      return
    }
    toast({ message: 'Warehouse created', type: 'is-success', duration: 2500 })
    emit('created'); emit('close')
  } catch (err) {
    errorMsg.value = err?.data?.message || err?.message || 'Failed to create warehouse'
    toast({ message: errorMsg.value, type: 'is-danger', duration: 4000 })
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="modal is-active">
    <div class="modal-background" @click="emit('close')"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Create warehouse (Lager)</p>
        <button class="delete" aria-label="close" @click="emit('close')"></button>
      </header>
      <section class="modal-card-body">
        <div v-if="errorMsg" class="notification is-danger is-light">{{ errorMsg }}</div>
        <label class="checkbox mb-3 is-block"><input type="checkbox" v-model="useRaw" /> Advanced: edit raw JSON payload</label>

        <template v-if="!useRaw">
          <div class="field"><label class="label">Name *</label><div class="control"><input class="input" v-model="form.name" placeholder="LogYou Fulfillment" /></div></div>
          <div class="field"><label class="label">Company</label><div class="control"><input class="input" v-model="form.company" placeholder="LogYou GmbH" /></div></div>
          <div class="columns">
            <div class="column"><div class="field"><label class="label">First name</label><div class="control"><input class="input" v-model="form.firstname" /></div></div></div>
            <div class="column"><div class="field"><label class="label">Last name</label><div class="control"><input class="input" v-model="form.lastname" /></div></div></div>
          </div>
          <div class="field"><label class="label">Street *</label><div class="control"><input class="input" v-model="form.street" placeholder="Mühlenweg 4" /></div></div>
          <div class="columns">
            <div class="column is-one-third"><div class="field"><label class="label">ZIP</label><div class="control"><input class="input" v-model="form.zip" placeholder="35510" /></div></div></div>
            <div class="column"><div class="field"><label class="label">City *</label><div class="control"><input class="input" v-model="form.city" placeholder="Butzbach" /></div></div></div>
            <div class="column is-one-quarter"><div class="field"><label class="label">Country *</label><div class="control"><input class="input" v-model="form.country" maxlength="2" placeholder="DE" /></div></div></div>
          </div>
          <div class="columns">
            <div class="column"><div class="field"><label class="label">Email</label><div class="control"><input class="input" v-model="form.email" /></div></div></div>
            <div class="column"><div class="field"><label class="label">Phone</label><div class="control"><input class="input" v-model="form.phone" /></div></div></div>
          </div>
        </template>
        <template v-else>
          <div class="field"><label class="label">Raw warehouse payload (JSON)</label><div class="control"><textarea class="textarea" rows="10" v-model="rawJson"></textarea></div></div>
        </template>
      </section>
      <footer class="modal-card-foot">
        <button class="button is-primary" :class="{ 'is-loading': submitting }" @click="submit">Create</button>
        <button class="button" @click="emit('close')">Cancel</button>
      </footer>
    </div>
  </div>
</template>

<style scoped>.is-block { display: block; }</style>
