<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
          Cloud Portal
        </h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          Sign in to your account
        </p>
      </div>

      <form class="mt-8 space-y-6" @submit.prevent="login">
        <div class="rounded-md shadow-sm space-y-4">
          <FormControl
            label="Email"
            type="email"
            v-model="form.email"
            placeholder="you@example.com"
            :disabled="loading"
            required
          />

          <FormControl
            label="Password"
            type="password"
            v-model="form.password"
            placeholder="Password"
            :disabled="loading"
            required
          />
        </div>

        <div v-if="error" class="rounded-md bg-red-50 p-4">
          <p class="text-sm text-red-700">{{ error }}</p>
        </div>

        <div>
          <Button
            type="submit"
            variant="solid"
            class="w-full"
            :loading="loading"
          >
            Sign in
          </Button>
        </div>

        <div class="text-center">
          <router-link
            :to="{ name: 'Register' }"
            class="text-sm text-blue-600 hover:text-blue-500"
          >
            Don't have an account? Sign up
          </router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Button, FormControl, createResource } from 'frappe-ui'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const error = ref('')

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

const loginResource = createResource({
  url: 'login',
  makeParams() {
    return {
      usr: form.email,
      pwd: form.password,
    }
  },
  onSuccess() {
    loading.value = false
    error.value = ''
    const redirectPath = route.query.redirect || '/sites'
    window.location.href = '/portal' + redirectPath
  },
  onError(err) {
    loading.value = false
    error.value = err.messages?.[0] || err.message || 'Invalid email or password'
  }
})

function login() {
  if (!form.email || !form.password) {
    error.value = 'Please enter email and password'
    return
  }

  error.value = ''
  loading.value = true
  loginResource.submit()
}
</script>
