<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '@/api'

const router = useRouter()

// Form state
const step = ref(1)
const loading = ref(false)
const error = ref('')
const slugChecking = ref(false)
const slugAvailable = ref<boolean | null>(null)

// Org data
const orgName = ref('')
const orgSlug = ref('')

// Admin data
const adminEmail = ref('')
const adminPassword = ref('')
const adminPasswordConfirm = ref('')
const adminFirstName = ref('')
const adminLastName = ref('')
const adminPhone = ref('')

// Auto-generate slug from name
watch(orgName, (name) => {
  if (name && !orgSlug.value) {
    orgSlug.value = name
      .toLowerCase()
      .replace(/[äöüß]/g, c => ({ ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }[c] || c))
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '')
      .slice(0, 30)
  }
})

// Check slug availability
let slugTimeout: number
watch(orgSlug, async (slug) => {
  clearTimeout(slugTimeout)
  slugAvailable.value = null
  
  if (slug.length < 3) return
  
  slugChecking.value = true
  slugTimeout = setTimeout(async () => {
    try {
      const res = await fetch(`${import.meta.env.VITE_API_URL || '/api'}/organizations/check/${slug}`)
      const data = await res.json()
      slugAvailable.value = data.available
    } catch {
      slugAvailable.value = null
    }
    slugChecking.value = false
  }, 500)
})

const canProceedStep1 = computed(() => 
  orgName.value.length >= 2 && 
  orgSlug.value.length >= 3 && 
  slugAvailable.value === true
)

const canProceedStep2 = computed(() =>
  adminEmail.value.includes('@') &&
  adminPassword.value.length >= 8 &&
  adminPassword.value === adminPasswordConfirm.value &&
  adminFirstName.value.length >= 2 &&
  adminLastName.value.length >= 2
)

async function submit() {
  if (!canProceedStep2.value) return
  
  error.value = ''
  loading.value = true
  
  try {
    await api.post('/organizations/register', {
      name: orgName.value,
      slug: orgSlug.value,
      admin_email: adminEmail.value,
      admin_password: adminPassword.value,
      admin_first_name: adminFirstName.value,
      admin_last_name: adminLastName.value,
      admin_phone: adminPhone.value || undefined
    })
    
    // Redirect to login with success message
    router.push({ 
      name: 'login', 
      query: { 
        registered: 'true',
        org: orgSlug.value,
        email: adminEmail.value
      }
    })
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Registrierung fehlgeschlagen'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 py-12 px-4">
    <div class="max-w-lg w-full">
      <!-- Logo -->
      <div class="text-center mb-8">
        <h1 class="text-4xl font-bold text-primary-600">🔐 SeCu</h1>
        <p class="mt-2 text-gray-600 dark:text-gray-400">Organisation registrieren</p>
      </div>

      <!-- Progress -->
      <div class="flex items-center justify-center mb-8">
        <div class="flex items-center">
          <div :class="['w-10 h-10 rounded-full flex items-center justify-center text-white font-bold',
                        step >= 1 ? 'bg-primary-600' : 'bg-gray-300']">1</div>
          <div :class="['w-24 h-1 mx-2', step >= 2 ? 'bg-primary-600' : 'bg-gray-300']"></div>
          <div :class="['w-10 h-10 rounded-full flex items-center justify-center font-bold',
                        step >= 2 ? 'bg-primary-600 text-white' : 'bg-gray-300 text-gray-600']">2</div>
        </div>
      </div>

      <div class="card">
        <!-- Step 1: Organization -->
        <div v-if="step === 1">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-6">
            Ihre Organisation
          </h2>
          
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Firmenname *
              </label>
              <input
                v-model="orgName"
                type="text"
                class="input"
                placeholder="z.B. Muster Sicherheit GmbH"
              />
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                URL-Kürzel *
              </label>
              <div class="flex items-center gap-2">
                <input
                  v-model="orgSlug"
                  type="text"
                  class="input"
                  placeholder="muster-sicherheit"
                />
                <span v-if="slugChecking" class="text-gray-400">⏳</span>
                <span v-else-if="slugAvailable === true" class="text-green-500">✓</span>
                <span v-else-if="slugAvailable === false" class="text-red-500">✗</span>
              </div>
              <p class="mt-1 text-xs text-gray-500">
                Wird für den Login verwendet. Nur Kleinbuchstaben und Bindestriche.
              </p>
              <p v-if="slugAvailable === false" class="mt-1 text-xs text-red-500">
                Dieses Kürzel ist bereits vergeben.
              </p>
            </div>
          </div>
          
          <div class="mt-6 flex justify-between">
            <router-link to="/login" class="btn btn-secondary">
              ← Zurück zum Login
            </router-link>
            <button 
              @click="step = 2" 
              :disabled="!canProceedStep1"
              class="btn btn-primary"
            >
              Weiter →
            </button>
          </div>
        </div>

        <!-- Step 2: Admin Account -->
        <div v-if="step === 2">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-6">
            Administrator-Konto
          </h2>
          
          <form @submit.prevent="submit" class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Vorname *
                </label>
                <input v-model="adminFirstName" type="text" class="input" />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Nachname *
                </label>
                <input v-model="adminLastName" type="text" class="input" />
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                E-Mail *
              </label>
              <input v-model="adminEmail" type="email" class="input" />
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Telefon
              </label>
              <input v-model="adminPhone" type="tel" class="input" placeholder="Optional" />
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Passwort *
              </label>
              <input v-model="adminPassword" type="password" class="input" placeholder="Mindestens 8 Zeichen" />
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Passwort bestätigen *
              </label>
              <input v-model="adminPasswordConfirm" type="password" class="input" />
              <p v-if="adminPassword && adminPasswordConfirm && adminPassword !== adminPasswordConfirm" 
                 class="mt-1 text-xs text-red-500">
                Passwörter stimmen nicht überein
              </p>
            </div>
            
            <div v-if="error" class="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
              {{ error }}
            </div>
            
            <div class="mt-6 flex justify-between">
              <button type="button" @click="step = 1" class="btn btn-secondary">
                ← Zurück
              </button>
              <button 
                type="submit" 
                :disabled="!canProceedStep2 || loading"
                class="btn btn-primary"
              >
                {{ loading ? 'Wird erstellt...' : 'Organisation erstellen' }}
              </button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- Info -->
      <div class="mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
        <p>Nach der Registrierung können Sie sofort loslegen.</p>
        <p class="mt-1">Kostenlos starten • Keine Kreditkarte nötig</p>
      </div>
    </div>
  </div>
</template>
