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

definePageMeta({
  middleware: "auth"
})

const supabase = useSupabaseClient()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )
const numberRange = useNumberRange("customers")
const dataStore = useDataStore()

let currentCustomer = ref(null)



//Working
const mode = ref(route.params.mode || "show")
const customerInfo = ref({
  name: "",
  infoData: {},
  active: true
})

//Functions
const setupPage = async () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentCustomer.value = await dataStore.getCustomerById(Number(useRoute().params.id))
  }

  if(mode.value === "edit") customerInfo.value = currentCustomer.value


}

const createCustomer = async () => {

  if(!customerInfo.value.customerNumber) customerInfo.value.customerNumber = await numberRange.useNextNumber()


  const {data,error} = await supabase
      .from("customers")
      .insert([customerInfo.value])
      .select()

  if(error) {
    console.log(error)
  } else {
    mode.value = "show"
    customerInfo.value = {
      id: 0,
      name: "",
      infoData: {}
    }
    toast.add({title: "Kunde erfolgreich erstellt"})
    await dataStore.fetchCustomers()
    router.push(`/customers/show/${data[0].id}`)
    setupPage()
  }
}

const editCustomer = async () => {
  router.push(`/customers/edit/${currentCustomer.value.id}`)
  setupPage()
}

const cancelEditorCreate = () => {
  mode.value = "show"
  customerInfo.value = {
    id: 0,
    name: "",
    infoData: {}
  }
}

const updateCustomer = async () => {
  const {error} = await supabase
      .from("customers")
      .update(customerInfo.value)
      .eq('id',customerInfo.value.id)

  if(error) {
    console.log(error)
  }
  toast.add({title: "Kunde erfolgreich gespeichert"})
  router.push(`/customers/show/${currentCustomer.id}`)
  dataStore.fetchCustomers()
}



setupPage()
</script>

<template>
  <UCard v-if="currentCustomer && mode == 'show'" >
    <template #header>
      <UBadge
          v-if="currentCustomer.active"
      >
        Kunde aktiv
      </UBadge>
      <UBadge
          v-else
          color="red"
      >
        Kunde gesperrt
      </UBadge>
      {{currentCustomer.name}}
    </template>

    <InputGroup>
      <UButton
        @click="router.push(`/projects/create?customer=${currentCustomer.id}`)"
      >
        + Projekt
      </UButton>
      <UButton
        @click="router.push(`/contacts/create?customer=${currentCustomer.id}`)"
      >
        + Ansprechpartner
      </UButton>
    </InputGroup>


    Kundennummer: {{currentCustomer.customerNumber}} <br>

    <UDivider
        class="my-2"
    />

    Informationen:<br>
    <div v-if="currentCustomer.infoData">
      <span v-if="currentCustomer.infoData.street">Straße + Hausnummer: {{currentCustomer.infoData.street}}<br></span>
      <span v-if="currentCustomer.infoData.zip && currentCustomer.infoData.city">PLZ + Ort: {{currentCustomer.infoData.zip}} {{currentCustomer.infoData.city}}<br></span>
      <span v-if="currentCustomer.infoData.tel">Telefon: {{currentCustomer.infoData.tel}}<br></span>
      <span v-if="currentCustomer.infoData.email">E-Mail: {{currentCustomer.infoData.email}}<br></span>
      <span v-if="currentCustomer.infoData.web">Web: {{currentCustomer.infoData.web}}<br></span>
      <span v-if="currentCustomer.infoData.ustid">USt-Id: {{currentCustomer.infoData.ustid}}<br></span>
    </div>

    <UDivider
        class="my-2"
    />

    Notizen:<br>
    {{currentCustomer.notes}}<br>

    <UDivider
        class="my-2"
    />

    Kontakte: <br>

    <ul>
      <li
          v-for="contact in dataStore.getContactsByCustomerId(currentCustomer.id)"
      >
        <router-link :to="'/contacts/show/' + contact.id">{{contact.salutation}} {{contact.fullName}} - {{contact.role}}</router-link>
      </li>
    </ul>




    <template #footer>
      <UButton
          v-if="mode == 'show' && currentCustomer.id"
          @click="editCustomer"
      >
        Bearbeiten
      </UButton>
      <UButton
          color="red"
          class="ml-2"
          disabled
      >
        Archivieren
      </UButton>
      <!-- TODO: Kunde archivieren        -->
    </template>



  </UCard>
  <UCard v-else-if="mode == 'edit' || mode == 'create'" >
    <template #header v-if="mode === 'edit'">
      <UBadge>{{customerInfo.customerNumber}}</UBadge>{{customerInfo.name}}
    </template>

    <UFormGroup
        label="Name:"
    >
      <UInput
          v-model="customerInfo.name"
      />
    </UFormGroup>

    <UFormGroup
        label="Kundennummer:"
    >
      <UInput
          v-model="customerInfo.customerNumber"
          placeholder="Leer lassen für automatisch generierte Nummer"
      />
    </UFormGroup>

    <UTooltip text="Ist ein Kunde nicht aktiv so wird er für neue Aufträge gesperrt">
      <UFormGroup
          label="Kunde aktiv:"
      >
        <UCheckbox
            v-model="customerInfo.active"
        />
      </UFormGroup>
    </UTooltip>
    <UFormGroup
        label="Notizen:"
    >
      <UTextarea
          v-model="customerInfo.notes"
      />
    </UFormGroup>

    <UFormGroup
        label="Straße + Hausnummer"
    >
      <UInput
          v-model="customerInfo.infoData.street"
      />
    </UFormGroup>
    <UFormGroup
        label="Postleitzahl"
    >
      <UInput
          v-model="customerInfo.infoData.zip"
      />
    </UFormGroup>
    <UFormGroup
        label="Ort"
    >
      <UInput
          v-model="customerInfo.infoData.city"
      />
    </UFormGroup>

    <UFormGroup
        label="Telefon:"
    >
      <UInput
          v-model="customerInfo.infoData.tel"
      />
    </UFormGroup>
    <UFormGroup
        label="E-Mail:"
    >
      <UInput
          v-model="customerInfo.infoData.email"
      />
    </UFormGroup>
    <UFormGroup
        label="Webseite:"
    >
      <UInput
          v-model="customerInfo.infoData.web"
      />
    </UFormGroup>
    <UFormGroup
        label="USt-Id:"
    >
      <UInput
          v-model="customerInfo.infoData.ustid"
      />
    </UFormGroup>

    <template #footer>
      <UButton
          v-if="mode == 'edit'"
          @click="updateCustomer"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode == 'create'"
          @click="createCustomer"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
      >
        Abbrechen
      </UButton>
    </template>

  </UCard>

  <HistoryDisplay
      type="customer"
      v-if="currentCustomer"
      :element-id="currentCustomer.id"
  />
</template>

<style scoped>
td {
  padding: 0.2em;
}
</style>