<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { useForm } from '@tanstack/vue-form'
import { z } from 'zod'
import { Eye, EyeOff, Lock, Check, X, ArrowLeft, Shield, KeyRound } from 'lucide-vue-next'
import { ThemeToggle } from '@/components/ui/theme-toggle'

const emit = defineEmits<{
  next: [password: string]
  navigateToRecover: []
}>()

const showPassword = ref(false)
const showConfirmPassword = ref(false)

const passwordSchema = z
  .string()
  .min(8, 'Password must be at least 8 characters')
  .regex(/[A-Z]/, 'Must contain at least one uppercase letter')
  .regex(/[a-z]/, 'Must contain at least one lowercase letter')
  .regex(/[0-9]/, 'Must contain at least one number')

const form = useForm({
  defaultValues: {
    password: '',
    confirmPassword: '',
  },
  validators: {
    onChange: z.object({
      password: passwordSchema,
      confirmPassword: z.string(),
    }),
  },
  onSubmit: async ({ value }) => {
    if (value.password === value.confirmPassword) {
      emit('next', value.password)
    }
  },
})

const passwordStrength = computed(() => {
  const password = form.state.values.password
  if (!password) return { level: 0, text: '', color: '', width: '0%' }

  let strength = 0
  const checks = {
    length: password.length >= 8,
    uppercase: /[A-Z]/.test(password),
    lowercase: /[a-z]/.test(password),
    number: /[0-9]/.test(password),
    special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
  }

  strength = Object.values(checks).filter(Boolean).length

  if (strength <= 2) return { level: 1, text: 'Weak', color: 'bg-destructive', width: '25%' }
  if (strength <= 3) return { level: 2, text: 'Fair', color: 'bg-yellow-500', width: '50%' }
  if (strength <= 4) return { level: 3, text: 'Good', color: 'bg-blue-500', width: '75%' }
  return { level: 4, text: 'Strong', color: 'bg-green-500', width: '100%' }
})

const isPasswordMatch = computed(() => {
  const { password, confirmPassword } = form.state.values
  if (!confirmPassword) return true
  return password === confirmPassword
})

const canProceed = computed(() => {
  const { password, confirmPassword } = form.state.values
  return (
    password.length >= 8 &&
    confirmPassword.length >= 8 &&
    isPasswordMatch.value &&
    passwordStrength.value.level >= 2
  )
})

const handleIHaveWallet = () => {
  emit('navigateToRecover')
}

function isInvalid(field: any) {
  return field.state.meta.isTouched && !field.state.meta.isValid
}
</script>

<template>
  <div class="relative flex min-h-screen flex-col bg-gradient-to-br from-background via-background to-primary/5 p-4">
    <!-- Theme Toggle -->
    <div class="absolute right-4 top-4 z-10">
      <ThemeToggle />
    </div>

    <!-- Back Button -->
    <div class="absolute left-4 top-4 z-10">
      <Button variant="ghost" size="icon" @click="handleIHaveWallet">
        <ArrowLeft :size="20" />
      </Button>
    </div>

    <!-- Content Container -->
    <div class="flex flex-1 flex-col items-center justify-center">
      <div class="w-full max-w-md space-y-8">
        <!-- Header -->
        <div class="flex flex-col items-center space-y-4 text-center">
          <div class="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-accent shadow-xl">
            <Shield :size="32" class="text-primary-foreground" />
          </div>

          <div class="space-y-2">
            <h1 class="text-3xl font-bold tracking-tight text-foreground">
              Create Password
            </h1>
            <p class="text-base text-muted-foreground">
              Secure your new wallet
            </p>
          </div>
        </div>

        <!-- Form -->
        <Card class="border-2 border-border/50 shadow-xl">
          <CardContent class="p-6">
            <form id="create-password-form" @submit.prevent="form.handleSubmit">
              <div class="space-y-6">
                <!-- Password Field -->
                <form.Field name="password">
                  <template #default="{ field }">
                    <div class="space-y-2">
                      <Label :for="field.name" class="text-base">Password</Label>
                      <div class="relative">
                        <Lock
                          :size="20"
                          class="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                        />
                        <Input
                          :id="field.name"
                          :name="field.name"
                          :model-value="field.state.value"
                          :type="showPassword ? 'text' : 'password'"
                          placeholder="Enter your password"
                          class="h-12 pl-11 pr-11 text-base"
                          :class="{ 'border-destructive': isInvalid(field) }"
                          autocomplete="new-password"
                          @blur="field.handleBlur"
                          @input="field.handleChange(($event.target as HTMLInputElement).value)"
                        />
                        <button
                          type="button"
                          class="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                          @click="showPassword = !showPassword"
                        >
                          <Eye v-if="!showPassword" :size="20" />
                          <EyeOff v-else :size="20" />
                        </button>
                      </div>

                      <!-- Password Strength -->
                      <div v-if="field.state.value" class="space-y-2">
                        <div class="flex items-center gap-2">
                          <div class="h-2 flex-1 overflow-hidden rounded-full bg-muted">
                            <div
                              class="h-full transition-all duration-300"
                              :class="passwordStrength.color"
                              :style="{ width: passwordStrength.width }"
                            />
                          </div>
                          <span class="text-xs font-semibold" :class="`text-${passwordStrength.color.replace('bg-', '')}`">
                            {{ passwordStrength.text }}
                          </span>
                        </div>
                      </div>

                      <!-- Error Message -->
                      <p v-if="isInvalid(field)" class="text-sm text-destructive">
                        {{ field.state.meta.errors[0] }}
                      </p>
                    </div>
                  </template>
                </form.Field>

                <!-- Confirm Password Field -->
                <form.Field name="confirmPassword">
                  <template #default="{ field }">
                    <div class="space-y-2">
                      <Label :for="field.name" class="text-base">Confirm Password</Label>
                      <div class="relative">
                        <KeyRound
                          :size="20"
                          class="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
                        />
                        <Input
                          :id="field.name"
                          :name="field.name"
                          :model-value="field.state.value"
                          :type="showConfirmPassword ? 'text' : 'password'"
                          placeholder="Re-enter your password"
                          class="h-12 pl-11 pr-11 text-base"
                          :class="{ 'border-destructive': field.state.value && !isPasswordMatch }"
                          autocomplete="new-password"
                          @blur="field.handleBlur"
                          @input="field.handleChange(($event.target as HTMLInputElement).value)"
                        />
                        <button
                          type="button"
                          class="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                          @click="showConfirmPassword = !showConfirmPassword"
                        >
                          <Eye v-if="!showConfirmPassword" :size="20" />
                          <EyeOff v-else :size="20" />
                        </button>
                      </div>

                      <!-- Password Match Indicator -->
                      <div v-if="field.state.value" class="flex items-center gap-2">
                        <Check v-if="isPasswordMatch" :size="16" class="text-green-500" />
                        <X v-else :size="16" class="text-destructive" />
                        <span class="text-sm" :class="isPasswordMatch ? 'text-green-500' : 'text-destructive'">
                          {{ isPasswordMatch ? 'Passwords match' : 'Passwords do not match' }}
                        </span>
                      </div>
                    </div>
                  </template>
                </form.Field>

                <!-- Security Info -->
                <Alert>
                  <Shield :size="16" />
                  <AlertDescription class="text-xs">
                    Use at least 8 characters with uppercase, lowercase, and numbers for a strong password.
                  </AlertDescription>
                </Alert>

                <!-- Submit Button -->
                <Button
                  type="submit"
                  size="lg"
                  class="h-12 w-full text-base font-semibold"
                  :disabled="!canProceed"
                >
                  Continue
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <!-- Footer Link -->
        <div class="text-center">
          <p class="text-sm text-muted-foreground">
            Already have a wallet?
            <Button variant="link" class="p-0 text-sm font-semibold text-primary" @click="handleIHaveWallet">
              Import wallet
            </Button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
