<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle class="text-destructive">Delete User Account</DialogTitle>
        <DialogDescription>
          This action cannot be undone. This will permanently delete the user account.
        </DialogDescription>
      </DialogHeader>
      
      <div class="space-y-4">
        <div v-if="user" class="flex items-center space-x-3 p-3 bg-muted rounded-md">
          <Avatar class="h-10 w-10">
            <AvatarImage
              :src="getInitialsAvatarUrl(user.first_name, user.last_name)"
            />
            <AvatarFallback>{{ getUserInitials(user) }}</AvatarFallback>
          </Avatar>
          <div>
            <div class="font-medium">
              {{ user.first_name }} {{ user.last_name }}
            </div>
            <div class="text-sm text-muted-foreground">
              {{ user.email }}
            </div>
          </div>
        </div>

        <Alert v-if="hasAssociations" variant="destructive">
          <AlertCircle class="h-4 w-4" />
          <AlertTitle>Cannot Delete User</AlertTitle>
          <AlertDescription>
            This user has active associations and cannot be deleted:
            <ul class="list-disc list-inside mt-2 space-y-1">
              <li v-if="associations.projectMemberships > 0">
                {{ associations.projectMemberships }} project membership(s)
              </li>
              <li v-if="associations.taskAssignments > 0">
                {{ associations.taskAssignments }} task assignment(s)
              </li>
            </ul>
            <p class="mt-2">
              Please remove the user from projects and reassign their tasks before deleting.
            </p>
          </AlertDescription>
        </Alert>

        <Alert v-else variant="destructive">
          <AlertCircle class="h-4 w-4" />
          <AlertTitle>Warning</AlertTitle>
          <AlertDescription>
            You are about to permanently delete this user account. This action cannot be undone.
          </AlertDescription>
        </Alert>

        <div v-if="!hasAssociations" class="space-y-2">
          <Label for="confirm_email">
            Type <span class="font-mono font-bold">{{ user?.email }}</span> to confirm
          </Label>
          <Input
            id="confirm_email"
            v-model="confirmEmail"
            placeholder="Enter user email"
            @paste.prevent
          />
        </div>
      </div>

      <DialogFooter>
        <Button
          variant="outline"
          @click="handleCancel"
          :disabled="isDeleting"
        >
          Cancel
        </Button>
        <Button
          v-if="!hasAssociations"
          variant="destructive"
          @click="handleDelete"
          :disabled="!isConfirmed || isDeleting"
        >
          <Loader2 v-if="isDeleting" class="h-4 w-4 mr-2 animate-spin" />
          <Trash2 v-else class="h-4 w-4 mr-2" />
          Delete User
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getInitialsAvatarUrl } = useAvatarUrl()
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 { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { AlertCircle, Loader2, Trash2 } from 'lucide-vue-next'
import type { User } from '@/types/auth'

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

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

interface UserAssociations {
  projectMemberships: number
  taskAssignments: number
}

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

const confirmEmail = ref('')
const associations = ref<UserAssociations>({
  projectMemberships: 0,
  taskAssignments: 0
})

const hasAssociations = computed(() => {
  return associations.value.projectMemberships > 0 || associations.value.taskAssignments > 0
})

const isConfirmed = computed(() => {
  return confirmEmail.value === props.user?.email
})

const getUserInitials = (user: User) => {
  return `${user.first_name.charAt(0)}${user.last_name.charAt(0)}`.toUpperCase()
}

const handleCancel = () => {
  emit('update:open', false)
}

const handleDelete = () => {
  if (!isConfirmed.value || !props.user) return
  
  emit('delete', props.user.id)
}

// Check for associations when user changes
watch(() => props.user, async (user) => {
  if (user) {
    // In a real implementation, you would fetch this from the API
    // For now, we'll assume no associations (the backend will validate)
    associations.value = {
      projectMemberships: 0,
      taskAssignments: 0
    }
  }
}, { immediate: true })

// Reset form when dialog closes
watch(() => props.open, (isOpen) => {
  if (!isOpen) {
    confirmEmail.value = ''
    associations.value = {
      projectMemberships: 0,
      taskAssignments: 0
    }
  }
})
</script>
