<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-2xl font-bold tracking-tight">Recovery Management</h2>
        <p class="text-muted-foreground">
          Manage and recover soft-deleted shots and assets
        </p>
      </div>
      <Button @click="refreshData" :disabled="isLoading" variant="outline">
        <RefreshCw :class="{ 'animate-spin': isLoading }" class="w-4 h-4 mr-2" />
        Refresh
      </Button>
    </div>

    <!-- Filters -->
    <Card>
      <CardHeader>
        <CardTitle>Filters</CardTitle>
      </CardHeader>
      <CardContent class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-3 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 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>

          <!-- 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>
      </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 -->
      <div class="grid grid-cols-1 md:grid-cols-3 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">Deleted Shots</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">Deleted Assets</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>
      </div>

      <!-- Deleted Shots -->
      <div v-if="shouldShowShots && filteredShots.length > 0">
        <h3 class="text-lg font-semibold mb-4 flex items-center">
          <Film class="w-5 h-5 mr-2" />
          Deleted Shots ({{ filteredShots.length }})
        </h3>
        <div class="grid gap-4">
          <Card v-for="shot in filteredShots" :key="`shot-${shot.id}`" class="hover:shadow-md transition-shadow">
            <CardContent class="p-6">
              <div class="flex items-start justify-between">
                <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">Deleted:</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>

                <div class="flex items-center space-x-2 ml-4">
                  <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>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      <!-- Deleted Assets -->
      <div v-if="shouldShowAssets && filteredAssets.length > 0">
        <h3 class="text-lg font-semibold mb-4 flex items-center">
          <Package class="w-5 h-5 mr-2" />
          Deleted Assets ({{ filteredAssets.length }})
        </h3>
        <div class="grid gap-4">
          <Card v-for="asset in filteredAssets" :key="`asset-${asset.id}`" class="hover:shadow-md transition-shadow">
            <CardContent class="p-6">
              <div class="flex items-start justify-between">
                <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">Deleted:</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>

                <div class="flex items-center space-x-2 ml-4">
                  <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>
                </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 ? 'Try adjusting your filters' : 'There are no items currently available for recovery' }}
        </p>
      </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">Deleted:</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>

    <!-- 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>
  </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
} 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'

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

// Filters
const selectedProjectId = ref<string>('')
const selectedItemType = ref<string>('all')
const searchQuery = ref<string>('')

// Dialog state
const showPreviewDialog = ref(false)
const showConfirmDialog = ref(false)
const previewInfo = ref<RecoveryInfo | null>(null)
const itemToRecover = ref<DeletedShot | DeletedAsset | null>(null)
const recoveryType = ref<'shot' | 'asset'>('shot')

// 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) {
    const projectId = parseInt(selectedProjectId.value)
    const selectedProject = projectsStore.getProjectById(projectId)
    if (selectedProject) {
      shots = shots.filter(shot => shot.project_name === selectedProject.name)
    }
  }

  // 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) {
    const projectId = parseInt(selectedProjectId.value)
    const selectedProject = projectsStore.getProjectById(projectId)
    if (selectedProject) {
      assets = assets.filter(asset => asset.project_name === selectedProject.name)
    }
  }

  // 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 shouldShowShots = computed(() => 
  selectedItemType.value === 'all' || selectedItemType.value === 'shots'
)

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

// 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 loadDeletedItems = async () => {
  try {
    isLoading.value = true
    error.value = null

    const projectId = selectedProjectId.value ? parseInt(selectedProjectId.value) : undefined

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

    deletedShots.value = shots
    deletedAssets.value = assets
  } catch (err: any) {
    error.value = err.response?.data?.detail || 'Failed to load recovery data'
    console.error('Failed to load recovery data:', err)
  } 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
    if (recoveryType.value === 'shot') {
      deletedShots.value = deletedShots.value.filter(s => s.id !== itemToRecover.value!.id)
    } else {
      deletedAssets.value = deletedAssets.value.filter(a => a.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
  }
}

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

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