<template>
  <div class="space-y-6">
    <div class="space-y-4">
      <!-- Current Password -->
      <div class="space-y-2">
        <Label for="current-password">Current Password</Label>
        <div class="relative">
          <Input
            id="current-password"
            :type="showCurrentPassword ? 'text' : 'password'"
            v-model="currentPassword"
            placeholder="Enter current password"
            :disabled="isSubmitting"
            @blur="validateCurrentPassword"
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            class="absolute right-0 top-0 h-full px-3"
            @click="showCurrentPassword = !showCurrentPassword"
          >
            <Eye v-if="!showCurrentPassword" class="h-4 w-4" />
            <EyeOff v-else class="h-4 w-4" />
          </Button>
        </div>
        <p v-if="errors.currentPassword" class="text-sm text-destructive">
          {{ errors.currentPassword }}
        </p>
      </div>

      <!-- New Password -->
      <div class="space-y-2">
        <Label for="new-password">New Password</Label>
        <div class="relative">
          <Input
            id="new-password"
            :type="showNewPassword ? 'text' : 'password'"
            v-model="newPassword"
            placeholder="Enter new password"
            :disabled="isSubmitting"
            @input="validateNewPassword"
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            class="absolute right-0 top-0 h-full px-3"
            @click="showNewPassword = !showNewPassword"
          >
            <Eye v-if="!showNewPassword" class="h-4 w-4" />
            <EyeOff v-else class="h-4 w-4" />
          </Button>
        </div>
        
        <!-- Password Strength Indicator -->
        <div v-if="newPassword" class="space-y-2">
          <div class="flex items-center gap-2">
            <div class="flex-1 h-2 bg-secondary rounded-full overflow-hidden">
              <div
                class="h-full transition-all duration-300"
                :class="passwordStrengthColor"
                :style="{ width: `${passwordStrengthPercent}%` }"
              />
            </div>
            <span class="text-xs font-medium" :class="passwordStrengthTextColor">
              {{ passwordStrengthText }}
            </span>
          </div>
        </div>

        <p v-if="errors.newPassword" class="text-sm text-destructive">
          {{ errors.newPassword }}
        </p>
      </div>

      <!-- Confirm Password -->
      <div class="space-y-2">
        <Label for="confirm-password">Confirm New Password</Label>
        <div class="relative">
          <Input
            id="confirm-password"
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            placeholder="Confirm new password"
            :disabled="isSubmitting"
            @input="validateConfirmPassword"
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            class="absolute right-0 top-0 h-full px-3"
            @click="showConfirmPassword = !showConfirmPassword"
          >
            <Eye v-if="!showConfirmPassword" class="h-4 w-4" />
            <EyeOff v-else class="h-4 w-4" />
          </Button>
        </div>
        <p v-if="errors.confirmPassword" class="text-sm text-destructive">
          {{ errors.confirmPassword }}
        </p>
      </div>

      <!-- Password Requirements -->
      <div class="rounded-lg border p-4 space-y-2">
        <p class="text-sm font-medium">Password Requirements:</p>
        <ul class="text-sm space-y-1">
          <li class="flex items-center gap-2" :class="requirements.minLength ? 'text-green-600' : 'text-muted-foreground'">
            <Check v-if="requirements.minLength" class="h-4 w-4" />
            <X v-else class="h-4 w-4" />
            At least 8 characters
          </li>
          <li class="flex items-center gap-2" :class="requirements.hasUppercase ? 'text-green-600' : 'text-muted-foreground'">
            <Check v-if="requirements.hasUppercase" class="h-4 w-4" />
            <X v-else class="h-4 w-4" />
            One uppercase letter
          </li>
          <li class="flex items-center gap-2" :class="requirements.hasLowercase ? 'text-green-600' : 'text-muted-foreground'">
            <Check v-if="requirements.hasLowercase" class="h-4 w-4" />
            <X v-else class="h-4 w-4" />
            One lowercase letter
          </li>
          <li class="flex items-center gap-2" :class="requirements.hasNumber ? 'text-green-600' : 'text-muted-foreground'">
            <Check v-if="requirements.hasNumber" class="h-4 w-4" />
            <X v-else class="h-4 w-4" />
            One number
          </li>
          <li class="flex items-center gap-2" :class="requirements.hasSpecial ? 'text-green-600' : 'text-muted-foreground'">
            <Check v-if="requirements.hasSpecial" class="h-4 w-4" />
            <X v-else class="h-4 w-4" />
            One special character (!@#$%^&*)
          </li>
        </ul>
      </div>
    </div>

    <!-- Action Buttons -->
    <div class="flex gap-2">
      <Button
        @click="handleSubmit"
        :disabled="!isFormValid || isSubmitting"
      >
        <Loader2 v-if="isSubmitting" class="h-4 w-4 mr-2 animate-spin" />
        Change Password
      </Button>
      <Button
        variant="outline"
        @click="handleReset"
        :disabled="isSubmitting"
      >
        Reset
      </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Eye, EyeOff, Check, X, Loader2 } from 'lucide-vue-next'
import { useToast } from '@/components/ui/toast/use-toast'
import { userService } from '@/services/user'

const emit = defineEmits<{
  (e: 'password-changed'): void
}>()

const { toast } = useToast()

const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const showCurrentPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)
const isSubmitting = ref(false)

const errors = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// Password requirements
const requirements = computed(() => ({
  minLength: newPassword.value.length >= 8,
  hasUppercase: /[A-Z]/.test(newPassword.value),
  hasLowercase: /[a-z]/.test(newPassword.value),
  hasNumber: /\d/.test(newPassword.value),
  hasSpecial: /[!@#$%^&*(),.?":{}|<>]/.test(newPassword.value)
}))

// Password strength calculation
const passwordStrength = computed(() => {
  const reqs = requirements.value
  const metRequirements = Object.values(reqs).filter(Boolean).length
  
  if (metRequirements === 0) return 0
  if (metRequirements <= 2) return 1 // Weak
  if (metRequirements <= 4) return 2 // Medium
  return 3 // Strong
})

const passwordStrengthPercent = computed(() => {
  return (passwordStrength.value / 3) * 100
})

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return ''
  if (strength === 1) return 'Weak'
  if (strength === 2) return 'Medium'
  return 'Strong'
})

const passwordStrengthColor = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return 'bg-secondary'
  if (strength === 1) return 'bg-red-500'
  if (strength === 2) return 'bg-yellow-500'
  return 'bg-green-500'
})

const passwordStrengthTextColor = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return 'text-muted-foreground'
  if (strength === 1) return 'text-red-500'
  if (strength === 2) return 'text-yellow-500'
  return 'text-green-500'
})

const isFormValid = computed(() => {
  return (
    currentPassword.value.length > 0 &&
    newPassword.value.length >= 8 &&
    confirmPassword.value === newPassword.value &&
    Object.values(requirements.value).every(Boolean) &&
    !errors.value.currentPassword &&
    !errors.value.newPassword &&
    !errors.value.confirmPassword
  )
})

const validateCurrentPassword = () => {
  if (!currentPassword.value) {
    errors.value.currentPassword = 'Current password is required'
  } else {
    errors.value.currentPassword = ''
  }
}

const validateNewPassword = () => {
  if (!newPassword.value) {
    errors.value.newPassword = 'New password is required'
  } else if (newPassword.value.length < 8) {
    errors.value.newPassword = 'Password must be at least 8 characters'
  } else if (!Object.values(requirements.value).every(Boolean)) {
    errors.value.newPassword = 'Password does not meet all requirements'
  } else if (newPassword.value === currentPassword.value) {
    errors.value.newPassword = 'New password must be different from current password'
  } else {
    errors.value.newPassword = ''
  }
  
  // Re-validate confirm password if it has a value
  if (confirmPassword.value) {
    validateConfirmPassword()
  }
}

const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    errors.value.confirmPassword = 'Please confirm your new password'
  } else if (confirmPassword.value !== newPassword.value) {
    errors.value.confirmPassword = 'Passwords do not match'
  } else {
    errors.value.confirmPassword = ''
  }
}

const handleSubmit = async () => {
  // Validate all fields
  validateCurrentPassword()
  validateNewPassword()
  validateConfirmPassword()

  if (!isFormValid.value) {
    return
  }

  isSubmitting.value = true

  try {
    await userService.changePassword({
      current_password: currentPassword.value,
      new_password: newPassword.value
    })

    toast({
      title: 'Success',
      description: 'Password changed successfully',
    })

    emit('password-changed')
    handleReset()
  } catch (error: any) {
    const errorMessage = error.response?.data?.detail || 'Failed to change password'
    
    // Check if it's a current password error
    if (errorMessage.toLowerCase().includes('incorrect') || errorMessage.toLowerCase().includes('current password')) {
      errors.value.currentPassword = errorMessage
    }
    
    toast({
      title: 'Error',
      description: errorMessage,
      variant: 'destructive',
    })
  } finally {
    isSubmitting.value = false
  }
}

const handleReset = () => {
  currentPassword.value = ''
  newPassword.value = ''
  confirmPassword.value = ''
  showCurrentPassword.value = false
  showNewPassword.value = false
  showConfirmPassword.value = false
  errors.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}
</script>
