<template>
  <Teleport to="body">
  <UModal v-model="isOpen" :ui="{ width: 'sm:max-w-md' }" class="login-modal">
      <UCard>
        <template #header>
          <h3 class="text-lg font-semibold text-gray-900">Admin Login</h3>
        </template>

        <form @submit.prevent="handleSubmit" class="space-y-4">
        <UFormGroup label="Username" name="username">
          <UInput
            v-model="form.username"
            placeholder="Enter username"
            :disabled="loading"
            class="w-full"
            autofocus
          />
        </UFormGroup>

          <UFormGroup label="Password" name="password">
            <UInput
              v-model="form.password"
              type="password"
              placeholder="Enter password"
              :disabled="loading"
              class="w-full"
            />
          </UFormGroup>

          <div v-if="error" class="text-red-600 text-sm p-3 bg-red-50 border border-red-200 rounded-md">
            {{ error }}
          </div>

          <div class="flex justify-end space-x-3 pt-4">
            <UButton
              type="button"
              variant="outline"
              color="gray"
              :disabled="loading"
              @click="close"
            >
              Cancel
            </UButton>
            <UButton
              type="submit"
              variant="solid"
              color="primary"
              :loading="loading"
            >
              Login
            </UButton>
          </div>
        </form>
      </UCard>
    </UModal>
  </Teleport>
</template>

<script setup lang="ts">
interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  username: '',
  password: ''
})

const loading = ref(false)
const error = ref('')

const handleSubmit = async () => {
  if (!form.username || !form.password) {
    error.value = 'Please enter both username and password'
    return
  }

  loading.value = true
  error.value = ''

  try {
    await $fetch('/api/auth/login', {
      method: 'POST',
      body: {
        username: form.username,
        password: form.password
      }
    })

    emit('success')
    close()
  } catch (err: any) {
    error.value = err.data?.statusMessage || 'Login failed'
  } finally {
    loading.value = false
  }
}

const close = () => {
  isOpen.value = false
  form.username = ''
  form.password = ''
  error.value = ''
}
</script>
