<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle>Reset Password</DialogTitle>
        <DialogDescription>
          Set a new password for {{ user?.first_name }} {{ user?.last_name }}
        </DialogDescription>
      </DialogHeader>
      
      <form @submit.prevent="handleSubmit" class="space-y-4">
        <Alert>
          <AlertCircle class="h-4 w-4" />
          <AlertTitle>Security Notice</AlertTitle>
          <AlertDescription>
            The user will need to use this new password on their next login. Make sure to communicate the password securely.
          </AlertDescription>
        </Alert>

        <div class="space-y-2">
          <Label for="new_password">New Password</Label>
          <div class="relative">
            <Input
              id="new_password"
              v-model="formData.new_password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="Enter new password"
              required
              @input="checkPasswordStrength"
            />
            <Button
              type="button"
              variant="ghost"
              size="sm"
              class="absolute right-0 top-0 h-full px-3"
              @click="showPassword = !showPassword"
            >
              <Eye v-if="!showPassword" class="h-4 w-4" />
              <EyeOff v-else class="h-4 w-4" />
            </Button>
          </div>
          <div class="space-y-1">
            <p class="text-xs text-muted-foreground">Password requirements:</p>
            <ul class="text-xs space-y-1">
              <li :class="passwordChecks.length ? 'text-green-600' : 'text-muted-foreground'">
                <Check v-if="passwordChecks.length" class="h-3 w-3 inline mr-1" />
                <X v-else class="h-3 w-3 inline mr-1" />
                At least 8 characters
              </li>
              <li :class="passwordChecks.uppercase ? 'text-green-600' : 'text-muted-foreground'">
                <Check v-if="passwordChecks.uppercase" class="h-3 w-3 inline mr-1" />
                <X v-else class="h-3 w-3 inline mr-1" />
                One uppercase letter
              </li>
              <li :class="passwordChecks.lowercase ? 'text-green-600' : 'text-muted-foreground'">
                <Check v-if="passwordChecks.lowercase" class="h-3 w-3 inline mr-1" />
                <X v-else class="h-3 w-3 inline mr-1" />
                One lowercase letter
              </li>
              <li :class="passwordChecks.number ? 'text-green-600' : 'text-muted-foreground'">
                <Check v-if="passwordChecks.number" class="h-3 w-3 inline mr-1" />
                <X v-else class="h-3 w-3 inline mr-1" />
                One number
              </li>
            </ul>
            <div v-if="formData.new_password" class="flex items-center space-x-2 mt-2">
              <div class="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                <div
                  class="h-full transition-all"
                  :class="passwordStrengthColor"
                  :style="{ width: `${passwordStrength}%` }"
                ></div>
              </div>
              <span class="text-xs font-medium">{{ passwordStrengthLabel }}</span>
            </div>
          </div>
        </div>

        <div class="space-y-2">
          <Label for="confirm_password">Confirm Password</Label>
          <Input
            id="confirm_password"
            v-model="formData.confirm_password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="Confirm new password"
            required
          />
          <p v-if="passwordMismatch" class="text-sm text-destructive">
            Passwords do not match
          </p>
        </div>

        <div class="flex items-center space-x-2">
          <Button
            type="button"
            variant="outline"
            @click="generatePassword"
            class="flex-1"
          >
            <Shuffle class="h-4 w-4 mr-2" />
            Generate Password
          </Button>
          <Button
            v-if="generatedPassword"
            type="button"
            variant="outline"
            @click="copyToClipboard"
          >
            <Copy class="h-4 w-4 mr-2" />
            Copy
          </Button>
        </div>

        <div v-if="copySuccess" class="bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md p-3">
          <p class="text-sm text-green-800 dark:text-green-200 flex items-center">
            <Check class="h-4 w-4 mr-2" />
            Password copied to clipboard
          </p>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            @click="$emit('update:open', false)"
            :disabled="isSubmitting"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            :disabled="!isFormValid || isSubmitting"
          >
            <Loader2 v-if="isSubmitting" class="h-4 w-4 mr-2 animate-spin" />
            Reset Password
          </Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Eye, EyeOff, Check, X, Loader2, Shuffle, Copy, AlertCircle } from 'lucide-vue-next'
import type { User } from '@/types/auth'

interface Props {
  open: boolean
  user: User | null
  isSubmitting?: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'submit', userId: number, password: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formData = ref({
  new_password: '',
  confirm_password: ''
})

const showPassword = ref(false)
const generatedPassword = ref('')
const copySuccess = ref(false)

const passwordChecks = computed(() => ({
  length: formData.value.new_password.length >= 8,
  uppercase: /[A-Z]/.test(formData.value.new_password),
  lowercase: /[a-z]/.test(formData.value.new_password),
  number: /[0-9]/.test(formData.value.new_password)
}))

const passwordStrength = computed(() => {
  const checks = Object.values(passwordChecks.value).filter(Boolean).length
  return (checks / 4) * 100
})

const passwordStrengthLabel = computed(() => {
  if (passwordStrength.value === 0) return ''
  if (passwordStrength.value <= 25) return 'Weak'
  if (passwordStrength.value <= 50) return 'Fair'
  if (passwordStrength.value <= 75) return 'Good'
  return 'Strong'
})

const passwordStrengthColor = computed(() => {
  if (passwordStrength.value <= 25) return 'bg-red-500'
  if (passwordStrength.value <= 50) return 'bg-orange-500'
  if (passwordStrength.value <= 75) return 'bg-yellow-500'
  return 'bg-green-500'
})

const passwordMismatch = computed(() => {
  return formData.value.confirm_password && 
         formData.value.new_password !== formData.value.confirm_password
})

const isFormValid = computed(() => {
  return formData.value.new_password &&
         formData.value.confirm_password &&
         !passwordMismatch.value &&
         Object.values(passwordChecks.value).every(Boolean)
})

const checkPasswordStrength = () => {
  // Password strength is computed automatically
}

const generatePassword = () => {
  const length = 16
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'
  let password = ''
  
  // Ensure at least one of each required character type
  password += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)]
  password += 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)]
  password += '0123456789'[Math.floor(Math.random() * 10)]
  
  // Fill the rest randomly
  for (let i = password.length; i < length; i++) {
    password += charset[Math.floor(Math.random() * charset.length)]
  }
  
  // Shuffle the password
  password = password.split('').sort(() => Math.random() - 0.5).join('')
  
  formData.value.new_password = password
  formData.value.confirm_password = password
  generatedPassword.value = password
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(generatedPassword.value)
    copySuccess.value = true
    setTimeout(() => {
      copySuccess.value = false
    }, 3000)
  } catch (err) {
    console.error('Failed to copy password:', err)
  }
}

const handleSubmit = () => {
  if (!isFormValid.value || !props.user) return
  
  emit('submit', props.user.id, formData.value.new_password)
}

// Reset form when dialog closes
watch(() => props.open, (isOpen) => {
  if (!isOpen) {
    formData.value = {
      new_password: '',
      confirm_password: ''
    }
    showPassword.value = false
    generatedPassword.value = ''
    copySuccess.value = false
  }
})
</script>
