<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle>Create New User</DialogTitle>
        <DialogDescription>
          Add a new user account to the system
        </DialogDescription>
      </DialogHeader>
      
      <form @submit.prevent="handleSubmit" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <Label for="first_name">First Name</Label>
            <Input
              id="first_name"
              v-model="formData.first_name"
              placeholder="John"
              required
            />
          </div>
          <div class="space-y-2">
            <Label for="last_name">Last Name</Label>
            <Input
              id="last_name"
              v-model="formData.last_name"
              placeholder="Doe"
              required
            />
          </div>
        </div>

        <div class="space-y-2">
          <Label for="email">Email</Label>
          <Input
            id="email"
            v-model="formData.email"
            type="email"
            placeholder="john.doe@example.com"
            required
            @blur="validateEmail"
          />
          <p v-if="emailError" class="text-sm text-destructive">{{ emailError }}</p>
        </div>

        <div class="space-y-2">
          <Label for="password">Password</Label>
          <div class="relative">
            <Input
              id="password"
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="Enter 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.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 password"
            required
          />
          <p v-if="passwordMismatch" class="text-sm text-destructive">
            Passwords do not match
          </p>
        </div>

        <div class="space-y-2">
          <Label for="role">Role</Label>
          <Select v-model="formData.role" required>
            <SelectTrigger>
              <SelectValue placeholder="Select role" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="artist">Artist</SelectItem>
              <SelectItem value="coordinator">Coordinator</SelectItem>
              <SelectItem value="director">Director</SelectItem>
              <SelectItem value="developer">Developer</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="flex items-center space-x-4">
          <div class="flex items-center space-x-2">
            <Checkbox
              id="is_approved"
              v-model:checked="formData.is_approved"
            />
            <Label for="is_approved" class="text-sm font-normal cursor-pointer">
              Approved
            </Label>
          </div>
          <div class="flex items-center space-x-2">
            <Checkbox
              id="is_admin"
              v-model:checked="formData.is_admin"
            />
            <Label for="is_admin" class="text-sm font-normal cursor-pointer">
              Admin Permission
            </Label>
          </div>
        </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" />
            Create User
          </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 { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Eye, EyeOff, Check, X, Loader2 } from 'lucide-vue-next'

interface Props {
  open: boolean
  isSubmitting?: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'submit', data: UserCreateData): void
}

export interface UserCreateData {
  email: string
  password: string
  first_name: string
  last_name: string
  role: 'artist' | 'coordinator' | 'director' | 'developer'
  is_approved: boolean
  is_admin: boolean
}

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

const formData = ref<UserCreateData & { confirm_password: string }>({
  email: '',
  password: '',
  confirm_password: '',
  first_name: '',
  last_name: '',
  role: 'artist',
  is_approved: true,
  is_admin: false
})

const showPassword = ref(false)
const emailError = ref('')

const passwordChecks = computed(() => ({
  length: formData.value.password.length >= 8,
  uppercase: /[A-Z]/.test(formData.value.password),
  lowercase: /[a-z]/.test(formData.value.password),
  number: /[0-9]/.test(formData.value.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.password !== formData.value.confirm_password
})

const isFormValid = computed(() => {
  return formData.value.first_name &&
         formData.value.last_name &&
         formData.value.email &&
         formData.value.password &&
         formData.value.confirm_password &&
         formData.value.role &&
         !passwordMismatch.value &&
         Object.values(passwordChecks.value).every(Boolean) &&
         !emailError.value
})

const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (formData.value.email && !emailRegex.test(formData.value.email)) {
    emailError.value = 'Please enter a valid email address'
  } else {
    emailError.value = ''
  }
}

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

const handleSubmit = () => {
  if (!isFormValid.value) return
  
  const { confirm_password, ...submitData } = formData.value
  emit('submit', submitData)
}

// Reset form when dialog closes
watch(() => props.open, (isOpen) => {
  if (!isOpen) {
    formData.value = {
      email: '',
      password: '',
      confirm_password: '',
      first_name: '',
      last_name: '',
      role: 'artist',
      is_approved: true,
      is_admin: false
    }
    emailError.value = ''
    showPassword.value = false
  }
})
</script>
