<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">
          Create your account
        </p>
      </div>

      <form class="mt-8 space-y-6" @submit.prevent="register">
        <div class="rounded-md shadow-sm space-y-4">
          <!-- VOEN field with lookup -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">
              VOEN (ИНН) <span class="text-red-500">*</span>
            </label>
            <div class="flex gap-2">
              <input
                type="text"
                v-model="form.voen"
                placeholder="0000000000"
                :disabled="loading || voenLoading"
                class="flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
                @keydown.enter.prevent="lookupVoen"
              />
              <Button
                type="button"
                variant="subtle"
                :loading="voenLoading"
                :disabled="!form.voen || loading"
                @click="lookupVoen"
              >
                Lookup
              </Button>
            </div>
            <div v-if="voenInfo" class="mt-2 rounded-md bg-blue-50 p-3">
              <p class="text-sm font-medium text-blue-800">{{ voenInfo.name }}</p>
              <p class="text-xs text-blue-600 mt-0.5">{{ voenInfo.organization_type }}</p>
              <div class="flex gap-3 mt-1">
                <span v-if="voenInfo.active" class="text-xs text-green-600">Active</span>
                <span v-if="voenInfo.vat_payer" class="text-xs text-blue-600">VAT Payer</span>
              </div>
            </div>
            <p v-if="voenError" class="mt-1 text-sm text-red-600">{{ voenError }}</p>
          </div>

          <FormControl
            label="Full Name"
            type="text"
            v-model="form.fullName"
            placeholder="John Doe"
            :disabled="loading"
            required
          />

          <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 (min 6 characters)"
            :disabled="loading"
            required
          />

          <FormControl
            label="Confirm Password"
            type="password"
            v-model="form.confirmPassword"
            placeholder="Confirm 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 v-if="success" class="rounded-md bg-green-50 p-4">
          <p class="text-sm text-green-700">{{ success }}</p>
        </div>

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

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

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

const loading = ref(false)
const error = ref('')
const success = ref('')
const voenLoading = ref(false)
const voenError = ref('')
const voenInfo = ref(null)

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

const voenResource = createResource({
  url: 'cloud_portal.api.voen.lookup',
  onSuccess(data) {
    voenLoading.value = false
    if (data.success) {
      voenInfo.value = data
      voenError.value = ''
      if (!form.fullName) {
        form.fullName = data.name
      }
    } else {
      voenInfo.value = null
      voenError.value = data.message || 'Organization not found'
    }
  },
  onError(err) {
    voenLoading.value = false
    voenInfo.value = null
    voenError.value = err.messages?.[0] || err.message || 'Lookup failed'
  },
})

function lookupVoen() {
  if (!form.voen) return
  voenLoading.value = true
  voenError.value = ''
  voenInfo.value = null
  voenResource.fetch({ voen: form.voen })
}

const registerResource = createResource({
  url: 'cloud_portal.api.auth.register_user',
  onSuccess(data) {
    loading.value = false
    if (data.success) {
      success.value = 'Account created! Redirecting...'
      error.value = ''
      setTimeout(() => {
        window.location.href = '/portal/sites'
      }, 500)
    } else {
      error.value = data.message || 'Registration failed'
    }
  },
  onError(err) {
    loading.value = false
    error.value = err.messages?.[0] || err.message || 'Registration failed'
  },
})

function register() {
  if (!form.voen) {
    error.value = 'Please enter your VOEN (ИНН)'
    return
  }
  if (!form.fullName || !form.email || !form.password) {
    error.value = 'Please fill in all fields'
    return
  }
  if (form.password.length < 6) {
    error.value = 'Password must be at least 6 characters'
    return
  }
  if (form.password !== form.confirmPassword) {
    error.value = 'Passwords do not match'
    return
  }

  error.value = ''
  success.value = ''
  loading.value = true

  registerResource.fetch({
    full_name: form.fullName,
    email: form.email,
    password: form.password,
    voen: form.voen,
  })
}
</script>
