<template>
  <div class="min-h-screen bg-[#04151F] flex flex-col items-center justify-center px-4 py-8">
    <!-- Header Logo / Brand -->
    <div class="mb-8 text-center">
      <h1 class="text-3xl font-bold text-white tracking-tight">
        Service<span class="text-[#00E5A0]">Finder</span>
      </h1>
      <p class="text-white/40 text-sm mt-1">Fiók aktiválás — KYC kitöltése</p>
    </div>

    <!-- Progress Bar -->
    <div class="w-full max-w-lg mb-8">
      <div class="flex items-center justify-between">
        <div
          v-for="(step, idx) in steps"
          :key="idx"
          class="flex items-center flex-1"
        >
          <!-- Step circle + label -->
          <div class="flex flex-col items-center">
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-300"
              :class="stepCircleClass(idx)"
            >
              <span v-if="currentStep > idx + 1">✓</span>
              <span v-else>{{ idx + 1 }}</span>
            </div>
            <span
              class="text-xs mt-1.5 transition-colors duration-300"
              :class="currentStep >= idx + 1 ? 'text-[#00E5A0]' : 'text-white/30'"
            >
              {{ step.label }}
            </span>
          </div>
          <!-- Connector line -->
          <div
            v-if="idx < steps.length - 1"
            class="flex-1 h-0.5 mx-3 rounded transition-colors duration-300"
            :class="currentStep > idx + 1 ? 'bg-[#00E5A0]' : 'bg-white/10'"
          />
        </div>
      </div>
    </div>

    <!-- Glassmorphism Card -->
    <div class="w-full max-w-lg">
      <div
        class="backdrop-blur-xl bg-white/5 border border-white/10 rounded-2xl shadow-2xl p-8 md:p-10 transition-all duration-500"
      >
        <!-- ==================== STEP 1: Personal ==================== -->
        <div v-if="currentStep === 1">
          <h2 class="text-xl font-semibold text-white mb-1">Személyes adatok</h2>
          <p class="text-[#00E5A0]/70 text-sm mb-6">
            Vezeték- és keresztnév megadása
          </p>

          <div class="space-y-4">
            <!-- Last name -->
            <div>
              <label class="block text-sm text-white/60 mb-1">Vezetéknév</label>
              <input
                v-model="kycForm.last_name"
                type="text"
                placeholder="pl. Kovács"
                class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
              />
            </div>

            <!-- First name -->
            <div>
              <label class="block text-sm text-white/60 mb-1">Keresztnév</label>
              <input
                v-model="kycForm.first_name"
                type="text"
                placeholder="pl. István"
                class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
              />
            </div>
          </div>
        </div>

        <!-- ==================== STEP 2: Address (Soft KYC) ==================== -->
        <div v-if="currentStep === 2">
          <h2 class="text-xl font-semibold text-white mb-1">Lakcím adatok</h2>
          <p class="text-white/40 text-sm mb-6">Csak az irányítószám és város kötelező <span class="text-[#D4AF37]">(Soft KYC)</span></p>

          <div class="space-y-4">
            <!-- Country selector (EU-ready) -->
            <div>
              <label class="block text-sm text-white/60 mb-1">Ország</label>
              <select
                v-model="kycForm.region_code"
                class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
              >
                <option value="HU" class="bg-[#04151F]">🇭🇺 Magyarország</option>
                <option value="AT" class="bg-[#04151F]">🇦🇹 Ausztria</option>
                <option value="SK" class="bg-[#04151F]">🇸🇰 Szlovákia</option>
                <option value="DE" class="bg-[#04151F]">🇩🇪 Németország</option>
                <option value="RO" class="bg-[#04151F]">🇷🇴 Románia</option>
              </select>
            </div>

            <div class="grid grid-cols-3 gap-3">
              <div class="col-span-1">
                <label class="block text-sm text-white/60 mb-1">Irányítószám</label>
                <input
                  v-model="kycForm.address_zip"
                  type="text"
                  placeholder="1234"
                  class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                />
              </div>
              <div class="col-span-2">
                <label class="block text-sm text-white/60 mb-1">Város</label>
                <div class="relative">
                  <input
                    v-model="kycForm.address_city"
                    type="text"
                    placeholder="Budapest"
                    class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition pr-10"
                    :class="{ 'opacity-60': isCityLoading }"
                  />
                  <!-- Loading spinner -->
                  <div
                    v-if="isCityLoading"
                    class="absolute right-3 top-1/2 -translate-y-1/2"
                  >
                    <svg
                      class="animate-spin h-5 w-5 text-[#00E5A0]"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                    </svg>
                  </div>
                </div>
              </div>
            </div>

            <div class="grid grid-cols-3 gap-3">
              <div class="col-span-2">
                <label class="block text-sm text-white/60 mb-1">Utca neve <span class="text-white/20">(opcionális)</span></label>
                <input
                  v-model="kycForm.address_street_name"
                  type="text"
                  placeholder="Kossuth Lajos"
                  class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                />
              </div>
              <div>
                <label class="block text-sm text-white/60 mb-1">Típus <span class="text-white/20">(opcionális)</span></label>
                <select
                  v-model="kycForm.address_street_type"
                  class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                >
                  <option value="" disabled class="bg-[#04151F]">Típus</option>
                  <option value="utca" class="bg-[#04151F]">utca</option>
                  <option value="út" class="bg-[#04151F]">út</option>
                  <option value="tér" class="bg-[#04151F]">tér</option>
                  <option value="körút" class="bg-[#04151F]">körút</option>
                  <option value="sugárút" class="bg-[#04151F]">sugárút</option>
                  <option value="köz" class="bg-[#04151F]">köz</option>
                  <option value="sor" class="bg-[#04151F]">sor</option>
                  <option value="liget" class="bg-[#04151F]">liget</option>
                  <option value="park" class="bg-[#04151F]">park</option>
                  <option value="dűlő" class="bg-[#04151F]">dűlő</option>
                </select>
              </div>
            </div>

            <div>
              <label class="block text-sm text-white/60 mb-1">Házszám <span class="text-white/20">(opcionális)</span></label>
              <input
                v-model="kycForm.address_house_number"
                type="text"
                placeholder="10/A"
                class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                @keydown.tab.exact="handleHouseNumberTab"
              />
            </div>
          </div>
        </div>

        <!-- ==================== STEP 3: Security ==================== -->
        <div v-if="currentStep === 3">
          <h2 class="text-xl font-semibold text-white mb-1">Okmányok</h2>
          <p class="text-white/40 text-sm mb-6">Személyi igazolvány és jogosítvány adatok <span class="text-[#D4AF37]">(opcionális)</span></p>

          <div class="space-y-6">
            <!-- Identity Documents -->
            <div>
              <!-- ID Card -->
              <div class="bg-white/5 rounded-lg p-4 mb-3 border border-white/5">
                <div class="flex items-center gap-2 mb-3">
                  <div class="w-2 h-2 rounded-full bg-white/20" />
                  <span class="text-sm text-white/50">Személyi igazolvány <span class="text-white/20">(opcionális)</span></span>
                </div>
                <div class="grid grid-cols-2 gap-3">
                  <div>
                    <label class="block text-xs text-white/40 mb-1">Okmány száma</label>
                    <input
                      v-model="kycForm.identity_docs.ID_CARD.number"
                      type="text"
                      placeholder="123456AB"
                      class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                    />
                  </div>
                  <div>
                    <label class="block text-xs text-white/40 mb-1">Lejárat</label>
                    <input
                      v-model="kycForm.identity_docs.ID_CARD.expiry_date"
                      type="date"
                      class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white [color-scheme:dark] focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                    />
                  </div>
                </div>
              </div>

              <!-- Driver's License (optional) -->
              <div class="bg-white/5 rounded-lg p-4 border border-white/5">
                <div class="flex items-center gap-2 mb-3">
                  <div class="w-2 h-2 rounded-full bg-white/20" />
                  <span class="text-sm text-white/50">Jogosítvány <span class="text-white/20">(opcionális)</span></span>
                </div>
                <div class="grid grid-cols-2 gap-3">
                  <div>
                    <label class="block text-xs text-white/40 mb-1">Okmány száma</label>
                    <input
                      v-model="kycForm.identity_docs.LICENSE.number"
                      type="text"
                      placeholder="HU-1234567"
                      class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/30 focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                    />
                  </div>
                  <div>
                    <label class="block text-xs text-white/40 mb-1">Lejárat</label>
                    <input
                      v-model="kycForm.identity_docs.LICENSE.expiry_date"
                      type="date"
                      class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white [color-scheme:dark] focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- Language & Currency Preferences -->
            <div class="grid grid-cols-2 gap-3 pt-2">
              <div>
                <label class="block text-sm text-white/60 mb-1">Nyelv</label>
                <select
                  v-model="kycForm.preferred_language"
                  class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                >
                  <option value="hu" class="bg-[#04151F]">Magyar</option>
                  <option value="en" class="bg-[#04151F]">English</option>
                </select>
              </div>
              <div>
                <label class="block text-sm text-white/60 mb-1">Pénznem</label>
                <select
                  v-model="kycForm.preferred_currency"
                  class="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-[#00E5A0] focus:ring-1 focus:ring-[#00E5A0]/30 transition"
                >
                  <option value="HUF" class="bg-[#04151F]">HUF (Ft)</option>
                  <option value="EUR" class="bg-[#04151F]">EUR (€)</option>
                  <option value="USD" class="bg-[#04151F]">USD ($)</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <!-- ==================== Navigation Buttons ==================== -->
        <div class="flex items-center justify-between mt-8 pt-6 border-t border-white/5">
          <!-- Back button -->
          <button
            v-if="currentStep > 1"
            @click="prevStep"
            class="px-5 py-2.5 rounded-lg text-white/60 hover:text-white border border-white/10 hover:border-white/30 transition-all text-sm"
          >
            ← Vissza
          </button>
          <div v-else />

          <!-- Next / Submit -->
          <button
            v-if="currentStep < 3"
            @click="nextStep"
            ref="nextButton"
            class="px-6 py-2.5 rounded-lg bg-[#00E5A0] text-[#04151F] font-semibold hover:bg-[#00E5A0]/90 hover:shadow-lg hover:shadow-[#00E5A0]/20 transition-all text-sm"
          >
            Tovább →
          </button>

          <button
            v-else
            @click="handleSubmit"
            :disabled="isSubmitting"
            class="px-6 py-2.5 rounded-lg font-semibold transition-all text-sm flex items-center gap-2"
            :class="isSubmitting
              ? 'bg-[#00E5A0]/50 text-[#04151F]/70 cursor-not-allowed'
              : 'bg-[#00E5A0] text-[#04151F] hover:bg-[#00E5A0]/90 hover:shadow-lg hover:shadow-[#00E5A0]/20'"
          >
            <!-- Spinner -->
            <svg
              v-if="isSubmitting"
              class="animate-spin h-4 w-4 text-[#04151F]"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
            <span>{{ isSubmitting ? 'Feldolgozás...' : 'Garázs Hitelesítése és Belépés' }}</span>
          </button>
        </div>

        <!-- Error message -->
        <div
          v-if="errorMessage"
          class="mt-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-sm"
        >
          {{ errorMessage }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// ── Steps definition ──
const steps = [
  { label: 'Személyes', key: 'personal' },
  { label: 'Lakcím', key: 'address' },
  { label: 'Okmányok', key: 'security' },
]

const currentStep = ref(1)
const isSubmitting = ref(false)
const errorMessage = ref<string | null>(null)
const isCityLoading = ref(false)
const nextButton = ref<HTMLButtonElement | null>(null)

// ── KYC Form (minimal — only DB-required fields) ──
const kycForm = reactive({
  last_name: '',
  first_name: '',
  region_code: 'HU',
  address_zip: '',
  address_city: '',
  address_street_name: '',
  address_street_type: '',
  address_house_number: '',
  identity_docs: {
    ID_CARD: { number: '', expiry_date: '' },
    LICENSE: { number: '', expiry_date: '' },
  },
  preferred_language: 'hu',
  preferred_currency: 'HUF',
})

// ── Debounced ZIP → City auto-fill via internal API ──
let zipTimeout: ReturnType<typeof setTimeout>
watch(
  () => kycForm.address_zip,
  (newZip) => {
    clearTimeout(zipTimeout)
    if (newZip && newZip.length >= 3) {
      isCityLoading.value = true
      zipTimeout = setTimeout(async () => {
        try {
          const country = kycForm.region_code || 'HU'
          const response = await fetch(`/api/v1/system/zip-lookup?country_code=${country}&zip_code=${newZip}`)
          if (response.ok) {
            const data = await response.json()
            kycForm.address_city = data.city
          }
        } catch (error) {
          console.error('Cím lekérdezési hiba:', error)
        } finally {
          isCityLoading.value = false
        }
      }, 600) // 600ms késleltetés a gépelés után
    } else {
      isCityLoading.value = false
    }
  }
)

// ── Step circle styling ──
function stepCircleClass(idx: number): string {
  const stepNum = idx + 1
  if (currentStep.value > stepNum) {
    return 'bg-[#00E5A0] text-[#04151F]'
  }
  if (currentStep.value === stepNum) {
    return 'bg-[#00E5A0]/20 text-[#00E5A0] border-2 border-[#00E5A0]'
  }
  return 'bg-white/5 text-white/30 border border-white/10'
}

// ── Simple step validation (Soft KYC) ──
function validateStep(): boolean {
  errorMessage.value = null

  if (currentStep.value === 1) {
    if (!kycForm.last_name) { errorMessage.value = 'Kérlek add meg a vezetéknevedet.'; return false }
    if (!kycForm.first_name) { errorMessage.value = 'Kérlek add meg a keresztnevedet.'; return false }
  }

  if (currentStep.value === 2) {
    if (!kycForm.address_zip) { errorMessage.value = 'Kérlek add meg az irányítószámot.'; return false }
    if (!kycForm.address_city) { errorMessage.value = 'Kérlek add meg a várost.'; return false }
    // Soft KYC: Utca, típus, házszám már NEM kötelező
  }

  // Step 3 has no required validations anymore (Soft KYC - all optional)
  
  return true
}

// ── Navigation ──
function nextStep() {
  if (!validateStep()) return
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

function prevStep() {
  if (currentStep.value > 1) {
    currentStep.value--
    errorMessage.value = null
  }
}

// ── Tab order fix: Házszám → Tovább gomb ──
function handleHouseNumberTab(event: KeyboardEvent) {
  if (currentStep.value === 2 && nextButton.value) {
    event.preventDefault()
    nextTick(() => {
      nextButton.value?.focus()
    })
  }
}

// ── Submit ──
async function handleSubmit() {
  if (!validateStep()) return

  isSubmitting.value = true
  errorMessage.value = null

  try {
    // Build the payload matching UserKYCComplete schema (Soft KYC)
    const payload: any = {
      first_name: kycForm.first_name,
      last_name: kycForm.last_name,
      region_code: kycForm.region_code,
      address_zip: kycForm.address_zip,
      address_city: kycForm.address_city,
      preferred_language: kycForm.preferred_language,
      preferred_currency: kycForm.preferred_currency,
    }

    // Soft KYC: Csak akkor küldjük a részletes címet, ha ki van töltve
    if (kycForm.address_street_name) payload.address_street_name = kycForm.address_street_name
    if (kycForm.address_street_type) payload.address_street_type = kycForm.address_street_type
    if (kycForm.address_house_number) payload.address_house_number = kycForm.address_house_number

    // Only include identity_docs if at least one document is filled
    const hasIdCard = kycForm.identity_docs.ID_CARD.number || kycForm.identity_docs.ID_CARD.expiry_date
    const hasLicense = kycForm.identity_docs.LICENSE.number || kycForm.identity_docs.LICENSE.expiry_date

    if (hasIdCard || hasLicense) {
      payload.identity_docs = {}
      if (hasIdCard) {
        payload.identity_docs.ID_CARD = {
          number: kycForm.identity_docs.ID_CARD.number || null,
          expiry_date: kycForm.identity_docs.ID_CARD.expiry_date || null,
        }
      }
      if (hasLicense) {
        payload.identity_docs.LICENSE = {
          number: kycForm.identity_docs.LICENSE.number || null,
          expiry_date: kycForm.identity_docs.LICENSE.expiry_date || null,
        }
      }
    }

    await authStore.completeKyc(payload)

    // Navigate to dashboard on success
    router.push('/dashboard')
  } catch (err: any) {
    errorMessage.value =
      err.response?.data?.detail ||
      err.response?.data?.message ||
      'A KYC kitöltése sikertelen. Kérlek ellenőrizd az adatokat és próbáld újra.'
  } finally {
    isSubmitting.value = false
  }
}
</script>
