<script setup lang="ts">
import { ref } from 'vue'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Lock } from 'lucide-vue-next'

interface Props {
  isOpen: boolean
  title?: string
  description?: string
}

interface Emits {
  (e: 'update:isOpen', value: boolean): void
  (e: 'password', password: string): void
  (e: 'cancel'): void
}

withDefaults(defineProps<Props>(), {
  title: 'Enter Password',
  description: 'Your identity is encrypted. Please enter your password to continue.'
})

const emit = defineEmits<Emits>()

const password = ref('')
const isLoading = ref(false)
const error = ref('')

function handleSubmit() {
  if (!password.value.trim()) {
    error.value = 'Password is required'
    return
  }

  error.value = ''
  emit('password', password.value)
}

function handleCancel() {
  emit('cancel')
  handleClose()
}

function handleClose() {
  emit('update:isOpen', false)
  // Reset form
  password.value = ''
  error.value = ''
  isLoading.value = false
}

function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    handleSubmit()
  }
}
</script>

<template>
  <Dialog :open="isOpen" @update:open="handleClose">
    <DialogContent class="sm:max-w-[425px]">
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2">
          <Lock class="w-5 h-5" />
          {{ title }}
        </DialogTitle>
        <DialogDescription>
          {{ description }}
        </DialogDescription>
      </DialogHeader>

      <div class="grid gap-4 py-4">
        <div class="space-y-2">
          <Label for="password">Password</Label>
          <Input
            id="password"
            type="password"
            v-model="password"
            placeholder="Enter your password"
            :disabled="isLoading"
            @keydown="handleKeydown"
            class="w-full"
            autofocus
          />
          <p v-if="error" class="text-sm text-destructive">
            {{ error }}
          </p>
        </div>
      </div>

      <DialogFooter>
        <Button variant="outline" @click="handleCancel" :disabled="isLoading">
          Cancel
        </Button>
        <Button @click="handleSubmit" :disabled="isLoading || !password.trim()">
          <span v-if="isLoading" class="animate-spin mr-2">⚡</span>
          Unlock
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>