<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="max-w-3xl max-h-[90vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2 text-destructive">
          <AlertTriangle class="h-5 w-5" />
          Permanent Delete {{ isBulkOperation ? `${itemCount} Items` : itemName }}
        </DialogTitle>
        <DialogDescription>
          This action is <strong>irreversible</strong> and will permanently remove all data from the database and file system.
          This is NOT a soft delete - the data cannot be recovered.
        </DialogDescription>
      </DialogHeader>

      <!-- Loading State -->
      <div v-if="isLoadingInfo" class="flex items-center justify-center py-8">
        <div class="flex items-center gap-2">
          <Loader2 class="h-4 w-4 animate-spin" />
          <span class="text-sm text-muted-foreground">Loading deletion information...</span>
        </div>
      </div>

      <!-- Error State -->
      <Alert v-else-if="loadError" variant="destructive">
        <AlertCircle class="h-4 w-4" />
        <AlertTitle>Failed to load deletion information</AlertTitle>
        <AlertDescription>{{ loadError }}</AlertDescription>
      </Alert>

      <!-- Deletion Information -->
      <div v-else class="space-y-4">
        <!-- Critical Warning -->
        <Alert variant="destructive">
          <AlertTriangle class="h-4 w-4" />
          <AlertTitle>⚠️ PERMANENT DELETION WARNING</AlertTitle>
          <AlertDescription class="space-y-2">
            <p class="font-semibold">This action will PERMANENTLY and IRREVERSIBLY:</p>
            <ul class="list-disc list-inside space-y-1 ml-2">
              <li>Remove all database records</li>
              <li>Delete all associated files from the file system</li>
              <li>Remove all related tasks, submissions, attachments, notes, and reviews</li>
              <li>Erase all activity history</li>
            </ul>
            <p class="font-semibold mt-3 text-destructive-foreground">
              ⚠️ THIS CANNOT BE UNDONE. THERE IS NO RECOVERY OPTION.
            </p>
          </AlertDescription>
        </Alert>

        <!-- Bulk Operation Summary -->
        <div v-if="isBulkOperation" class="rounded-lg border bg-muted/20 p-4">
          <h3 class="font-medium mb-3">Items to be Permanently Deleted</h3>
          <div class="max-h-40 overflow-y-auto space-y-2">
            <div
              v-for="item in items"
              :key="`${item.type}-${item.id}`"
              class="flex items-center justify-between p-2 bg-background rounded border"
            >
              <div class="flex-1">
                <div class="font-medium text-sm">{{ item.name }}</div>
                <div class="text-xs text-muted-foreground">
                  {{ item.type === 'shot' ? 'Shot' : 'Asset' }} • {{ item.project_name }}
                </div>
              </div>
              <Badge variant="outline">{{ item.type }}</Badge>
            </div>
          </div>
        </div>

        <!-- Single Item Details -->
        <div v-else-if="items.length === 1" class="rounded-lg border bg-muted/20 p-4">
          <h3 class="font-medium mb-3">Item Details</h3>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-muted-foreground">Name:</span>
              <span class="font-medium">{{ items[0].name }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-muted-foreground">Type:</span>
              <Badge variant="outline">{{ items[0].type }}</Badge>
            </div>
            <div class="flex justify-between">
              <span class="text-muted-foreground">Project:</span>
              <span class="font-medium">{{ items[0].project_name }}</span>
            </div>
            <div v-if="items[0].episode_name" class="flex justify-between">
              <span class="text-muted-foreground">Episode:</span>
              <span class="font-medium">{{ items[0].episode_name }}</span>
            </div>
          </div>
        </div>

        <!-- Impact Summary -->
        <div class="rounded-lg border bg-destructive/10 p-4">
          <h3 class="font-medium mb-3 text-destructive">Deletion Impact</h3>
          <div class="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
            <div class="flex items-center gap-2">
              <ListTodo class="h-4 w-4 text-muted-foreground" />
              <span>{{ totalCounts.tasks }} task{{ totalCounts.tasks === 1 ? '' : 's' }}</span>
            </div>
            <div class="flex items-center gap-2">
              <Upload class="h-4 w-4 text-muted-foreground" />
              <span>{{ totalCounts.submissions }} submission{{ totalCounts.submissions === 1 ? '' : 's' }}</span>
            </div>
            <div class="flex items-center gap-2">
              <Paperclip class="h-4 w-4 text-muted-foreground" />
              <span>{{ totalCounts.attachments }} attachment{{ totalCounts.attachments === 1 ? '' : 's' }}</span>
            </div>
            <div class="flex items-center gap-2">
              <MessageSquare class="h-4 w-4 text-muted-foreground" />
              <span>{{ totalCounts.notes }} note{{ totalCounts.notes === 1 ? '' : 's' }}</span>
            </div>
            <div class="flex items-center gap-2">
              <CheckCircle class="h-4 w-4 text-muted-foreground" />
              <span>{{ totalCounts.reviews }} review{{ totalCounts.reviews === 1 ? '' : 's' }}</span>
            </div>
            <div class="flex items-center gap-2">
              <HardDrive class="h-4 w-4 text-muted-foreground" />
              <span>{{ formatFileSize(totalCounts.fileSize) }} files</span>
            </div>
          </div>
        </div>

        <!-- Security Notice -->
        <Alert variant="default" class="border-orange-200 bg-orange-50">
          <Shield class="h-4 w-4 text-orange-600" />
          <AlertTitle class="text-orange-800">Security Confirmation Required</AlertTitle>
          <AlertDescription class="text-orange-700">
            To prevent accidental deletion, you must type the confirmation phrase exactly as shown below.
          </AlertDescription>
        </Alert>

        <!-- Confirmation Input -->
        <div class="space-y-2">
          <Label for="confirm-input" class="text-base">
            Type <code class="bg-destructive/20 px-2 py-1 rounded text-sm font-mono font-bold">{{ confirmationPhrase }}</code> to confirm permanent deletion:
          </Label>
          <Input
            id="confirm-input"
            v-model="confirmationText"
            placeholder="Type the confirmation phrase"
            class="font-mono"
            :class="{ 'border-destructive': confirmationText && !isConfirmed }"
            @paste.prevent
          />
          <p v-if="confirmationText && !isConfirmed" class="text-xs text-destructive">
            Confirmation phrase does not match. Please type it exactly as shown.
          </p>
        </div>

        <!-- Final Warning -->
        <Alert variant="destructive" class="border-2">
          <AlertTriangle class="h-4 w-4" />
          <AlertDescription class="font-semibold">
            By confirming this action, you acknowledge that all data will be permanently destroyed and cannot be recovered by any means.
          </AlertDescription>
        </Alert>
      </div>

      <DialogFooter>
        <Button
          variant="outline"
          @click="handleCancel"
          :disabled="isDeleting"
        >
          Cancel
        </Button>
        <Button
          variant="destructive"
          @click="handleDelete"
          :disabled="!isConfirmed || isDeleting || isLoadingInfo || !!loadError"
        >
          <Loader2 v-if="isDeleting" class="mr-2 h-4 w-4 animate-spin" />
          <Trash2 v-else class="mr-2 h-4 w-4" />
          {{ isDeleting ? 'Deleting...' : 'Permanently Delete' }}
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  AlertTriangle,
  AlertCircle,
  CheckCircle,
  Loader2,
  ListTodo,
  Upload,
  Paperclip,
  MessageSquare,
  HardDrive,
  Shield,
  Trash2
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from '@/components/ui/alert'

interface DeletedItem {
  id: number
  name: string
  type: 'shot' | 'asset'
  project_name: string
  episode_name?: string
  task_count: number
  submission_count: number
  attachment_count: number
  note_count: number
  review_count: number
}

interface Props {
  open: boolean
  items: DeletedItem[]
  isDeleting?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  'confirm-delete': [confirmationToken: string]
}>()

// State
const confirmationText = ref('')
const isLoadingInfo = ref(false)
const loadError = ref<string | null>(null)

// Computed
const isBulkOperation = computed(() => props.items.length > 1)

const itemCount = computed(() => props.items.length)

const itemName = computed(() => {
  if (props.items.length === 0) return ''
  return props.items[0].name
})

const confirmationPhrase = computed(() => {
  if (isBulkOperation.value) {
    return `DELETE ${itemCount.value} ITEMS`
  }
  return `DELETE ${itemName.value}`
})

const isConfirmed = computed(() => {
  return confirmationText.value === confirmationPhrase.value
})

const totalCounts = computed(() => {
  return props.items.reduce(
    (acc, item) => ({
      tasks: acc.tasks + item.task_count,
      submissions: acc.submissions + item.submission_count,
      attachments: acc.attachments + item.attachment_count,
      notes: acc.notes + item.note_count,
      reviews: acc.reviews + item.review_count,
      fileSize: acc.fileSize + (item.submission_count + item.attachment_count) * 1024 * 1024 // Estimate
    }),
    { tasks: 0, submissions: 0, attachments: 0, notes: 0, reviews: 0, fileSize: 0 }
  )
})

// Methods
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

const generateConfirmationToken = (): string => {
  // Generate confirmation token that matches backend expectations
  if (isBulkOperation.value) {
    const shotCount = props.items.filter(item => item.type === 'shot').length
    const assetCount = props.items.filter(item => item.type === 'asset').length
    
    if (shotCount > 0 && assetCount > 0) {
      // Mixed bulk operation - will be handled separately by the parent component
      return 'CONFIRM_MIXED_BULK_PERMANENT_DELETE'
    } else if (shotCount > 0) {
      return 'CONFIRM_BULK_SHOTS_PERMANENT_DELETE'
    } else {
      return 'CONFIRM_BULK_ASSETS_PERMANENT_DELETE'
    }
  } else {
    const item = props.items[0]
    if (item.type === 'shot') {
      return 'CONFIRM_SHOT_PERMANENT_DELETE'
    } else {
      return 'CONFIRM_ASSET_PERMANENT_DELETE'
    }
  }
}

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

const handleDelete = () => {
  if (!isConfirmed.value) return

  const confirmationToken = generateConfirmationToken()
  emit('confirm-delete', confirmationToken)
}

// Reset state when dialog opens/closes
watch(() => props.open, (newOpen) => {
  if (newOpen) {
    confirmationText.value = ''
    isLoadingInfo.value = false
    loadError.value = null
  } else {
    confirmationText.value = ''
    isLoadingInfo.value = false
    loadError.value = null
  }
})
</script>
