<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle>Edit User</DialogTitle>
        <DialogDescription>
          Update user information and permissions
        </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="edit_first_name">First Name</Label>
            <Input
              id="edit_first_name"
              v-model="formData.first_name"
              placeholder="John"
              required
              :class="{ 'border-orange-500': isModified('first_name') }"
            />
          </div>
          <div class="space-y-2">
            <Label for="edit_last_name">Last Name</Label>
            <Input
              id="edit_last_name"
              v-model="formData.last_name"
              placeholder="Doe"
              required
              :class="{ 'border-orange-500': isModified('last_name') }"
            />
          </div>
        </div>

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

        <div class="space-y-2">
          <Label for="edit_role">Role</Label>
          <Select 
            v-model="formData.role" 
            required
            :disabled="!!isCurrentUser"
          >
            <SelectTrigger :class="{ 'border-orange-500': isModified('role') }">
              <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>
          <p v-if="isCurrentUser" class="text-xs text-muted-foreground">
            Cannot change your own role
          </p>
        </div>

        <div class="flex items-center space-x-4">
          <div class="flex items-center space-x-2">
            <Checkbox
              id="edit_is_approved"
              :checked="formData.is_approved"
              @update:checked="(val: boolean) => formData.is_approved = val"
              :class="{ 'border-orange-500': isModified('is_approved') }"
            />
            <Label for="edit_is_approved" class="text-sm font-normal cursor-pointer">
              Approved
            </Label>
          </div>
          <div class="flex items-center space-x-2">
            <Checkbox
              id="edit_is_admin"
              :checked="formData.is_admin"
              @update:checked="(val: boolean) => formData.is_admin = val"
              :disabled="!!(isCurrentUser && user?.is_admin)"
              :class="{ 'border-orange-500': isModified('is_admin') }"
            />
            <Label for="edit_is_admin" class="text-sm font-normal cursor-pointer">
              Admin Permission
            </Label>
          </div>
        </div>
        <p v-if="isCurrentUser && user?.is_admin" class="text-xs text-muted-foreground">
          Cannot remove your own admin permission
        </p>

        <div v-if="hasModifications" class="bg-orange-50 dark:bg-orange-950 border border-orange-200 dark:border-orange-800 rounded-md p-3">
          <p class="text-sm text-orange-800 dark:text-orange-200 font-medium">
            Modified fields are highlighted
          </p>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            @click="$emit('update:open', false)"
            :disabled="isSubmitting"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            :disabled="!isFormValid || !hasModifications || isSubmitting"
          >
            <Loader2 v-if="isSubmitting" class="h-4 w-4 mr-2 animate-spin" />
            Save Changes
          </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 { Loader2 } from 'lucide-vue-next'
import type { User } from '@/types/auth'

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

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

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

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

const formData = ref({
  first_name: '',
  last_name: '',
  email: '',
  role: 'artist' as 'artist' | 'coordinator' | 'director' | 'developer',
  is_approved: true,
  is_admin: false
})

const originalData = ref({
  first_name: '',
  last_name: '',
  email: '',
  role: 'artist' as 'artist' | 'coordinator' | 'director' | 'developer',
  is_approved: true,
  is_admin: false
})

const emailError = ref('')

const isCurrentUser = computed(() => {
  return props.user && props.currentUserId && props.user.id === props.currentUserId
})

const isModified = (field: keyof typeof formData.value) => {
  return formData.value[field] !== originalData.value[field]
}

const hasModifications = computed(() => {
  return Object.keys(formData.value).some(key => 
    isModified(key as keyof typeof formData.value)
  )
})

const isFormValid = computed(() => {
  return formData.value.first_name &&
         formData.value.last_name &&
         formData.value.email &&
         formData.value.role &&
         !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 handleSubmit = () => {
  if (!isFormValid.value || !hasModifications.value || !props.user) return
  
  // Send all fields (Pydantic v2 requires all fields even if Optional)
  const changes: UserEditData = {
    first_name: formData.value.first_name,
    last_name: formData.value.last_name,
    email: formData.value.email,
    role: formData.value.role,
    is_approved: formData.value.is_approved,
    is_admin: formData.value.is_admin
  }
  
  emit('submit', props.user.id, changes)
}

// Load user data when dialog opens
watch(() => props.user, (user) => {
  if (user) {
    formData.value = {
      first_name: user.first_name,
      last_name: user.last_name,
      email: user.email,
      role: user.role,
      is_approved: user.is_approved,
      is_admin: user.is_admin
    }
    originalData.value = { ...formData.value }
    emailError.value = ''
  }
}, { immediate: true })

// Reset form when dialog closes
watch(() => props.open, (isOpen) => {
  if (!isOpen) {
    emailError.value = ''
  }
})
</script>
