<template>
  <q-page class="bg-surface-dark login-page">
    <Transition mode="out-in" name="fade-slide">
      <div
        v-if="!clicked"
        key="splash"
        class="splash-screen"
        @click="clicked = true"
      >
        <img class="splash-layer splash-layer--bg" :src="BackgroundLogin" />

        <img class="splash-layer splash-layer--photo" :src="FotoDiarista" />

        <img class="splash-layer splash-layer--logo" :src="LogoLogin" />
      </div>

      <div v-else-if="steps === 5" key="step5" class="splash-screen">
        <img class="splash-layer splash-layer--bg" :src="BackgroundLogin" />

        <img class="splash-layer splash-layer--photo" :src="FotoDiarista" />

        <img class="splash-layer splash-layer--logo-small" :src="LogoLogin" />

        <div class="step4-card-wrapper">
          <LoginStep4Panel
            @back="goBack"
            @cep-resolved="onCepResolved"
            @device-location="onDeviceLocation"
          />
        </div>
      </div>

      <div v-else key="flow" class="flow-screen">
        <div class="flow-header items-center row">
          <q-btn
            v-if="steps >= 4"
            class="flow-back-btn"
            color="primary"
            dense
            flat
            icon="mdi-arrow-left"
            round
            @click="goBack"
          />
        </div>

        <div class="flow-logo q-my-xl">
          <q-img style="max-width: 180px" :src="LogoDiariaCampos" />
        </div>

        <div v-if="steps === 3" class="register-later-row">
          <q-btn
            align="right"
            class="register-later-btn"
            color="primary"
            flat
            icon-right="mdi-chevron-right-circle-outline"
            no-caps
            :label="$t('auth.register_later')"
            @click="steps = 5"
          />
        </div>

        <q-form
          ref="loginForm"
          autocapitalize="off"
          autocomplete="off"
          autocorrect="off"
          class="flow-form"
          spellcheck="false"
          @submit="onSubmit"
        >
          <div
            class="flow-content"
            :class="{ 'flow-content--centered': steps < 3 }"
          >
            <LoginStep1Panel
              v-if="steps === 1"
              v-model:email="email"
              v-model:phone="phone"
            />

            <LoginStep2Panel v-else-if="steps === 2" v-model:code="code" />

            <LoginStep3Panel v-else-if="steps === 3" v-model="stepThreeForm" />

            <LoginStepAvatarPanel
              v-else-if="steps === 4"
              v-model="stepAvatarForm"
            />
          </div>

          <div class="flow-footer">
            <q-btn
              class="full-width"
              color="primary-button"
              padding="8px 12px"
              rounded
              type="submit"
              :label="$t('auth.continue')"
              :loading="submitting"
            >
              <template #loading>
                <q-spinner />
              </template>
            </q-btn>
          </div>
        </q-form>
      </div>
    </Transition>
  </q-page>
</template>

<script setup>
import { createUserAndClient, sendCode, validateCode } from "src/api/user";
import { useAuth } from "src/composables/useAuth";
import { useRegistrationFlowStore } from "src/stores/registrationFlow";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

import BackgroundLogin from "src/assets/background-login.svg";
import FotoDiarista from "src/assets/foto_diarista_login.svg";
import LogoDiariaCampos from "src/assets/logo_diaria_campos_login.svg";
import LogoLogin from "src/assets/logo_diaria_login.svg";

import LoginStepAvatarPanel from "src/components/login/LoginStepAvatarPanel.vue";
import LoginStep1Panel from "src/components/login/LoginStep1Panel.vue";
import LoginStep2Panel from "src/components/login/LoginStep2Panel.vue";
import LoginStep3Panel from "src/components/login/LoginStep3Panel.vue";
import LoginStep4Panel from "src/components/login/LoginStep4Panel.vue";

const { setAuthDataFromPayload } = useAuth();
const flowStore = useRegistrationFlowStore();
const router = useRouter();

const clicked = ref(false);
const code = ref("");
const email = ref("");
const isLogin = ref(false);

const loginForm = ref(null);

const phone = ref("");

const stepAvatarForm = ref({
  avatar: null,
});

const steps = ref(1);

const stepThreeForm = ref({
  address: "",
  address_type: "home",
  city: "",
  complement: "",
  district: "",
  document: "",
  instructions: "",
  name: "",
  nickname: "",
  no_complement: false,
  number: "",
  state: "",
  zip_code: "",
});

const submitting = ref(false);

const goBack = () => {
  if (steps.value === 4) {
    steps.value = 3;
  } else if (steps.value === 5) {
    steps.value = 3;
  }
};

const navigateToMap = (lat, lng) => {
  flowStore.setCredentials(email.value, phone.value, code.value);
  flowStore.setInitialLocation(lat, lng);
  router.push({ name: "LocationMapPage" });
};

const onCepResolved = (geoData) => {
  navigateToMap(geoData.lat, geoData.lng);
};

const onDeviceLocation = ({ lat, lng }) => {
  navigateToMap(lat, lng);
};

const onSubmit = async () => {
  submitting.value = true;

  try {
    switch (steps.value) {
      case 1: {
        const response = await sendValidationCode();

        isLogin.value = response.data.payload.isLogin;
        break;
      }

      case 2:
        await validateCodeInput();
        break;

      case 3:
        steps.value = 4;
        break;

      case 4:
        await registerUserAndClient();
        break;

      default:
        break;
    }
  } finally {
    submitting.value = false;
  }
};

const registerUserAndClient = async () => {
  const payload = new FormData();

  const append = (key, value) => {
    if (value === null || value === undefined || value === "") {
      return;
    }

    if (typeof value === "boolean") {
      payload.append(key, value ? "1" : "0");
    } else {
      payload.append(key, value);
    }
  };

  Object.entries(stepThreeForm.value).forEach(([key, value]) => {
    if (key === "no_complement") {
      return;
    }

    if (key === "complement" && stepThreeForm.value.no_complement) {
      return;
    }

    append(key, value);
  });

  append("avatar", stepAvatarForm.value.avatar);
  append("code", code.value);
  append("email", email.value);
  append("has_complement", !stepThreeForm.value.no_complement);
  append("phone", phone.value);

  const response = await createUserAndClient(payload);

  if (response.status === 200) {
    await setAuthDataFromPayload(response.data.payload);
    router.push({ name: "DashboardPage" });
  } else {
    console.error("Failed to create user and client");
  }
};

const sendValidationCode = async () => {
  const response = await sendCode(email.value, phone.value);

  if (response.status === 201) {
    steps.value = 2;
  } else {
    console.error("Failed to send validation code");
  }

  return response;
};

const validateCodeInput = async () => {
  const response = await validateCode(
    email.value,
    phone.value,
    code.value,
    isLogin.value,
  );

  if (response.status === 200) {
    if (isLogin.value === true) {
      await setAuthDataFromPayload(response.data.payload);
      router.push({ name: "DashboardPage" });
    } else {
      steps.value = 3;
    }
  } else {
    console.error("Invalid validation code");
  }
};

onMounted(() => {
  setTimeout(() => {
    clicked.value = true;
  }, 1500);
});
</script>

<style lang="scss" scoped>
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition:
    opacity 0.35s ease,
    transform 0.35s ease;
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(6px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(-6px);
}

.login-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  background: var(--q-surface-dark);
}

.splash-screen {
  position: relative;
  width: 100vw;
  min-height: 100vh;
  overflow: hidden;
  cursor: pointer;

  .splash-layer {
    position: absolute;

    &--bg {
      inset: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    &--photo {
      inset: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      opacity: 0.15;
      mix-blend-mode: multiply;
    }

    &--logo {
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 180px;
      z-index: 1;
    }

    &--logo-small {
      top: 18%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 100px;
      z-index: 1;
    }
  }
}

.step4-card-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -30%);
  z-index: 2;
  width: 90%;
  max-width: 360px;
}

.flow-screen {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 500px;
  min-height: 100vh;
  padding: 16px 20px;
  background: var(--q-surface-dark);
}

.flow-header {
  min-height: 36px;
  display: flex;
  align-items: center;
  padding-left: max(4px, env(safe-area-inset-left));
}

.flow-back-btn {
  margin-left: -4px;
}

.flow-logo {
  display: flex;
  justify-content: center;
  padding: 12px 0 20px;
}

.flow-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.flow-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;

  &--centered {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.flow-footer {
  flex-shrink: 0;
  padding: 8px 0 calc(12px + env(safe-area-inset-bottom));
}

.register-later-row {
  display: flex;
  justify-content: flex-end;
  margin-top: -14px;
  padding-bottom: 18px;
}

.register-later-btn {
  justify-content: flex-end;
}
</style>
