<template>
  <div v-if="isCheckin">
    <div class="spinner" style="margin: 100px auto; width: 80px; height: 80px;">
      <div class="dot1" />
      <div class="dot2" />
    </div>
    <div class="flex justify-center text-2xl">
      {{ t('message.loading') }} ...
    </div>
  </div>
  <div v-else>
    <section v-if="show_content && (invitationData.role || request_id)" class="page-w bg-gray-400 dark:bg-gray-600 min-h-screen flex justify-center flex-wrap ">
		  <figure class="my-auto w-[calc(100%+1rem)]">
        <div class="max-w-sm mx-auto overflow-hidden shadow-xl dark:bg-gray-900 bg-gray-100 rounded-3xl p-2">
          <div class="flex flex-row justify-center">
            <div class="mt-1.4 ml-2">
							<button class="!outline-none text-gray-800 dark:text-gray-200" @click="toggleDark()">
								<div v-if="isDark" i-carbon-sun />
								<div v-else i-carbon-moon />
							</button>
            </div>
            <div class="order-last flex-shrink-0">
              <MenuLocales :label-mode="localesLabelMode" :include-current="includeCurrLocale" />
            </div>
            <div class="p-1 ml-8 flex flex-shrink-0 justify-center flex-grow bg-transparent">
              <span v-if="use_logo" class="text-lg rounded-full">
								<img v-if="isDark"
									class="m-auto mt-5"
									width="250"
									:src="`${assetsPath}/images/genadmin_b.svg`"
								/>
								<img v-else
									class="m-auto mt-5"
									width="250"
									:src="`${assetsPath}/images/genadmin_w.svg`"
								/>
              </span>
              <h2 v-else class="text-center mb-1 text-lg heading ~info">
                {{ t('login.welcome') }}
              </h2>
            </div>
          </div>
          <div v-if="use_logo" class="-mt-2 flex flex-row justify-center flex-none">
            <span class="mb-1 text-lg ">
            </span>
          </div>
          <div class="p-2">
            <p class="text-center mb-3 text-base support ">
              <span class="text-gray-400">{{ t('login.subtitle') }}</span>
            </p>
            <div class="container">
              <h5 class="hidden text-center subheading">
                <span class="text-gray-500">{{ t('login.subHeading') }}</span>
              </h5>
              <div class="hidden messages global mb-5">
                <span class="text-gray-500">{{ t('login.form','') }}</span>
              </div>
              <div id="login-password" class="mt-8">
                <form action="">
									<fieldset v-if="is_register" class="mt-10 relative">
                      <input
                        v-model="user"
                        name="identifier"
                        id="identifier"
                        type="text"
												class="input-fld peer h-10 w-full  border-b border-gray-500 py-2 focus:placeholder- focus:outline-none focus:border-indigo-500"
                        autocomplete="username"
                        @focus="errorMessage = ''"
                      >
                    <label for="identifier"
										class="input-lbl absolute left-0 -top-3.5 transition-all peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-gray-600 peer-focus:text-sm text-xs text-gray-600 dark:text-gray-500 text-xs text-gray-600 dark:text-gray-500"
                      >{{ t('login.username') }}</label>
                    <div class="messages " />
                  </fieldset>
									<fieldset v-if="is_register" class="mt-10 relative">
                      <input
                        v-model="email"
                        name="email"
                        id="email"
                        type="text"
												class="input-fld peer h-10 w-full  border-b border-gray-500 py-2 focus:placeholder- focus:outline-none focus:border-indigo-500"
                        autocomplete="email"
                        @focus="errorMessage = ''"
                      >
                    <label for="identifier"
										class="input-lbl absolute left-0 -top-3.5 transition-all peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-gray-600 peer-focus:text-sm text-xs text-gray-600 dark:text-gray-500"
                      >{{ t('login.email') }}</label>
                    <div class="messages " />
                  </fieldset>
									<fieldset class="mt-10 relative">
                      <input
                        v-model="password"
                        name="password"
                        class="input-fld peer h-10 w-full  border-b border-gray-500 py-2 focus:placeholder- focus:outline-none focus:border-indigo-500"
                        :type="passwordVisible ? 'text' : 'password'"
                        autocomplete="current-password"
                        @focus="errorMessage = ''"
                      >
											
											<label for="password"
										class="input-lbl absolute left-0 -top-3.5 transition-all peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-2 peer-focus:-top-3.5 peer-focus:text-gray-600 peer-focus:text-sm text-xs text-gray-600 dark:text-gray-500"
										>
                      {{ t('login.password') }}
                    </label>
                    <div v-if="connection.state !== ''" class="messages text-red-400 ">
                      {{ t(connection.state) }}
                    </div>
                    <div v-if="errorMessage !== ''" class="messages text-red-400 ">
                      {{ t(errorMessage) }}
                    </div>
                  <svg class="password-visibility-toggle absolute top-4 -right-70 cursor-pointer" @click="togglePasswordVisible">
                    <path v-if="!passwordVisible" class="eye-open" d="M8 2.36365C4.36364 2.36365 1.25818 4.62547 0 7.81819C1.25818 11.0109 4.36364 13.2727 8 13.2727C11.6364 13.2727 14.7418 11.0109 16 7.81819C14.7418 4.62547 11.6364 2.36365 8 2.36365ZM8 11.4546C5.99273 11.4546 4.36364 9.82547 4.36364 7.81819C4.36364 5.81092 5.99273 4.18183 8 4.18183C10.0073 4.18183 11.6364 5.81092 11.6364 7.81819C11.6364 9.82547 10.0073 11.4546 8 11.4546ZM8 5.63637C6.79273 5.63637 5.81818 6.61092 5.81818 7.81819C5.81818 9.02547 6.79273 10 8 10C9.20727 10 10.1818 9.02547 10.1818 7.81819C10.1818 6.61092 9.20727 5.63637 8 5.63637Z" />
                    <path v-else class="eye-closed" fill-rule="evenodd" clip-rule="evenodd" d="M14.8222 1.85355C15.0175 1.65829 15.0175 1.34171 14.8222 1.14645C14.627 0.951184 14.3104 0.951184 14.1151 1.14645L12.005 3.25653C10.8901 2.482 9.56509 1.92505 8.06 1.92505C3 1.92505 0 7.92505 0 7.92505C0 7.92505 1.16157 10.2482 3.25823 12.0033L1.19366 14.0679C0.998396 14.2632 0.998396 14.5798 1.19366 14.775C1.38892 14.9703 1.7055 14.9703 1.90076 14.775L14.8222 1.85355ZM4.85879 10.4028L6.29159 8.96998C6.10643 8.66645 6 8.3089 6 7.92505C6 6.81505 6.89 5.92505 8 5.92505C8.38385 5.92505 8.7414 6.03148 9.04493 6.21664L10.4777 4.78384C9.79783 4.24654 8.93821 3.92505 8 3.92505C5.8 3.92505 4 5.72505 4 7.92505C4 8.86326 4.32149 9.72288 4.85879 10.4028ZM11.8644 6.88906L13.8567 4.8968C15.2406 6.40616 16 7.92505 16 7.92505C16 7.92505 13 13.925 8.06 13.925C7.09599 13.925 6.20675 13.7073 5.39878 13.3547L6.96401 11.7895C7.29473 11.8779 7.64207 11.925 8 11.925C10.22 11.925 12 10.145 12 7.92505C12 7.56712 11.9529 7.21978 11.8644 6.88906ZM9.33847 9.41501L9.48996 9.26352C9.44222 9.31669 9.39164 9.36726 9.33847 9.41501Z" />
                  </svg>
                  </fieldset>
                  <input name="csrf_token" type="hidden" value="">
                  <div class="mt-10 flex justify-center">
                    <button v-if="is_register" type="submit" @click.prevent="onRegister"
										class="text-lg flex-grow flex-shrink-0 bg-indigo-500 hover:bg-indigo-700 border-indigo-500 hover:border-indigo-700 text-sm border-4 text-white py-1 px-2 rounded"
										>
                      {{ t('login.register') }}
                    </button>
										<button v-else type="submit" @click.prevent="onSend"
										class="text-lg flex-grow flex-shrink-0 bg-indigo-500 hover:bg-indigo-700 border-indigo-500 hover:border-indigo-700 text-sm border-4 text-white py-1 px-2 rounded"
										>
                      {{ t('send') }}
                    </button>

                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <section style="display: none" class="section p-4">
        </section>
			</figure>
    </section>
		<div v-else class="text-center m-auto">
			<img v-if="isDark"
				class="m-auto mt-5"
				width="250"
				:src="`${assetsPath}/images/genadmin_b.svg`"
				@click="router.push(goRoute)"
			/>
			<img v-else
				class="m-auto mt-5"
				width="250"
				:src="`${assetsPath}/images/genadmin_w.svg`"
				@click="router.push(goRoute)"
			/>
			<h2 class="mt-8 text-2xl text-gray-700 dark:text-gray-400">{{ t('message.loading', 'Loading') }}...</h2>
			<h4>{{useState().connection.value.state}}</h4>
		</div>
  </div>
</template>
<script setup lang="ts">
import { ref, } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import MenuLocales  from '@/MenuLocales.vue'
import {LocalesLabelModes,InvitationDataType}  from '~/typs'
import { isDark, toggleDark } from '~/composables'
import useState from '~/hooks/useState'
import { onTimeoutAuth } from '~/hooks/utilsAuth'
import { MessageType } from '~/typs'
import { show_message,send_data } from '~/hooks/utils'
import { b64_to_utf8,utf8_to_b64 } from '~/hooks/tools'

const assetsPath = useState().ASSETS_PATH.value
const router = useRouter()
const goRoute = "/"
const use_logo = router.currentRoute.value.meta.use_logo
const t = useI18n().t
const includeCurrLocale = true 
const is_register = computed(() => {
  switch(router.currentRoute.value.name) {
		case 'Register':
			return true
		default:
			return false
	}
})
const show_content = ref(true)
const invitationData = ref({} as InvitationDataType)

const { connection } = useState()
connection.value.state = ''
const localesLabelMode = ref(LocalesLabelModes.auto)
const errorMessage = ref('')
const isCheckin = ref(false)
const user = ref('')
const email = ref('')
const password = ref('')
const passwordVisible = ref(false)
const togglePasswordVisible = () => passwordVisible.value = !passwordVisible.value
const request_id = ref('')
const onSend = async() => {
  if (request_id.value.length === 0 || password.value.length === 0 ) {
    errorMessage.value = 'login.nodata'
    return
  }
  const url = useState().CONFURLS.value.sendrecovery || ''
	if (url.length == 0 ) {
    errorMessage.value = 'login.no_url_found'
    return
	}
  errorMessage.value = ''
  connection.value.state = ''
  const formData = { 
		id: request_id.value, 
		val: utf8_to_b64(password.value),
	}
  const [responseData,_err] = await send_data(url, formData, false, false)
  if (responseData && responseData.status && responseData.status === 'ok') {
		const srcRoute = useState().sourceRoute.value.length > 0 ? useState().sourceRoute.value : '/'
    router.push(srcRoute)
  } else {
    useState().userID.value = ''
    errorMessage.value = 'login.invalidcredentials'
	}
}
const onRegister = async() => {
	if (user.value.length === 0 || password.value.length === 0 || email.value.length === 0 ) {
    errorMessage.value = 'login.nodata'
    return
  }
  let success = false
  const url = useState().CONFURLS.value.newuser || ''
	if (url.length == 0 ) {
    errorMessage.value = 'login.no_url_found'
    return
	}
  errorMessage.value = ''
  connection.value.state = ''
  const formData = { 
		username: user.value, 
		email: email.value, 
		password: utf8_to_b64(password.value),
		role: invitationData.value.role,
		data: invitationData.value.data,
	}
  const [responseData,_err] = await send_data(url, formData, true, false)
  if (responseData && responseData.status && responseData.status === 'ok') {
    // if (responseData.defs)
    //   store.dispatch(AppDefsAction.addDefs, { key: map_key, defs: responseData.defs })
    success = true
    useState().checkin.value = false
    useState().userID.value = user.value
	}
  if (success) {
    localStorage.removeItem(useState().AUTHKEY.value)
		const srcRoute = useState().sourceRoute.value.length > 0 ? useState().sourceRoute.value : '/'
    router.push(srcRoute)
  } else {
    useState().userID.value = ''
    errorMessage.value = 'login.invalidcredentials'
	}
}
const load_invitation_data = async (id: string): Promise<[any,string]> => {
	let url = useState().CONFURLS.value.invitation || ''
	if (url.length == 0)
		return [{},'No URL defined']
	url = `${url}/${id}`
	let res: any = {}
	let error = null
	try {
		const response = await self.fetch(url, {
			method: 'GET',
		})
		if (response.ok) {
			res = await response.json()
			if (res.data) {
				error = null
			} else {
				error = res.message
			} 
		} else {
		   error = response.statusText
		}
	}
	catch (err: any) {
		error = err.message
	}
	if (error) {
		show_message(MessageType.Error, `'Load invitation info' -> ${error}`, 5000)
		useState().connection.value.state = 'connection.error'
		return [{}, error]
	}
	return [res,error]
}
onBeforeMount(async() => {
  const id = router.currentRoute.value.params.id || router.currentRoute.value.query.id || ''
	request_id.value = id as string
	show_content.value = false
	if (is_register.value) {
		const [res,error] = await load_invitation_data(id as string)
		if (error && error.length > 0) {
			return 
		}
		try {
			invitationData.value = JSON.parse(b64_to_utf8(res.data))
		} catch (err: any) {
			console.log(err)
		}
		if (res && res.auth) {
			localStorage.setItem(useState().AUTHKEY.value,res.auth)
			onTimeoutAuth()
		}
		if (invitationData.value.email) {
			email.value = invitationData.value.email
			show_content.value = true
		}
	} else if (request_id.value.length > 0) {
			show_content.value = true
	}
})
</script>
