<template>
  <UModal
    v-model:open="isOpen"
    :title="title"
    :description="description"
    :dismissible="dismissible"
    :ui="{
      content: 'bg-ghost-900 border border-ghost-700',
      header: 'bg-ghost-900 border-b border-ghost-700',
      body: 'bg-ghost-900',
      footer: 'bg-ghost-900 border-t border-ghost-700',
      title: 'text-ghost-100',
      description: 'text-ghost-400',
    }"
  >
    <template #body>
      <div class="space-y-6">
        <!-- Success State -->
        <div v-if="loginSuccess" class="text-center py-4">
          <div class="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
            <Icon name="heroicons:check-circle" class="w-10 h-10 text-green-400" />
          </div>
          <h3 class="text-lg font-semibold text-ghost-100 mb-2">Check your email</h3>
          <p class="text-ghost-300">
            We've sent a magic link to <strong class="text-ghost-100">{{ loginForm.email }}</strong>.
            Click the link to sign in.
          </p>
        </div>

        <!-- Login Form -->
        <UForm v-else :state="loginForm" @submit="handleLogin">
          <UFormField label="Email Address" name="email" required class="mb-4">
            <UInput
              v-model="loginForm.email"
              type="email"
              size="lg"
              class="w-full"
              placeholder="your.email@example.com"
              :ui="{
                root: 'bg-ghost-800 border-ghost-600 text-ghost-100 placeholder-ghost-500',
              }"
            />
          </UFormField>

          <!-- Info Box -->
          <div class="bg-ghost-800 border border-ghost-600 p-4 rounded-lg mb-6">
            <div class="flex items-start gap-3">
              <Icon name="heroicons:envelope" class="w-5 h-5 text-whisper-400 flex-shrink-0 mt-0.5" />
              <p class="text-sm text-ghost-300">
                We'll send you a secure magic link. No password needed!
              </p>
            </div>
          </div>

          <!-- Error Message -->
          <div
            v-if="loginError"
            class="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg"
          >
            <p class="text-red-400 text-sm">{{ loginError }}</p>
          </div>

          <!-- Submit Button -->
          <UButton
            type="submit"
            :loading="isLoggingIn"
            :disabled="!isLoginFormValid"
            size="lg"
            class="w-full"
          >
            Send Magic Link
          </UButton>
        </UForm>

        <!-- Join Link -->
        <div v-if="!loginSuccess" class="text-center pt-2 border-t border-ghost-700">
          <p class="text-ghost-400 text-sm pt-4">
            Don't have an account?
            <NuxtLink
              to="/join"
              class="text-whisper-400 hover:text-whisper-300 font-medium"
              @click="close"
            >
              Join Ghost Guild
            </NuxtLink>
          </p>
        </div>
      </div>
    </template>

    <template #footer>
      <div class="flex justify-end">
        <UButton
          v-if="loginSuccess"
          variant="ghost"
          color="neutral"
          @click="resetAndClose"
        >
          Close
        </UButton>
      </div>
    </template>
  </UModal>
</template>

<script setup>
const props = defineProps({
  title: {
    type: String,
    default: 'Sign in to continue',
  },
  description: {
    type: String,
    default: 'Enter your email to receive a secure login link',
  },
  dismissible: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['success', 'close'])

const { showLoginModal, hideLoginModal } = useLoginModal()
const { checkMemberStatus } = useAuth()

const isOpen = computed({
  get: () => showLoginModal.value,
  set: (value) => {
    if (!value) {
      hideLoginModal()
      emit('close')
    }
  },
})

const loginForm = reactive({
  email: '',
})

const isLoggingIn = ref(false)
const loginSuccess = ref(false)
const loginError = ref('')

const isLoginFormValid = computed(() => {
  return loginForm.email && loginForm.email.includes('@')
})

const handleLogin = async () => {
  if (isLoggingIn.value) return

  isLoggingIn.value = true
  loginError.value = ''

  try {
    const response = await $fetch('/api/auth/login', {
      method: 'POST',
      body: {
        email: loginForm.email,
      },
    })

    if (response.success) {
      loginSuccess.value = true
      emit('success', { email: loginForm.email })
    }
  } catch (err) {
    console.error('Login error:', err)

    if (err.statusCode === 404) {
      loginError.value = 'No account found with that email. Please check your email or join Ghost Guild.'
    } else if (err.statusCode === 500) {
      loginError.value = 'Failed to send login email. Please try again later.'
    } else {
      loginError.value = err.statusMessage || 'Something went wrong. Please try again.'
    }
  } finally {
    isLoggingIn.value = false
  }
}

const close = () => {
  isOpen.value = false
}

const resetAndClose = () => {
  loginForm.email = ''
  loginSuccess.value = false
  loginError.value = ''
  close()
}

// Reset form when modal opens
watch(isOpen, (newValue) => {
  if (newValue) {
    loginForm.email = ''
    loginSuccess.value = false
    loginError.value = ''
  }
})
</script>
