<script setup lang="ts">
import type { SaasConfig } from '../../modules/saasConfig'

const { signInEmail } = useAuth()
const runtimeConfig = useRuntimeConfig()
const toast = useToast()
const { t } = useI18n()
const localePath = useLocalePath()

const { socialProviders } = useSocialProviders()
const saasConfig = computed<SaasConfig>(() => runtimeConfig.public.saas || {})

// Detect if we're on a mobile device (Capacitor or small screen)
const apiBaseUrl = useApiBaseUrl()
const isCapacitor = computed(() => apiBaseUrl !== null && apiBaseUrl !== undefined && apiBaseUrl !== '')
const isMobile = computed(() => {
  // Check if Capacitor app
  if (isCapacitor.value) return true

  // Check screen size for web
  if (typeof window !== 'undefined') {
    return window.innerWidth < 768
  }

  return false
})

const loading = ref(false)
const disableForm = ref(false)
const state = reactive({
  email: '',
  password: ''
})

// Computed property to check if form is valid
const isFormValid = computed(() => {
  return state.email.trim().length > 0 && state.password.trim().length > 0
})

// Handle browser autofill detection
onMounted(() => {
  // Check for autofilled values after a short delay
  setTimeout(() => {
    const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement
    const passwordInput = document.querySelector('input[type="password"]') as HTMLInputElement

    if (emailInput?.value && !state.email) {
      state.email = emailInput.value
    }
    if (passwordInput?.value && !state.password) {
      state.password = passwordInput.value
    }
  }, 100)
})

async function handleSignIn() {
  if (loading.value || !isFormValid.value) return
  loading.value = true
  const { error } = await signInEmail({
    email: state.email.trim(),
    password: state.password
  })
  if (error) {
    toast.add({
      title: error.message,
      color: 'error'
    })
    disableForm.value = false
  } else {
    toast.add({
      title: t('auth.toastSignedIn')
    })

    // Fetch session to ensure auth state is updated before navigation
    // The fetchSession function handles concurrent calls (e.g., from middleware)
    // by awaiting the same promise, preventing race conditions
    const { fetchSession } = useAuth()
    await fetchSession()

    // Navigate to dashboard - middleware will also call fetchSession but will
    // reuse the same promise if still in progress
    await navigateTo(localePath('/dashboard'))
  }
  loading.value = false
}

// Note: We don't need a watch here because we're already handling
// the redirect in handleSignIn() with navigateTo()
// A watch would cause double redirects and race conditions

function signInPending() {
  disableForm.value = true
}
</script>

<template>
  <NuxtLayout>
    <UContainer>
      <UPageBody>
        <AuthCard
          :title="t('auth.login.title')"
          :disabled="disableForm"
        >
          <!-- Magic Link button - more prominent on mobile -->
          <UButton
            v-if="saasConfig.enableMagicLink"
            :to="localePath('/auth/magic-link')"
            :color="isMobile ? 'primary' : 'neutral'"
            :variant="isMobile ? 'solid' : 'outline'"
            block
            :icon="useSolarIcon('link')"
            class="mb-3"
          >
            {{ t('auth.magicLink.signInWithMagicLink') }}
          </UButton>

          <USeparator
            v-if="saasConfig.enableMagicLink"
            :label="t('auth.or')"
            class="my-6"
          />

          <!-- OAuth providers - shown but less prominent on mobile -->
          <AuthSocialProviders
            v-if="!isMobile || socialProviders.length > 0"
            :available-providers="socialProviders"
            @sign-in="signInPending"
          />

          <USeparator
            v-if="socialProviders.length > 0"
            :label="t('auth.or')"
            class="my-6"
          />

          <div class="mb-6">
            <UForm
              :state="state"
              class="flex flex-col gap-4 text-left"
              @submit.prevent="handleSignIn"
            >
              <UFormField
                :label="t('auth.email')"
                required
              >
                <UInput
                  v-model="state.email"
                  type="email"
                  :placeholder="t('auth.email')"
                  class="w-full"
                  :icon="useSolarIcon('letter')"
                  autocomplete="email"
                />
              </UFormField>
              <UFormField
                :label="t('auth.password')"
                required
              >
                <UInput
                  v-model="state.password"
                  type="password"
                  :placeholder="t('auth.password')"
                  class="w-full"
                  :icon="useSolarIcon('lock')"
                  autocomplete="current-password"
                />
              </UFormField>

              <div class="flex justify-end">
                <ULink
                  :to="localePath('/auth/forgot-password')"
                  class="text-primary hover:underline"
                >
                  {{ t('auth.login.forgotPassword') }}
                </ULink>
              </div>

              <UButton
                type="submit"
                color="primary"
                :loading="loading"
                :disabled="!isFormValid"
                block
                :class="{ 'z-40 relative': disableForm && loading }"
                @click="signInPending"
              >
                {{ t('auth.signIn') }}
              </UButton>
            </UForm>

            <div class="text-center mt-6">
              {{ t('auth.login.noAccount') }}
              <ULink
                :to="localePath('/auth/register')"
                class="text-primary hover:underline ml-1"
              >
                {{ t('auth.signUp') }}
              </ULink>
            </div>
          </div>
        </AuthCard>
      </UPageBody>
    </UContainer>
  </NuxtLayout>
</template>
