<template>
  <div class="container mx-auto py-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-3xl font-bold">Recovery Management</h1>
        <p class="text-muted-foreground">
          Recover and restore soft-deleted shots and assets
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <Button @click="refreshData" :disabled="isLoading" variant="outline">
          <RefreshCw :class="{ 'animate-spin': isLoading }" class="w-4 h-4 mr-2" />
          Refresh
        </Button>
        <Button 
          v-if="selectedItems.length > 0" 
          @click="showBulkRecoveryDialog = true"
          :disabled="isRecovering"
        >
          <RotateCcw class="w-4 h-4 mr-2" />
          Recover Selected ({{ selectedItems.length }})
        </Button>
        <Button 
          v-if="selectedItems.length > 0" 
          @click="handleBulkPermanentDelete"
          :disabled="isRecovering"
          variant="destructive"
        >
          <Trash2 class="w-4 h-4 mr-2" />
          Permanent Delete ({{ selectedItems.length }})
        </Button>
      </div>
    </div>

    <!-- Filters and Search -->
    <Card>
      <CardHeader>
        <CardTitle>Filters</CardTitle>
      </CardHeader>
      <CardContent class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <!-- Project Filter -->
          <div class="space-y-2">
            <Label for="project-filter">Project</Label>
            <Select v-model="selectedProjectId">
              <SelectTrigger id="project-filter">
                <SelectValue placeholder="All Projects" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Projects</SelectItem>
                <SelectItem 
                  v-for="project in availableProjects.filter(p => p.id !== 0)" 
                  :key="project.id" 
                  :value="project.id.toString()"
                >
                  {{ project.name }}
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          <!-- Item Type Filter -->
          <div class="space-y-2">
            <Label for="type-filter">Item Type</Label>
            <Select v-model="selectedItemType">
              <SelectTrigger id="type-filter">
                <SelectValue placeholder="All Types" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="shots">Shots Only</SelectItem>
                <SelectItem value="assets">Assets Only</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <!-- Date Range Filter -->
          <div class="space-y-2">
            <Label for="date-filter">Date Removed</Label>
            <Select v-model="selectedDateRange">
              <SelectTrigger id="date-filter">
                <SelectValue placeholder="All Dates" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Dates</SelectItem>
                <SelectItem value="today">Today</SelectItem>
                <SelectItem value="week">This Week</SelectItem>
                <SelectItem value="month">This Month</SelectItem>
                <SelectItem value="quarter">This Quarter</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <!-- Search -->
          <div class="space-y-2">
            <Label for="search">Search</Label>
            <Input
              id="search"
              v-model="searchQuery"
              placeholder="Search by name..."
              class="w-full"
            />
          </div>
        </div>

        <!-- Sort Options -->
        <div class="flex items-center space-x-4">
          <div class="flex items-center space-x-2">
            <Label for="sort-by">Sort by:</Label>
            <Select v-model="sortBy">
              <SelectTrigger id="sort-by" class="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="name">Name</SelectItem>
                <SelectItem value="deleted_at">Date Removed</SelectItem>
                <SelectItem value="project">Project</SelectItem>
                <SelectItem value="type">Type</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Button 
            @click="sortOrder = sortOrder === 'asc' ? 'desc' : 'asc'"
            variant="outline"
            size="sm"
          >
            <ArrowUpDown class="w-4 h-4 mr-1" />
            {{ sortOrder === 'asc' ? 'Ascending' : 'Descending' }}
          </Button>
        </div>
      </CardContent>
    </Card>

    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center py-8">
      <div class="flex items-center space-x-2">
        <RefreshCw class="w-4 h-4 animate-spin" />
        <span>Loading recovery data...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="text-center py-8">
      <div class="text-red-600 mb-2">{{ error }}</div>
      <Button @click="refreshData" variant="outline">Try Again</Button>
    </div>

    <!-- Results -->
    <div v-else class="space-y-6">
      <!-- Summary Stats -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent class="p-6">
            <div class="flex items-center space-x-2">
              <Film class="w-5 h-5 text-blue-600" />
              <div>
                <p class="text-sm font-medium text-muted-foreground">Shots Available for Recovery</p>
                <p class="text-2xl font-bold">{{ filteredShots.length }}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent class="p-6">
            <div class="flex items-center space-x-2">
              <Package class="w-5 h-5 text-green-600" />
              <div>
                <p class="text-sm font-medium text-muted-foreground">Assets Available for Recovery</p>
                <p class="text-2xl font-bold">{{ filteredAssets.length }}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent class="p-6">
            <div class="flex items-center space-x-2">
              <Database class="w-5 h-5 text-purple-600" />
              <div>
                <p class="text-sm font-medium text-muted-foreground">Total Items</p>
                <p class="text-2xl font-bold">{{ filteredShots.length + filteredAssets.length }}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent class="p-6">
            <div class="flex items-center space-x-2">
              <CheckSquare class="w-5 h-5 text-orange-600" />
              <div>
                <p class="text-sm font-medium text-muted-foreground">Selected</p>
                <p class="text-2xl font-bold">{{ selectedItems.length }}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- Bulk Selection Controls -->
      <div v-if="(filteredShots.length > 0 || filteredAssets.length > 0)" class="flex items-center justify-between p-4 bg-muted rounded-lg">
        <div class="flex items-center space-x-4">
          <Checkbox 
            :checked="isAllSelected"
            @update:checked="toggleSelectAll"
            id="select-all"
          />
          <Label for="select-all" class="font-medium">
            Select All ({{ filteredShots.length + filteredAssets.length }} items)
          </Label>
        </div>
        <div v-if="selectedItems.length > 0" class="text-sm text-muted-foreground">
          {{ selectedItems.length }} item{{ selectedItems.length !== 1 ? 's' : '' }} selected
        </div>
      </div>

      <!-- Items List -->
      <div class="space-y-4">
        <!-- Shots Available for Recovery -->
        <div v-if="shouldShowShots && sortedFilteredShots.length > 0">
          <h3 class="text-lg font-semibold mb-4 flex items-center">
            <Film class="w-5 h-5 mr-2" />
            Shots Available for Recovery ({{ sortedFilteredShots.length }})
          </h3>
          <div class="grid gap-4">
            <Card 
              v-for="shot in sortedFilteredShots" 
              :key="`shot-${shot.id}`" 
              class="hover:shadow-md transition-shadow"
              :class="{ 'ring-2 ring-primary': isItemSelected('shot', shot.id) }"
            >
              <CardContent class="p-6">
                <div class="flex items-start space-x-4">
                  <!-- Selection Checkbox -->
                  <Checkbox 
                    :checked="isItemSelected('shot', shot.id)"
                    @update:checked="(checked: boolean) => toggleItemSelection('shot', shot.id, checked)"
                    class="mt-1"
                  />

                  <!-- Item Details -->
                  <div class="flex-1">
                    <div class="flex items-center space-x-2 mb-2">
                      <h4 class="font-semibold">{{ shot.name }}</h4>
                      <Badge variant="secondary">Shot</Badge>
                    </div>
                    
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm text-muted-foreground mb-4">
                      <div>
                        <span class="font-medium">Episode:</span> {{ shot.episode_name }}
                      </div>
                      <div>
                        <span class="font-medium">Project:</span> {{ shot.project_name }}
                      </div>
                      <div>
                        <span class="font-medium">Removed:</span> {{ formatDate(shot.deleted_at) }}
                      </div>
                      <div>
                        <span class="font-medium">By:</span> {{ shot.deleted_by_name }}
                      </div>
                    </div>

                    <div class="flex items-center space-x-4 text-sm">
                      <span class="flex items-center">
                        <CheckSquare class="w-4 h-4 mr-1" />
                        {{ shot.task_count }} tasks
                      </span>
                      <span class="flex items-center">
                        <FileText class="w-4 h-4 mr-1" />
                        {{ shot.submission_count }} submissions
                      </span>
                      <span class="flex items-center">
                        <Paperclip class="w-4 h-4 mr-1" />
                        {{ shot.attachment_count }} attachments
                      </span>
                      <span class="flex items-center">
                        <MessageSquare class="w-4 h-4 mr-1" />
                        {{ shot.note_count }} notes
                      </span>
                    </div>
                  </div>

                  <!-- Actions -->
                  <div class="flex items-center space-x-2">
                    <Button
                      @click="previewShotRecovery(shot)"
                      variant="outline"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <Eye class="w-4 h-4 mr-1" />
                      Preview
                    </Button>
                    <Button
                      @click="recoverShot(shot)"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <RotateCcw class="w-4 h-4 mr-1" />
                      Recover
                    </Button>
                    <Button
                      @click="handlePermanentDelete('shot', shot)"
                      variant="destructive"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <Trash2 class="w-4 h-4 mr-1" />
                      Permanent Delete
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <!-- Assets Available for Recovery -->
        <div v-if="shouldShowAssets && sortedFilteredAssets.length > 0">
          <h3 class="text-lg font-semibold mb-4 flex items-center">
            <Package class="w-5 h-5 mr-2" />
            Assets Available for Recovery ({{ sortedFilteredAssets.length }})
          </h3>
          <div class="grid gap-4">
            <Card 
              v-for="asset in sortedFilteredAssets" 
              :key="`asset-${asset.id}`" 
              class="hover:shadow-md transition-shadow"
              :class="{ 'ring-2 ring-primary': isItemSelected('asset', asset.id) }"
            >
              <CardContent class="p-6">
                <div class="flex items-start space-x-4">
                  <!-- Selection Checkbox -->
                  <Checkbox 
                    :checked="isItemSelected('asset', asset.id)"
                    @update:checked="(checked: boolean) => toggleItemSelection('asset', asset.id, checked)"
                    class="mt-1"
                  />

                  <!-- Item Details -->
                  <div class="flex-1">
                    <div class="flex items-center space-x-2 mb-2">
                      <h4 class="font-semibold">{{ asset.name }}</h4>
                      <Badge variant="outline">{{ asset.category }}</Badge>
                    </div>
                    
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm text-muted-foreground mb-4">
                      <div>
                        <span class="font-medium">Category:</span> {{ asset.category }}
                      </div>
                      <div>
                        <span class="font-medium">Project:</span> {{ asset.project_name }}
                      </div>
                      <div>
                        <span class="font-medium">Removed:</span> {{ formatDate(asset.deleted_at) }}
                      </div>
                      <div>
                        <span class="font-medium">By:</span> {{ asset.deleted_by_name }}
                      </div>
                    </div>

                    <div class="flex items-center space-x-4 text-sm">
                      <span class="flex items-center">
                        <CheckSquare class="w-4 h-4 mr-1" />
                        {{ asset.task_count }} tasks
                      </span>
                      <span class="flex items-center">
                        <FileText class="w-4 h-4 mr-1" />
                        {{ asset.submission_count }} submissions
                      </span>
                      <span class="flex items-center">
                        <Paperclip class="w-4 h-4 mr-1" />
                        {{ asset.attachment_count }} attachments
                      </span>
                      <span class="flex items-center">
                        <MessageSquare class="w-4 h-4 mr-1" />
                        {{ asset.note_count }} notes
                      </span>
                    </div>
                  </div>

                  <!-- Actions -->
                  <div class="flex items-center space-x-2">
                    <Button
                      @click="previewAssetRecovery(asset)"
                      variant="outline"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <Eye class="w-4 h-4 mr-1" />
                      Preview
                    </Button>
                    <Button
                      @click="recoverAsset(asset)"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <RotateCcw class="w-4 h-4 mr-1" />
                      Recover
                    </Button>
                    <Button
                      @click="handlePermanentDelete('asset', asset)"
                      variant="destructive"
                      size="sm"
                      :disabled="isRecovering"
                    >
                      <Trash2 class="w-4 h-4 mr-1" />
                      Permanent Delete
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <!-- Empty State -->
        <div v-if="filteredShots.length === 0 && filteredAssets.length === 0" class="text-center py-12">
          <Trash2 class="w-12 h-12 mx-auto text-muted-foreground mb-4" />
          <h3 class="text-lg font-semibold mb-2">No items available for recovery</h3>
          <p class="text-muted-foreground">
            {{ searchQuery || (selectedProjectId && selectedProjectId !== 'all') || selectedDateRange !== 'all' ? 'Try adjusting your filters' : 'There are no items currently available for recovery' }}
          </p>
        </div>
      </div>
    </div>

    <!-- Recovery Preview Dialog -->
    <Dialog v-model:open="showPreviewDialog">
      <DialogContent class="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Recovery Preview</DialogTitle>
          <DialogDescription>
            Review what will be recovered before proceeding
          </DialogDescription>
        </DialogHeader>

        <div v-if="previewInfo" class="space-y-4">
          <div class="grid grid-cols-2 gap-4 p-4 bg-muted rounded-lg">
            <div>
              <span class="font-medium">Name:</span> {{ previewInfo.name }}
            </div>
            <div v-if="previewInfo.episode_name">
              <span class="font-medium">Episode:</span> {{ previewInfo.episode_name }}
            </div>
            <div>
              <span class="font-medium">Project:</span> {{ previewInfo.project_name }}
            </div>
            <div>
              <span class="font-medium">Removed:</span> {{ formatDate(previewInfo.deleted_at) }}
            </div>
          </div>

          <div>
            <h4 class="font-semibold mb-2">Items to be recovered:</h4>
            <div class="grid grid-cols-2 gap-4 text-sm">
              <div class="flex justify-between">
                <span>Tasks:</span>
                <Badge variant="secondary">{{ previewInfo.task_count }}</Badge>
              </div>
              <div class="flex justify-between">
                <span>Submissions:</span>
                <Badge variant="secondary">{{ previewInfo.submission_count }}</Badge>
              </div>
              <div class="flex justify-between">
                <span>Attachments:</span>
                <Badge variant="secondary">{{ previewInfo.attachment_count }}</Badge>
              </div>
              <div class="flex justify-between">
                <span>Notes:</span>
                <Badge variant="secondary">{{ previewInfo.note_count }}</Badge>
              </div>
              <div class="flex justify-between">
                <span>Reviews:</span>
                <Badge variant="secondary">{{ previewInfo.review_count }}</Badge>
              </div>
              <div class="flex justify-between">
                <span>Files:</span>
                <Badge variant="secondary">{{ previewInfo.file_count }}</Badge>
              </div>
            </div>
          </div>

          <div class="flex items-center space-x-2 p-3 bg-green-50 border border-green-200 rounded-lg">
            <CheckCircle class="w-5 h-5 text-green-600" />
            <span class="text-sm text-green-800">
              Files are preserved and will be restored with the data
            </span>
          </div>
        </div>

        <DialogFooter>
          <Button @click="showPreviewDialog = false" variant="outline">
            Cancel
          </Button>
          <Button 
            @click="confirmRecovery" 
            :disabled="isRecovering"
          >
            <RotateCcw class="w-4 h-4 mr-1" />
            Confirm Recovery
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- Individual Recovery Confirmation Dialog -->
    <Dialog v-model:open="showConfirmDialog">
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Confirm Recovery</DialogTitle>
          <DialogDescription>
            Are you sure you want to recover this item and all its related data?
          </DialogDescription>
        </DialogHeader>

        <div v-if="itemToRecover" class="space-y-4">
          <div class="p-4 bg-muted rounded-lg">
            <div class="font-semibold">{{ itemToRecover.name }}</div>
            <div class="text-sm text-muted-foreground">
              {{ 'episode_name' in itemToRecover ? itemToRecover.episode_name : itemToRecover.category }} • {{ itemToRecover.project_name }}
            </div>
          </div>

          <div class="text-sm text-muted-foreground">
            This action will restore the item and all its related data to active status. 
            This cannot be undone.
          </div>
        </div>

        <DialogFooter>
          <Button @click="showConfirmDialog = false" variant="outline">
            Cancel
          </Button>
          <Button 
            @click="executeRecovery" 
            :disabled="isRecovering"
          >
            <RotateCcw class="w-4 h-4 mr-1" />
            {{ isRecovering ? 'Recovering...' : 'Recover' }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- Bulk Recovery Confirmation Dialog -->
    <Dialog v-model:open="showBulkRecoveryDialog">
      <DialogContent class="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Bulk Recovery Confirmation</DialogTitle>
          <DialogDescription>
            Are you sure you want to recover {{ selectedItems.length }} selected items?
          </DialogDescription>
        </DialogHeader>

        <div class="space-y-4">
          <div class="p-4 bg-muted rounded-lg">
            <div class="font-semibold mb-2">Selected Items ({{ selectedItems.length }}):</div>
            <div class="max-h-40 overflow-y-auto space-y-1">
              <div 
                v-for="item in selectedItemsDetails" 
                :key="`${item.type}-${item.id}`"
                class="text-sm flex items-center justify-between"
              >
                <span>{{ item.name }}</span>
                <Badge variant="outline" size="sm">{{ item.type }}</Badge>
              </div>
            </div>
          </div>

          <div class="text-sm text-muted-foreground">
            This action will restore all selected items and their related data to active status. 
            This operation cannot be undone.
          </div>

          <div v-if="isBulkRecovering" class="flex items-center space-x-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
            <RefreshCw class="w-4 h-4 animate-spin text-blue-600" />
            <span class="text-sm text-blue-800">
              Processing bulk recovery... This may take a moment.
            </span>
          </div>
        </div>

        <DialogFooter>
          <Button @click="showBulkRecoveryDialog = false" variant="outline" :disabled="isBulkRecovering">
            Cancel
          </Button>
          <Button 
            @click="executeBulkRecovery" 
            :disabled="isBulkRecovering"
          >
            <RotateCcw class="w-4 h-4 mr-1" />
            {{ isBulkRecovering ? 'Recovering...' : `Recover ${selectedItems.length} Items` }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- Permanent Delete Confirmation Dialog -->
    <PermanentDeleteConfirmDialog
      v-model:open="showPermanentDeleteDialog"
      :items="itemsToDelete"
      :is-deleting="isPermanentDeleting"
      @confirm-delete="executePermanentDelete"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { 
  RefreshCw, 
  Film, 
  Package, 
  Database, 
  CheckSquare, 
  FileText, 
  Paperclip, 
  MessageSquare, 
  Eye, 
  RotateCcw, 
  Trash2,
  CheckCircle,
  ArrowUpDown
} from 'lucide-vue-next'
import { useToast } from '@/components/ui/toast/use-toast'
import { useProjectsStore } from '@/stores/projects'
import { recoveryService, type DeletedShot, type DeletedAsset, type RecoveryInfo } from '@/services/recovery'

// UI Components
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import PermanentDeleteConfirmDialog from '@/components/admin/PermanentDeleteConfirmDialog.vue'

// State
const isLoading = ref(false)
const isRecovering = ref(false)
const isBulkRecovering = ref(false)
const error = ref<string | null>(null)
const deletedShots = ref<DeletedShot[]>([])
const deletedAssets = ref<DeletedAsset[]>([])

// Filters
const selectedProjectId = ref<string>('all')
const selectedItemType = ref<string>('all')
const selectedDateRange = ref<string>('all')
const searchQuery = ref<string>('')
const sortBy = ref<string>('deleted_at')
const sortOrder = ref<'asc' | 'desc'>('desc')

// Selection state
const selectedItems = ref<Array<{ type: 'shot' | 'asset', id: number }>>([])

// Dialog state
const showPreviewDialog = ref(false)
const showConfirmDialog = ref(false)
const showBulkRecoveryDialog = ref(false)
const showPermanentDeleteDialog = ref(false)
const previewInfo = ref<RecoveryInfo | null>(null)
const itemToRecover = ref<DeletedShot | DeletedAsset | null>(null)
const recoveryType = ref<'shot' | 'asset'>('shot')
const isPermanentDeleting = ref(false)
const itemsToDelete = ref<Array<{
  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
}>>([])
const permanentDeleteType = ref<'single' | 'bulk'>('single')

// Stores
const projectsStore = useProjectsStore()
const { toast } = useToast()

// Computed
const availableProjects = computed(() => projectsStore.availableProjects)

const filteredShots = computed(() => {
  let shots = deletedShots.value

  // Filter by project
  if (selectedProjectId.value && selectedProjectId.value !== 'all') {
    const projectId = parseInt(selectedProjectId.value)
    shots = shots.filter(shot => shot.project_id === projectId)
  }

  // Filter by date range
  if (selectedDateRange.value !== 'all') {
    const now = new Date()
    const filterDate = new Date()
    
    switch (selectedDateRange.value) {
      case 'today':
        filterDate.setHours(0, 0, 0, 0)
        break
      case 'week':
        filterDate.setDate(now.getDate() - 7)
        break
      case 'month':
        filterDate.setMonth(now.getMonth() - 1)
        break
      case 'quarter':
        filterDate.setMonth(now.getMonth() - 3)
        break
    }
    
    shots = shots.filter(shot => new Date(shot.deleted_at) >= filterDate)
  }

  // Filter by search query
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    shots = shots.filter(shot => 
      shot.name.toLowerCase().includes(query) ||
      shot.episode_name.toLowerCase().includes(query) ||
      shot.project_name.toLowerCase().includes(query)
    )
  }

  return shots
})

const filteredAssets = computed(() => {
  let assets = deletedAssets.value

  // Filter by project
  if (selectedProjectId.value && selectedProjectId.value !== 'all') {
    const projectId = parseInt(selectedProjectId.value)
    assets = assets.filter(asset => asset.project_id === projectId)
  }

  // Filter by date range
  if (selectedDateRange.value !== 'all') {
    const now = new Date()
    const filterDate = new Date()
    
    switch (selectedDateRange.value) {
      case 'today':
        filterDate.setHours(0, 0, 0, 0)
        break
      case 'week':
        filterDate.setDate(now.getDate() - 7)
        break
      case 'month':
        filterDate.setMonth(now.getMonth() - 1)
        break
      case 'quarter':
        filterDate.setMonth(now.getMonth() - 3)
        break
    }
    
    assets = assets.filter(asset => new Date(asset.deleted_at) >= filterDate)
  }

  // Filter by search query
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    assets = assets.filter(asset => 
      asset.name.toLowerCase().includes(query) ||
      asset.category.toLowerCase().includes(query) ||
      asset.project_name.toLowerCase().includes(query)
    )
  }

  return assets
})

const sortedFilteredShots = computed(() => {
  const shots = [...filteredShots.value]
  
  shots.sort((a, b) => {
    let aValue: any, bValue: any
    
    switch (sortBy.value) {
      case 'name':
        aValue = a.name.toLowerCase()
        bValue = b.name.toLowerCase()
        break
      case 'deleted_at':
        aValue = new Date(a.deleted_at)
        bValue = new Date(b.deleted_at)
        break
      case 'project':
        aValue = a.project_name.toLowerCase()
        bValue = b.project_name.toLowerCase()
        break
      case 'type':
        aValue = 'shot'
        bValue = 'shot'
        break
      default:
        return 0
    }
    
    if (aValue < bValue) return sortOrder.value === 'asc' ? -1 : 1
    if (aValue > bValue) return sortOrder.value === 'asc' ? 1 : -1
    return 0
  })
  
  return shots
})

const sortedFilteredAssets = computed(() => {
  const assets = [...filteredAssets.value]
  
  assets.sort((a, b) => {
    let aValue: any, bValue: any
    
    switch (sortBy.value) {
      case 'name':
        aValue = a.name.toLowerCase()
        bValue = b.name.toLowerCase()
        break
      case 'deleted_at':
        aValue = new Date(a.deleted_at)
        bValue = new Date(b.deleted_at)
        break
      case 'project':
        aValue = a.project_name.toLowerCase()
        bValue = b.project_name.toLowerCase()
        break
      case 'type':
        aValue = 'asset'
        bValue = 'asset'
        break
      default:
        return 0
    }
    
    if (aValue < bValue) return sortOrder.value === 'asc' ? -1 : 1
    if (aValue > bValue) return sortOrder.value === 'asc' ? 1 : -1
    return 0
  })
  
  return assets
})

const shouldShowShots = computed(() => 
  selectedItemType.value === 'all' || selectedItemType.value === 'shots'
)

const shouldShowAssets = computed(() => 
  selectedItemType.value === 'all' || selectedItemType.value === 'assets'
)

const isAllSelected = computed(() => {
  const totalItems = filteredShots.value.length + filteredAssets.value.length
  return totalItems > 0 && selectedItems.value.length === totalItems
})

const selectedItemsDetails = computed(() => {
  return selectedItems.value.map(item => {
    if (item.type === 'shot') {
      const shot = deletedShots.value.find(s => s.id === item.id)
      return shot ? { ...shot, type: 'shot' as const } : null
    } else {
      const asset = deletedAssets.value.find(a => a.id === item.id)
      return asset ? { ...asset, type: 'asset' as const } : null
    }
  }).filter((item): item is NonNullable<typeof item> => item !== null)
})

// Methods
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const isItemSelected = (type: 'shot' | 'asset', id: number) => {
  return selectedItems.value.some(item => item.type === type && item.id === id)
}

const toggleItemSelection = (type: 'shot' | 'asset', id: number, checked: boolean) => {
  if (checked) {
    selectedItems.value.push({ type, id })
  } else {
    selectedItems.value = selectedItems.value.filter(item => !(item.type === type && item.id === id))
  }
}

const toggleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedItems.value = [
      ...filteredShots.value.map(shot => ({ type: 'shot' as const, id: shot.id })),
      ...filteredAssets.value.map(asset => ({ type: 'asset' as const, id: asset.id }))
    ]
  } else {
    selectedItems.value = []
  }
}

const loadDeletedItems = async () => {
  try {
    isLoading.value = true
    error.value = null

    const projectId = selectedProjectId.value && selectedProjectId.value !== 'all' ? parseInt(selectedProjectId.value) : undefined

    console.log('Loading recovery data with projectId:', projectId)

    const [shots, assets] = await Promise.all([
      recoveryService.getDeletedShots(projectId),
      recoveryService.getDeletedAssets(projectId)
    ])

    console.log('Loaded shots for recovery:', shots.length)
    console.log('Loaded assets for recovery:', assets.length)
    console.log('Shots data:', shots)

    deletedShots.value = shots
    deletedAssets.value = assets
    
    // Clear selections when data changes
    selectedItems.value = []
  } catch (err: any) {
    error.value = err.response?.data?.detail || 'Failed to load recovery data'
    console.error('Failed to load recovery data:', err)
    console.error('Error details:', err.response)
  } finally {
    isLoading.value = false
  }
}

const refreshData = () => {
  loadDeletedItems()
}

const previewShotRecovery = async (shot: DeletedShot) => {
  try {
    previewInfo.value = await recoveryService.previewShotRecovery(shot.id)
    recoveryType.value = 'shot'
    showPreviewDialog.value = true
  } catch (err: any) {
    toast({
      title: 'Error',
      description: err.response?.data?.detail || 'Failed to load recovery preview',
      variant: 'destructive'
    })
  }
}

const previewAssetRecovery = async (asset: DeletedAsset) => {
  try {
    previewInfo.value = await recoveryService.previewAssetRecovery(asset.id)
    recoveryType.value = 'asset'
    showPreviewDialog.value = true
  } catch (err: any) {
    toast({
      title: 'Error',
      description: err.response?.data?.detail || 'Failed to load recovery preview',
      variant: 'destructive'
    })
  }
}

const recoverShot = (shot: DeletedShot) => {
  itemToRecover.value = shot
  recoveryType.value = 'shot'
  showConfirmDialog.value = true
}

const recoverAsset = (asset: DeletedAsset) => {
  itemToRecover.value = asset
  recoveryType.value = 'asset'
  showConfirmDialog.value = true
}

const confirmRecovery = () => {
  showPreviewDialog.value = false
  if (previewInfo.value) {
    if (recoveryType.value === 'shot' && previewInfo.value.shot_id) {
      const shot = deletedShots.value.find(s => s.id === previewInfo.value!.shot_id)
      if (shot) {
        recoverShot(shot)
      }
    } else if (recoveryType.value === 'asset' && previewInfo.value.asset_id) {
      const asset = deletedAssets.value.find(a => a.id === previewInfo.value!.asset_id)
      if (asset) {
        recoverAsset(asset)
      }
    }
  }
}

const executeRecovery = async () => {
  if (!itemToRecover.value) return

  try {
    isRecovering.value = true

    let result
    if (recoveryType.value === 'shot') {
      result = await recoveryService.recoverShot(itemToRecover.value.id)
    } else {
      result = await recoveryService.recoverAsset(itemToRecover.value.id)
    }

    toast({
      title: 'Recovery Successful',
      description: `${result.name} and all related data have been recovered`,
    })

    // Remove from deleted lists and selections
    if (recoveryType.value === 'shot') {
      deletedShots.value = deletedShots.value.filter(s => s.id !== itemToRecover.value!.id)
      selectedItems.value = selectedItems.value.filter(item => !(item.type === 'shot' && item.id === itemToRecover.value!.id))
    } else {
      deletedAssets.value = deletedAssets.value.filter(a => a.id !== itemToRecover.value!.id)
      selectedItems.value = selectedItems.value.filter(item => !(item.type === 'asset' && item.id === itemToRecover.value!.id))
    }

    showConfirmDialog.value = false
    itemToRecover.value = null
  } catch (err: any) {
    toast({
      title: 'Recovery Failed',
      description: err.response?.data?.detail || 'Failed to recover item',
      variant: 'destructive'
    })
  } finally {
    isRecovering.value = false
  }
}

const executeBulkRecovery = async () => {
  if (selectedItems.value.length === 0) return

  try {
    isBulkRecovering.value = true

    const shotIds = selectedItems.value.filter(item => item.type === 'shot').map(item => item.id)
    const assetIds = selectedItems.value.filter(item => item.type === 'asset').map(item => item.id)

    const results = await Promise.allSettled([
      shotIds.length > 0 ? recoveryService.bulkRecoverShots(shotIds) : Promise.resolve(null),
      assetIds.length > 0 ? recoveryService.bulkRecoverAssets(assetIds) : Promise.resolve(null)
    ])

    let totalSuccessful = 0
    let totalFailed = 0
    const errors: string[] = []

    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value) {
        totalSuccessful += result.value.successful_recoveries
        totalFailed += result.value.failed_recoveries
        if (result.value.errors.length > 0) {
          errors.push(...result.value.errors.map(e => e.error))
        }
      } else if (result.status === 'rejected') {
        totalFailed += index === 0 ? shotIds.length : assetIds.length
        errors.push(result.reason?.message || 'Unknown error occurred')
      }
    })

    if (totalSuccessful > 0) {
      toast({
        title: 'Bulk Recovery Completed',
        description: `Successfully recovered ${totalSuccessful} items${totalFailed > 0 ? `, ${totalFailed} failed` : ''}`,
        variant: totalFailed > 0 ? 'destructive' : 'default'
      })

      // Remove successfully recovered items from lists and selections
      const recoveredItems = selectedItems.value.filter((_, index) => index < totalSuccessful)
      recoveredItems.forEach(item => {
        if (item.type === 'shot') {
          deletedShots.value = deletedShots.value.filter(s => s.id !== item.id)
        } else {
          deletedAssets.value = deletedAssets.value.filter(a => a.id !== item.id)
        }
      })
      
      selectedItems.value = []
    } else {
      toast({
        title: 'Bulk Recovery Failed',
        description: errors.length > 0 ? errors[0] : 'All recovery operations failed',
        variant: 'destructive'
      })
    }

    showBulkRecoveryDialog.value = false
  } catch (err: any) {
    toast({
      title: 'Bulk Recovery Failed',
      description: err.response?.data?.detail || 'Failed to perform bulk recovery',
      variant: 'destructive'
    })
  } finally {
    isBulkRecovering.value = false
  }
}

const handlePermanentDelete = (type: 'shot' | 'asset', item: DeletedShot | DeletedAsset) => {
  const deleteItem = {
    id: item.id,
    name: item.name,
    type,
    project_name: item.project_name,
    episode_name: 'episode_name' in item ? item.episode_name : undefined,
    task_count: item.task_count,
    submission_count: item.submission_count,
    attachment_count: item.attachment_count,
    note_count: item.note_count,
    review_count: item.review_count
  }
  
  itemsToDelete.value = [deleteItem]
  permanentDeleteType.value = 'single'
  showPermanentDeleteDialog.value = true
}

const handleBulkPermanentDelete = () => {
  const deleteItems = selectedItems.value.map(item => {
    if (item.type === 'shot') {
      const shot = deletedShots.value.find(s => s.id === item.id)
      return shot ? {
        id: shot.id,
        name: shot.name,
        type: 'shot' as const,
        project_name: shot.project_name,
        episode_name: shot.episode_name,
        task_count: shot.task_count,
        submission_count: shot.submission_count,
        attachment_count: shot.attachment_count,
        note_count: shot.note_count,
        review_count: shot.review_count
      } : null
    } else {
      const asset = deletedAssets.value.find(a => a.id === item.id)
      return asset ? {
        id: asset.id,
        name: asset.name,
        type: 'asset' as const,
        project_name: asset.project_name,
        task_count: asset.task_count,
        submission_count: asset.submission_count,
        attachment_count: asset.attachment_count,
        note_count: asset.note_count,
        review_count: asset.review_count
      } : null
    }
  }).filter((item): item is NonNullable<typeof item> => item !== null)
  
  itemsToDelete.value = deleteItems
  permanentDeleteType.value = 'bulk'
  showPermanentDeleteDialog.value = true
}

const executePermanentDelete = async (confirmationToken: string) => {
  if (itemsToDelete.value.length === 0) return

  try {
    isPermanentDeleting.value = true

    if (permanentDeleteType.value === 'single') {
      const item = itemsToDelete.value[0]
      let result
      
      if (item.type === 'shot') {
        // Call permanent delete API for shot
        result = await recoveryService.permanentDeleteShot(item.id, confirmationToken)
      } else {
        // Call permanent delete API for asset
        result = await recoveryService.permanentDeleteAsset(item.id, confirmationToken)
      }

      toast({
        title: 'Permanent Deletion Successful',
        description: `${result.name} and all related data have been permanently deleted`,
      })

      // Remove from lists and selections
      if (item.type === 'shot') {
        deletedShots.value = deletedShots.value.filter(s => s.id !== item.id)
        selectedItems.value = selectedItems.value.filter(selected => !(selected.type === 'shot' && selected.id === item.id))
      } else {
        deletedAssets.value = deletedAssets.value.filter(a => a.id !== item.id)
        selectedItems.value = selectedItems.value.filter(selected => !(selected.type === 'asset' && selected.id === item.id))
      }
    } else {
      // Bulk permanent delete - handle shots and assets separately
      const shotIds = itemsToDelete.value.filter(item => item.type === 'shot').map(item => item.id)
      const assetIds = itemsToDelete.value.filter(item => item.type === 'asset').map(item => item.id)

      // Generate appropriate confirmation tokens for each type
      const shotToken = shotIds.length > 0 ? 'CONFIRM_BULK_SHOTS_PERMANENT_DELETE' : null
      const assetToken = assetIds.length > 0 ? 'CONFIRM_BULK_ASSETS_PERMANENT_DELETE' : null

      const results = await Promise.allSettled([
        shotIds.length > 0 && shotToken ? recoveryService.bulkPermanentDeleteShots(shotIds, shotToken) : Promise.resolve(null),
        assetIds.length > 0 && assetToken ? recoveryService.bulkPermanentDeleteAssets(assetIds, assetToken) : Promise.resolve(null)
      ])

      let totalSuccessful = 0
      let totalFailed = 0
      const errors: string[] = []

      results.forEach((result, index) => {
        if (result.status === 'fulfilled' && result.value) {
          totalSuccessful += result.value.successful_deletions
          totalFailed += result.value.failed_deletions
          if (result.value.errors.length > 0) {
            errors.push(...result.value.errors.map(e => e.error))
          }
        } else if (result.status === 'rejected') {
          totalFailed += index === 0 ? shotIds.length : assetIds.length
          errors.push(result.reason?.message || 'Unknown error occurred')
        }
      })

      if (totalSuccessful > 0) {
        toast({
          title: 'Bulk Permanent Deletion Completed',
          description: `Successfully deleted ${totalSuccessful} items permanently${totalFailed > 0 ? `, ${totalFailed} failed` : ''}`,
          variant: totalFailed > 0 ? 'destructive' : 'default'
        })

        // Remove successfully deleted items from lists and selections
        itemsToDelete.value.forEach(item => {
          if (item.type === 'shot') {
            deletedShots.value = deletedShots.value.filter(s => s.id !== item.id)
          } else {
            deletedAssets.value = deletedAssets.value.filter(a => a.id !== item.id)
          }
        })
        
        selectedItems.value = []
      } else {
        toast({
          title: 'Bulk Permanent Deletion Failed',
          description: errors.length > 0 ? errors[0] : 'All deletion operations failed',
          variant: 'destructive'
        })
      }
    }

    showPermanentDeleteDialog.value = false
    itemsToDelete.value = []
  } catch (err: any) {
    toast({
      title: 'Permanent Deletion Failed',
      description: err.response?.data?.detail || 'Failed to permanently delete items',
      variant: 'destructive'
    })
  } finally {
    isPermanentDeleting.value = false
  }
}

// Watch for project filter changes to reload data
watch(selectedProjectId, () => {
  loadDeletedItems()
})

// Initialize
onMounted(async () => {
  await projectsStore.fetchProjects()
  await loadDeletedItems()
})
</script>