<template>
  <h1>Create Lane</h1>

  <form v-if="!createdLink" @submit.prevent="submit">
    <fieldset>
      <legend>Internal Reference</legend>
      <label for="laneId">Lane ID</label><br>
      <input id="laneId" v-model="form.laneId" type="text" placeholder="e.g. LN-2094">
    </fieldset>

    <fieldset>
      <legend>State Codes</legend>
      <label for="pickupState">Pickup State</label><br>
      <input id="pickupState" v-model="form.pickupState" type="text" maxlength="2" placeholder="e.g. CA">
      <br><br>
      <label for="dropoffState">Dropoff State</label><br>
      <input id="dropoffState" v-model="form.dropoffState" type="text" maxlength="2" placeholder="e.g. TX">
    </fieldset>

    <fieldset>
      <legend>Addresses</legend>
      <label for="pickupAddress">Pickup Address</label><br>
      <input id="pickupAddress" v-model="form.pickupAddress" type="text" placeholder="123 Warehouse Blvd, Los Angeles, CA 90001">
      <br><br>
      <label for="dropoffAddress">Dropoff Address</label><br>
      <input id="dropoffAddress" v-model="form.dropoffAddress" type="text" placeholder="456 Distribution Dr, Houston, TX 77001">
    </fieldset>

    <p v-if="error" style="color:red">{{ error }}</p>
    <button type="submit">Create Lane</button>
  </form>

  <div v-else>
    <p>Lane created. Share this link with carriers:</p>
    <a :href="createdLink">{{ createdLink }}</a>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const form = reactive({
  laneId: '',
  pickupState: '',
  dropoffState: '',
  pickupAddress: '',
  dropoffAddress: '',
})

const error = ref('')
const createdLink = ref('')

const hasLaneId    = () => form.laneId.trim() !== ''
const hasStateCodes = () => form.pickupState.trim() !== '' && form.dropoffState.trim() !== ''
const hasAddresses  = () => form.pickupAddress.trim() !== '' && form.dropoffAddress.trim() !== ''

async function submit() {
  error.value = ''

  if (!hasLaneId() && !hasStateCodes() && !hasAddresses()) {
    error.value = 'Provide at least a Lane ID, both state codes, or both addresses.'
    return
  }

  const res = await fetch('/lanes', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      lane_id:         form.laneId       || null,
      pickup_state:    form.pickupState  || null,
      dropoff_state:   form.dropoffState || null,
      pickup_address:  form.pickupAddress  || null,
      dropoff_address: form.dropoffAddress || null,
    }),
  })

  if (!res.ok) {
    const body = await res.json()
    error.value = body.error?.message ?? 'Failed to create lane.'
    return
  }

  const { data } = await res.json()
  createdLink.value = `${window.location.origin}/lanes/${data.id}`
}
</script>
