<script setup>
definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()
const router = useRouter()
const mode = ref("incoming")
const toast = useToast()

const inventoryChangeData = ref({
  productId: null,
  sourceSpaceId: null,
  sourceProjectId: null,
  destinationSpaceId: null,
  destinationProjectId: null,
  quantity: 1,
  serials: []
})

const resetInput = () => {
  inventoryChangeData.value = {
    productId: null,
    sourceSpaceId: null,
    sourceProjectId: null,
    destinationSpaceId: null,
    destinationProjectId: null,
    quantity: 1
  }
}

const createMovement = async () => {

  let movements = []

  if(mode.value === 'incoming'){

    let movement = {
      productId: inventoryChangeData.value.productId,
      spaceId: inventoryChangeData.value.destinationSpaceId,
      projectId: inventoryChangeData.value.destinationProjectId,
      quantity: inventoryChangeData.value.quantity,
      profileId: profileStore.activeProfile.id,
      tenant: profileStore.currentTenant
    }

    movements.push(movement)

    /*const {error} = await supabase
        .from("movements")
        .insert([inventoryChangeData.value])
        .select()
    if(error) console.log(error)*/


  } else if (mode.value === 'outgoing'){

    let movement = {
      productId: inventoryChangeData.value.productId,
      spaceId: inventoryChangeData.value.sourceSpaceId,
      projectId: inventoryChangeData.value.sourceProjectId,
      quantity: inventoryChangeData.value.quantity * -1,
      profileId: profileStore.activeProfile.id,
      tenant: profileStore.currentTenant
    }

    movements.push(movement)
  } else if (mode.value === 'change'){
    let outMovement = {
      productId: inventoryChangeData.value.productId,
      spaceId: inventoryChangeData.value.sourceSpaceId,
      projectId: inventoryChangeData.value.sourceProjectId,
      quantity: inventoryChangeData.value.quantity * -1,
      profileId: profileStore.activeProfile.id,
      tenant: profileStore.currentTenant
    }
    let inMovement = {
      productId: inventoryChangeData.value.productId,
      spaceId: inventoryChangeData.value.destinationSpaceId,
      projectId: inventoryChangeData.value.destinationProjectId,
      quantity: inventoryChangeData.value.quantity,
      profileId: profileStore.activeProfile.id,
      tenant: profileStore.currentTenant
    }

    movements.push(outMovement)
    movements.push(inMovement)
  }

  console.log(movements)

  const {error} = await supabase
        .from("movements")
        .insert(movements)
        .select()
    if(error) {
      console.log(error)
    } else {
      resetInput()
    }





}

defineShortcuts({
  meta_enter: {
    usingInput: true,
    handler: () => {
      createMovement()
    }
  }
})


function checkProductId(productId) {
  return dataStore.products.filter(product =>product.id === productId).length > 0;
}
function checkSpaceId(spaceId) {
  return dataStore.spaces.filter(space => space.id === spaceId).length > 0;
}

function checkProjectId(projectId) {
  return dataStore.projects.some(i => i.id === projectId)
}

function changeFocusToSpaceId() {
  document.getElementById('spaceIdInput').focus()
}

function changeFocusToQuantity() {
  document.getElementById('quantityInput').focus()
}

function changeFocusToBarcode() {
  document.getElementById('barcodeInput').focus()
}


const findProductByBarcodeOrEAN = (input) => {
  return dataStore.products.find(i => i.barcode === input || i.ean === input || i.articleNumber === input)
}

const findSpaceBySpaceNumber = (input) => {
  return dataStore.spaces.find(i => i.spaceNumber === input)
}





const barcodeInput = ref("")
const showBarcodeTip = ref(true)
const serialInput = ref("")

const processBarcodeInput = () => {
  if(findProductByBarcodeOrEAN(barcodeInput.value) && !findSpaceBySpaceNumber(barcodeInput.value)){
    //Set Product

    inventoryChangeData.value.productId = findProductByBarcodeOrEAN(barcodeInput.value).id
  } else if (!findProductByBarcodeOrEAN(barcodeInput.value) && findSpaceBySpaceNumber(barcodeInput.value)){
    //Set Space

    if(mode.value === 'incoming'){
      inventoryChangeData.value.destinationSpaceId = findSpaceBySpaceNumber(barcodeInput.value).id
    } else if(mode.value === 'outgoing') {
      inventoryChangeData.value.sourceSpaceId = findSpaceBySpaceNumber(barcodeInput.value).id
    } else if(mode.value === 'change') {
      if(!inventoryChangeData.value.sourceSpaceId){
        inventoryChangeData.value.sourceSpaceId = findSpaceBySpaceNumber(barcodeInput.value).id
      } else {
        inventoryChangeData.value.destinationSpaceId = findSpaceBySpaceNumber(barcodeInput.value).id
      }
    }
    //console.log(findSpaceBySpaceNumber(barcodeInput.value))
  }
  barcodeInput.value = ""
  //console.log(movementData.value)
}

</script>

<template>
  <UDashboardNavbar
    title="Lager Vorgänge"
  >
      <template #right>
        <UButton
            @click="resetInput"
            class="mt-3"
            color="rose"
            variant="outline"
        >
          Abbrechen
        </UButton>
        <UButton
            @click="createMovement"
            :disabled="mode === '' && checkSpaceId(inventoryChangeData.spaceId) && checkProductId(inventoryChangeData.productId)"
            class="mt-3"
        >
          Bestätigen
        </UButton>

      </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <div class="w-80 mx-auto mt-5">
      <div class="flex flex-col">
        <UButton
            @click="mode = 'incoming'"
            class="my-2"
            :variant="mode === 'incoming' ? 'solid' : 'outline'"
        >Wareneingang</UButton>
        <UButton
            @click="mode = 'outgoing'"
            class="my-2"
            :variant="mode === 'outgoing' ? 'solid' : 'outline'"
        >Warenausgang</UButton>
        <UButton
            @click="mode = 'change'"
            class="my-2"
            :variant="mode === 'change' ? 'solid' : 'outline'"
        >Umlagern</UButton>
      </div>

      <UAlert
          title="Info"
          variant="outline"
          color="primary"
          v-if="showBarcodeTip"
          @close="showBarcodeTip = false"
          :close-button="{ icon: 'i-heroicons-x-mark-20-solid', color: 'gray', variant: 'link', padded: false }"
          description="Über die Barcode Eingabe können folgende Werte automatisch erkannt werden: Quelllagerplatz, Ziellagerplatz, Artikel (EAN oder Barcode). Es wird immer zuerst der Quell- und anschließend der Ziellagerplatz ausgefüllt."
      />

      <!--    <UTooltip
              text="Über die Barcode Eingabe könenn folgende Werte automatisch erkannt werden: Quell Lagerplatz, Ziellagerplatz, Artikel(EAN oder Barcode). Es wird immer zuerst der Quell- und anschließend der Ziellagerplatz ausgefüllt."
          >-->
      <UFormGroup
          label="Barcode:"
          class="mt-3"
      >
        <UInput
            @keyup.enter="processBarcodeInput"
            @focusout="processBarcodeInput"
            @input="processBarcodeInput"
            v-model="barcodeInput"
            id="barcodeInput"

        />

      </UFormGroup>
      <!--      <template #text>
              <span class="text-wrap">Über die Barcode Eingabe könenn folgende Werte automatisch erkannt werden: Quell Lagerplatz, Ziellagerplatz, Artikel(EAN oder Barcode). Es wird immer zuerst der Quell- und anschließend der Ziellagerplatz ausgefüllt.</span>

            </template>
          </UTooltip>-->

      <UDivider
          class="mt-5 w-80"
          v-if="mode !== 'incoming'"
      />

      <UFormGroup
          label="Quell Lagerplatz:"
          class="mt-3 w-80"
          v-if="mode !== 'incoming' "
      >
        <USelectMenu
            :options="dataStore.spaces"
            searchable
            option-attribute="spaceNumber"
            :color="checkSpaceId(inventoryChangeData.sourceSpaceId) ? 'primary' : 'rose'"
            v-model="inventoryChangeData.sourceSpaceId"
            @change="inventoryChangeData.sourceProjectId = null"
            value-attribute="id"
        >
          <template #label>
            {{dataStore.spaces.find(space => space.id === inventoryChangeData.sourceSpaceId) ? dataStore.spaces.find(space => space.id === inventoryChangeData.sourceSpaceId).description : "Kein Lagerplatz ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Quell Projekt:"
          class="mt-3 w-80"
          v-if="mode !== 'incoming' "
      >
        <USelectMenu
            :options="dataStore.projects"
            searchable
            option-attribute="name"
            :color="checkProjectId(inventoryChangeData.sourceProjectId) ? 'primary' : 'rose'"
            v-model="inventoryChangeData.sourceProjectId"
            @change="inventoryChangeData.sourceSpaceId = null"
            value-attribute="id"
        >
          <template #label>
            {{dataStore.getProjectById(inventoryChangeData.sourceProjectId) ? dataStore.getProjectById(inventoryChangeData.sourceProjectId).name : "Kein Projekt ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UDivider
          class="mt-5 w-80"
      />

      <UFormGroup
          label="Artikel:"
          class="mt-3 w-80"
      >
        <USelectMenu
            :options="dataStore.products"
            option-attribute="name"
            value-attribute="id"
            variant="outline"
            searchable
            :search-attributes="['name','ean', 'barcode']"
            :color="checkProductId(inventoryChangeData.productId) ? 'primary' : 'rose'"
            v-model="inventoryChangeData.productId"
            v-on:select="changeFocusToSpaceId"
        >
          <template #label>
            {{dataStore.products.find(product => product.id === inventoryChangeData.productId) ? dataStore.products.find(product => product.id === inventoryChangeData.productId).name : "Bitte Artikel auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UDivider
          class="mt-5 w-80"
          v-if="mode !== 'outgoing'"
      />

      <UFormGroup
          label="Ziel Lagerplatz:"
          class="mt-3 w-80"
          v-if="mode !== 'outgoing'"
      >
        <USelectMenu
            :options="dataStore.spaces"
            searchable
            option-attribute="spaceNumber"
            :color="checkSpaceId(inventoryChangeData.destinationSpaceId) ? 'primary' : 'rose'"
            v-model="inventoryChangeData.destinationSpaceId"
            @change="inventoryChangeData.destinationProjectId = null"
            value-attribute="id"
        >
          <template #label>
            {{dataStore.spaces.find(space => space.id === inventoryChangeData.destinationSpaceId) ? dataStore.spaces.find(space => space.id === inventoryChangeData.destinationSpaceId).description : "Kein Lagerplatz ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Ziel Projekt:"
          class="mt-3 w-80"
          v-if="mode !== 'outgoing'"
      >
        <USelectMenu
            :options="dataStore.projects"
            searchable
            option-attribute="name"
            :color="checkProjectId(inventoryChangeData.destinationProjectId) ? 'primary' : 'rose'"
            v-model="inventoryChangeData.destinationProjectId"
            value-attribute="id"
            @change="inventoryChangeData.destinationSpaceId = null"
        >
          <template #label>
            {{dataStore.getProjectById(inventoryChangeData.destinationProjectId) ? dataStore.getProjectById(inventoryChangeData.destinationProjectId).name : "Kein Projekt ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UDivider
          class="mt-5 w-80"
      />

      <UFormGroup
          label="Anzahl:"
          class="mt-3 w-80"
      >
        <UInput
            variant="outline"
            color="primary"
            placeholder="Anzahl"
            v-model="inventoryChangeData.quantity"
            type="number"
            id="quantityInput"
        />
      </UFormGroup>
      <UFormGroup
          label="Seriennummern:"
          class="mt-3 w-80"
      >
        <InputGroup class="w-full">
          <UInput
              variant="outline"
              color="primary"
              placeholder="Seriennummern"
              v-model="serialInput"
          />
          <UButton
              @click="inventoryChangeData.serials.push(serialInput)"
          >
            +
          </UButton>
        </InputGroup>

      </UFormGroup>

      <ul>
        <li v-for="serial in inventoryChangeData.serials">{{serial}}</li>
      </ul>

    </div>
  </UDashboardPanelContent>





</template>

<style scoped>

</style>