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

const emit = defineEmits<{
  goToCreate: []
  submit: [password: string]
}>()

const showPassword = ref(false)
const isLoading = ref(false)
const error = ref(false)

const passwordSchema = z.string().min(1, 'Password is required')

const form = useForm({
  defaultValues: {
    password: '',
  },
  validators: {
    onChange: z.object({
      password: passwordSchema,
    }),
  },
  onSubmit: async ({ value }) => {
    try {
      isLoading.value = true
      error.value = false
      emit('submit', value.password)
    } catch (err) {
      error.value = true
    } finally {
      isLoading.value = false
    }
  },
})

const handleNewWallet = () => {
  emit('goToCreate')
}

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

defineExpose({
  setError: (val: boolean) => {
    error.value = val
  },
  setLoading: (val: boolean) => {
    isLoading.value = false
  },
})
</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="handleNewWallet">
        <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="relative">
            <div class="flex h-20 w-20 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-accent shadow-xl ring-4 ring-background">
              <img
                src="@/assets/imgs/neptune_logo.jpg"
                alt="Neptune"
                class="h-16 w-16 rounded-xl object-cover"
              />
            </div>
          </div>

          <div class="space-y-2">
            <h1 class="text-3xl font-bold tracking-tight text-foreground">
              Welcome Back
            </h1>
            <p class="text-base text-muted-foreground">
              Enter your password to unlock
            </p>
          </div>
        </div>

        <!-- Form -->
        <Card class="border-2 border-border/50 shadow-xl">
          <CardContent class="p-6">
            <form id="login-form" @submit.prevent="form.handleSubmit">
              <form.Field name="password">
                <template #default="{ field }">
                  <div class="space-y-4">
                    <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': error || isInvalid(field) }"
                          autocomplete="current-password"
                          @blur="field.handleBlur"
                          @input="(e) => {
                            field.handleChange((e.target as HTMLInputElement).value)
                            error = false
                          }"
                        />
                        <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>
                      <p v-if="error" class="text-sm text-destructive">
                        Incorrect password. Please try again.
                      </p>
                    </div>

                    <!-- Submit Button -->
                    <Button
                      type="submit"
                      size="lg"
                      class="h-12 w-full text-base font-semibold"
                      :disabled="!field.state.value || isLoading"
                    >
                      <Loader2 v-if="isLoading" :size="20" class="mr-2 animate-spin" />
                      {{ isLoading ? 'Unlocking...' : 'Unlock Wallet' }}
                    </Button>
                  </div>
                </template>
              </form.Field>
            </form>
          </CardContent>
        </Card>

        <!-- Footer Link -->
        <div class="text-center">
          <p class="text-sm text-muted-foreground">
            Don't have a wallet?
            <Button variant="link" class="p-0 text-sm font-semibold text-primary" @click="handleNewWallet">
              Create one now
            </Button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
