<script setup lang="ts">
import WizardPage from "@/components/onboarding/WizardPage.vue";
import type { Ref } from "vue";
import { computed, ref, watch } from "vue";
import { useUserStore } from "@/stores/user";
import PersonalAddress from "@/components/onboarding/PersonalAddress.vue";
import OrganisationAddress from "@/components/onboarding/OrganisationAddress.vue";
import { itPost, itPut, useFetch } from "@/fetchHelpers";
import { useEntities } from "@/services/onboarding";

type BillingAddressType = {
  first_name: string;
  last_name: string;
  street: string;
  street_number: string;
  postal_code: string;
  city: string;
  country: string;
  company_street: string;
  company_street_number: string;
  company_postal_code: string;
  company_city: string;
  company_country: string;
};

const user = useUserStore();
const { organisations } = useEntities();

const userOrganisationName = computed(
  () => organisations.value?.find((c) => c.id === user.organisation)?.name
);

const address = ref({
  firstName: user.first_name,
  lastName: user.last_name,
  street: "",
  streetNumber: "",
  postalCode: "",
  city: "",
  country: "",
});

const useCompanyAddress = ref(false);

const orgAddress = ref({
  name: "",
  street: "",
  streetNumber: "",
  postalCode: "",
  city: "",
  country: "",
});

const fetchBillingAddress = useFetch("/api/shop/billing-address/");
const billingAddressData: Ref<BillingAddressType | null> = fetchBillingAddress.data;

watch(billingAddressData, (newVal) => {
  if (newVal) {
    address.value = {
      firstName: newVal.first_name || "",
      lastName: newVal.last_name || "",
      street: newVal.street || "",
      streetNumber: newVal.street_number || "",
      postalCode: newVal.postal_code || "",
      city: newVal.city || "",
      country: newVal.country || "",
    };
    orgAddress.value = {
      name: userOrganisationName.value || "",
      street: newVal.company_street || "",
      streetNumber: newVal.company_street_number || "",
      postalCode: newVal.company_postal_code || "",
      city: newVal.company_city || "",
      country: newVal.company_country || "",
    };
  }
});

const executePayment = () => {
  // FIXME do this as user types, not on submit -> the is the whole point of this ;)
  // FIXME same address and orgaddress too
  itPut("/api/shop/billing-address/update/", {
    first_name: address.value.firstName,
    last_name: address.value.lastName,
    street: address.value.street,
    street_number: address.value.streetNumber,
    postal_code: address.value.postalCode,
    city: address.value.city,
    country: address.value.country,
    company_street: orgAddress.value.street,
    company_street_number: orgAddress.value.streetNumber,
    company_postal_code: orgAddress.value.postalCode,
    company_city: orgAddress.value.city,
    company_country: orgAddress.value.country,
  });

  // Where the payment page will redirect to after the payment is done:
  // The reason why this is here is convenience: We could also do this in the backend
  // then we'd need to configure this for all environments (including Caprover).
  // /server/transactions/redirect?... will just redirect to the frontend to the right page
  // anyway, so it seems fine to do it here.
  const fullHost = `${window.location.protocol}//${window.location.host}`;

  itPost("/api/shop/vv/checkout/", {
    redirect_url: fullHost,
    organisation_address: orgAddress.value,
    address: address.value,
  }).then((res) => {
    console.log("Going to next page", res.next_step_url);
    window.location.href = res.next_step_url;
  });
};
</script>

<template>
  <WizardPage :step="2">
    <template #content>
      <h2 class="my-10">Lehrgang kaufen</h2>
      <p class="mb-4">
        Der Preis für diesen Lehrgang beträgt
        <b>300 CHF.</b>
        Mit dem Kauf erhältst du Zugang auf den gesamten Kurs (inkl. Prüfung).
      </p>
      <p>Hier kannst du ausschliesslich mit einer Kreditkarte bezahlen.</p>

      <h3 class="mb-4 mt-10">Adresse</h3>
      <p>
        Um die Zahlung vornehmen zu können, benötigen wir deine Privatadresse. Optional
        kannst du die Rechnungsadresse deiner Gesellschaft hinzufügen.
      </p>

      <PersonalAddress v-model="address" />

      <button
        v-if="!useCompanyAddress"
        class="underline"
        @click="useCompanyAddress = true"
      >
        {{ `Rechnungsadresse von ${userOrganisationName} hinzufügen` }}
      </button>

      <transition
        enter-active-class="transition ease-out duration-100"
        enter-from-class="transform opacity-0 scale-y-95"
        enter-to-class="transform opacity-100 scale-y-100"
        leave-active-class="transition ease-in duration-75"
        leave-from-class="transform opacity-100 scale-y-100"
        leave-to-class="transform opacity-0 scale-y-95"
      >
        <div v-if="useCompanyAddress">
          <div class="flex items-center justify-between">
            <h3>{{ `Rechnungsaddresse von ${userOrganisationName}` }}</h3>
            <button class="underline" @click="useCompanyAddress = false">
              Entfernen
            </button>
          </div>
          <OrganisationAddress v-model="orgAddress" />
        </div>
      </transition>
    </template>

    <template #footer>
      <router-link
        :to="{ name: 'accountProfile' }"
        class="btn-secondary flex items-center"
      >
        <it-icon-arrow-left class="it-icon mr-2 h-6 w-6" />
        Zurück
      </router-link>
      <button class="btn-blue flex items-center" @click="executePayment">
        Mit Kreditkarte bezahlen
        <it-icon-arrow-right class="it-icon ml-2 h-6 w-6" />
      </button>
    </template>
  </WizardPage>
</template>
