<script setup>
import InputGroup from "~/components/InputGroup.vue";
import dayjs from "dayjs";
import HistoryDisplay from "~/components/HistoryDisplay.vue";

const dataStore = useDataStore()
const supabase = useSupabaseClient()
const route = useRoute()
const router = useRouter()
const toast = useToast()

const {vendors} = storeToRefs(useDataStore())
const {fetchVendorInvoices} = useDataStore()

let currentVendorInvoice = ref(null)
//let currentDocument  = ref(null)
//Working
const mode = ref(route.params.mode || "show")
const useNetMode = ref(true)




//Functions
const setupPage = async () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentVendorInvoice.value = await dataStore.getIncomingInvoiceById(Number(useRoute().params.id))
    //currentDocument.value = await dataStore.getDocumentById(currentVendorInvoice.value.document)
  }

  if(mode.value === "edit") itemInfo.value = currentVendorInvoice.value
}

const currentDocument = computed(() => {
  if(currentVendorInvoice.value) {
    return dataStore.getDocumentById(currentVendorInvoice.value.document)

  } else {
    return null
  }

})



const itemInfo = ref({
  vendor: 0,
  expense: true,
  reference: "",
  date:  null,
  dueDate: null,
  paymentType: "",
  description: "",
  state: "Entwurf",
  accounts: [
    {
      account: null,
      amountNet: null,
      amountTax: null,
      taxType: null,
      costCentre: null
    }
  ]
})

const totalCalculated = computed(() => {
  let totalNet = 0
  let totalAmount19Tax = 0
  let totalAmount7Tax = 0
  let totalAmount0Tax = 0
  let totalGross = 0

  itemInfo.value.accounts.forEach(account => {
    if(account.amountNet) totalNet += account.amountNet

    if(account.taxType === 19 && account.amountTax) {
      totalAmount19Tax += account.amountTax
    }
  })

  totalGross = Number(totalNet + totalAmount19Tax)

  return {
    totalNet,
    totalAmount19Tax,
    totalGross
  }

})

const setState = async (newState) => {
  if(mode.value === 'show') {
    await dataStore.updateItem('incomingInvoices',{...currentVendorInvoice.value, state: newState})
  } else if(mode.value === 'edit') {
    await dataStore.updateItem('incomingInvoices',{...itemInfo.value, state: newState})
  }
  await router.push("/receipts")
}



setupPage()
</script>

<template>
  <div id="main">
    <object
        v-if="currentDocument ? currentDocument.url : false"
        :data="currentDocument.url + '#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0'"
        type="application/pdf"
        class="h-100 w-full mx-5"
    />
    <div class="w-4/5">
      <InputGroup class="mt-3" v-if="currentVendorInvoice">
        <UButton
            @click="dataStore.updateItem('incomingInvoices',itemInfo)"
            v-if="mode === 'edit'"
        >
          Speichern
        </UButton>
        <UButton
          :disabled="currentVendorInvoice.state !== 'Entwurf'"
          @click="router.push(`/incominginvoices/edit/${currentVendorInvoice.id}`)"
          v-if="mode !== 'edit'"
        >
          Bearbeiten
        </UButton>
        <UButton
            @click="setState('Entwurf')"
            v-if="currentVendorInvoice.state !== 'Entwurf'"
            color="cyan"
        >
          Status zu Entwurf
        </UButton>
        <UButton
            @click="setState('Gebucht')"
            v-if="currentVendorInvoice.state !== 'Gebucht'"
            color="rose"
        >
          Status auf Gebucht
        </UButton>
      </InputGroup>

      <div v-if="mode === 'show'">
        {{currentVendorInvoice}}
      </div>

      <div v-else-if="mode === 'edit'" class=" scrollContainer">
        <InputGroup class="my-3">
          <UButton
              :variant="itemInfo.expense ? 'solid' : 'outline'"
            @click="itemInfo.expense = true"
          >
            Ausgabe
          </UButton>
          <UButton
            :variant="!itemInfo.expense ? 'solid' : 'outline'"
            @click="itemInfo.expense = false"
          >
            Einnahme
          </UButton>
        </InputGroup>

        <UFormGroup label="Lieferant:" required>
          <InputGroup>
            <USelectMenu
                v-model="itemInfo.vendor"
                :options="dataStore.vendors"
                option-attribute="name"
                value-attribute="id"
                searchable
                :search-attributes="['name','vendorNumber']"
                class="flex-auto"
            >
              <template #label>
                {{dataStore.vendors.find(vendor => vendor.id === itemInfo.vendor) ? dataStore.vendors.find(vendor => vendor.id === itemInfo.vendor).name : 'Lieferant auswählen'}}
              </template>
            </USelectMenu>
            <UButton
                @click="router.push('/vendors/create')"
            >
              + Lieferant
            </UButton>
          </InputGroup>


        </UFormGroup>

        <UFormGroup
            class="mt-3"
            label="Rechnungsreferenz:"
            required
        >
          <UInput
              v-model="itemInfo.reference"
          />
        </UFormGroup>

        <InputGroup class="mt-3" gap="2">
          <UFormGroup label="Rechnungsdatum:" required>
            <UPopover :popper="{ placement: 'bottom-start' }">
              <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.date ? dayjs(itemInfo.date).format('DD.MM.YYYY') : 'Datum auswählen'" />

              <template #panel="{ close }">
                <LazyDatePicker v-model="itemInfo.date" @close="close" />
              </template>
            </UPopover>
          </UFormGroup>

          <UFormGroup label="Fälligkeitsdatum:" required>
            <UPopover :popper="{ placement: 'bottom-start' }">
              <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.dueDate ? dayjs(itemInfo.dueDate).format('DD.MM.YYYY') : 'Datum auswählen'" />

              <template #panel="{ close }">
                <LazyDatePicker v-model="itemInfo.dueDate" @close="close" />
              </template>
            </UPopover>
          </UFormGroup>
        </InputGroup>



        <UFormGroup label="Beschreibung:" required>
          <UTextarea
              v-model="itemInfo.description"
          />
        </UFormGroup>

        <InputGroup class="my-3">
          Brutto
          <UToggle
              v-model="useNetMode"
              @update:model-value="itemInfo.accounts = [{account: null,amountNet: null,amountTax: null,taxType: null}]"
          />
          Netto
        </InputGroup>

        <table v-if="itemInfo.accounts.length > 1">
          <tr>
            <td>Gesamt exkl. Steuer: </td>
            <td class="text-right">{{totalCalculated.totalNet.toFixed(2)}} €</td>
          </tr>
          <tr>
            <td>19% Steuer: </td>
            <td class="text-right">{{totalCalculated.totalAmount19Tax.toFixed(2)}} €</td>
          </tr>
          <tr>
            <td>Gesamt inkl. Steuer: </td>
            <td class="text-right">{{totalCalculated.totalGross.toFixed(2)}} €</td>
          </tr>
        </table>

        <div
            class="my-3"
            v-for="(item,index) in itemInfo.accounts"
        >

          <UFormGroup
              label="Kategorie"
              class=" mb-3"
          >
            <USelectMenu
                :options="dataStore.accounts"
                option-attribute="label"
                value-attribute="id"
                searchable
                :search-attributes="['label']"
                searchable-placeholder="Suche..."
                v-model="item.account"
            >
              <template #label>
                {{dataStore.accounts.find(account => account.id === item.account) ? dataStore.accounts.find(account => account.id === item.account).label : "Keine Kategorie ausgewählt" }}
              </template>

            </USelectMenu>
          </UFormGroup>
          <UFormGroup
              label="Kostenstelle"
              class=" mb-3"
          >
            <USelectMenu
                :options="dataStore.getCostCentresComposed"
                option-attribute="label"
                value-attribute="id"
                searchable
                :search-attributes="['label']"
                searchable-placeholder="Suche..."
                v-model="item.costCentre"
            >
              <template #label>
                {{dataStore.getCostCentresComposed.find(account => account.id === item.costCentre) ? dataStore.getCostCentresComposed.find(account => account.id === item.costCentre).label : "Keine Kostenstelle ausgewählt" }}
              </template>

            </USelectMenu>
          </UFormGroup>



          <InputGroup>
            <UFormGroup
                label="Umsatzsteuer"
                class="w-32"
                :help="`Betrag: ${item.amountTax ? String(item.amountTax).replace('.',',') : '0,00'} €`"
            >
              <USelectMenu
                  :options="[19,7,0]"
                  v-model="item.taxType"
                  @change="item.amountTax = Number(((item.amountNet ? item.amountNet : 0) * (Number(item.taxType)/100)).toFixed(2))"
              >
                <template #label>
                  {{item.taxType}} %
                </template>
              </USelectMenu>
            </UFormGroup>
            <UFormGroup
                v-if="useNetMode"
                label="Gesamtbetrag exkl. Steuer in EUR"
                class="flex-auto"
                :help="item.taxType !== null ? `Betrag inkl. Steuern: ${String(Number(item.amountNet + item.amountTax).toFixed(2)).replace('.',',')} €` : 'Zuerst Steuertyp festlegen' "

            >
              <UInput
                  type="number"
                  step="0.01"
                  v-model="item.amountNet"
                  :disabled="item.taxType === null"
                  @keyup="item.amountTax = Number((item.amountNet * (Number(item.taxType)/100)).toFixed(2))"
              >
                <template #trailing>
                  <span class="text-gray-500 dark:text-gray-400 text-xs">EUR</span>
                </template>
              </UInput>
            </UFormGroup>
            <UFormGroup
                v-else
                label="Gesamtbetrag inkl. Steuer in EUR"
                class="flex-auto"
                :help="item.taxType !== null ? `Betrag exkl. Steuern: ${item.amountNet ? String(item.amountNet.toFixed(2)).replace('.',',') : '0,00'} €` : 'Zuerst Steuertyp festlegen' "

            >
              <UInput
                  type="number"
                  step="0.01"
                  :disabled="item.taxType === null"
                  v-model="item.amountGross"
                  @keyup="item.amountNet = Number((item.amountGross / (1 + Number(item.taxType)/100)).toFixed(2)),
                  item.amountTax = Number((item.amountGross - item.amountNet).toFixed(2))"
              >
                <template #trailing>
                  <span class="text-gray-500 dark:text-gray-400 text-xs">EUR</span>
                </template>
              </UInput>

            </UFormGroup>


          </InputGroup>


          <UButton
              class="mt-3"
              @click="itemInfo.accounts = [...itemInfo.accounts.slice(0,index+1),{account:null, amountNet: null, amountTax:null, taxType: null} , ...itemInfo.accounts.slice(index+1)]"
          >
            Position hinzufügen
          </UButton>
          <UButton
              v-if="index !== 0"
              class="mt-3"
              variant="ghost"
              color="rose"
              @click="itemInfo.accounts = itemInfo.accounts.filter((account,itemIndex) => itemIndex !== index)"
          >
            Position entfernen
          </UButton>

        </div>
        <HistoryDisplay
            type="incomingInvoice"
            v-if="currentVendorInvoice"
            :element-id="currentVendorInvoice.id"
        />
      </div>
    </div>

  </div>

</template>

<style scoped>
#main {
  display: flex;
  flex-direction: row;
  height: 85vh;
}

.previewDoc {
  min-width: 50vw;
  min-height: 80vh;
}

.previewDoc object {
  width: 90%;
  height: 100%;
}



.scrollContainer {
  overflow-y: scroll;
  height: 75vh;
  margin-top: 1em;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.scrollContainer::-webkit-scrollbar {
  display: none;
}


.lineItemRow {
  display: flex;
  flex-direction: row;
}
</style>