<template>
  <Card class="overflow-hidden hover:shadow-md transition-shadow">
    <div class="aspect-video bg-muted flex items-center justify-center relative group">
      <!-- Image Preview -->
      <img
        v-if="thumbnailBlobUrl && !imageError"
        :src="thumbnailBlobUrl"
        :alt="attachment.file_name"
        class="w-full h-full object-cover cursor-pointer"
        @click="emit('view', attachment)"
        @error="imageError = true"
      />
      
      <!-- File Icon -->
      <div v-else class="flex flex-col items-center gap-2">
        <FileIcon class="h-12 w-12 text-muted-foreground" />
        <span class="text-xs text-muted-foreground">{{ getFileExtension(attachment.file_name) }}</span>
      </div>

      <!-- Overlay Actions -->
      <div class="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
        <Button
          size="icon"
          variant="secondary"
          @click="handleDownload"
        >
          <Download class="h-4 w-4" />
        </Button>
        <Button
          v-if="attachment.thumbnail_url"
          size="icon"
          variant="secondary"
          @click="emit('view', attachment)"
        >
          <Eye class="h-4 w-4" />
        </Button>
        <Button
          size="icon"
          variant="destructive"
          @click="emit('delete', attachment.id)"
        >
          <Trash2 class="h-4 w-4" />
        </Button>
      </div>
    </div>

    <CardContent class="p-3">
      <div class="space-y-1">
        <p class="text-sm font-medium truncate" :title="attachment.file_name">
          {{ attachment.file_name }}
        </p>
        <div class="flex items-center justify-between gap-2">
          <Badge variant="secondary" class="text-xs">
            {{ formatAttachmentType(attachment.attachment_type) }}
          </Badge>
          <div class="flex items-center gap-2 text-xs text-muted-foreground">
            <span>{{ formatFileSize(attachment.file_size) }}</span>
            <span>{{ formatDate(attachment.uploaded_at) }}</span>
          </div>
        </div>
        <p v-if="attachment.description" class="text-xs text-muted-foreground line-clamp-2">
          {{ attachment.description }}
        </p>
        <div class="flex items-center gap-2 text-xs text-muted-foreground">
          <Avatar class="h-4 w-4">
            <AvatarImage
              :src="getInitialsAvatarUrl(attachment.user_first_name, attachment.user_last_name)"
            />
            <AvatarFallback class="text-[8px]">{{ getUserInitials(attachment.user_first_name, attachment.user_last_name) }}</AvatarFallback>
          </Avatar>
          <span>By {{ attachment.user_first_name }} {{ attachment.user_last_name }}</span>
        </div>
      </div>
    </CardContent>
  </Card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { FileIcon, Download, Eye, Trash2 } from 'lucide-vue-next'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import type { TaskAttachment } from '@/services/task'
import { apiClient } from '@/services/api'
import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getInitialsAvatarUrl } = useAvatarUrl()

const props = defineProps<{
  attachment: TaskAttachment
}>()

const emit = defineEmits<{
  delete: [id: number]
  view: [attachment: TaskAttachment]
}>()

const imageError = ref(false)
const thumbnailBlobUrl = ref<string | null>(null)

function getFileExtension(filename: string): string {
  const parts = filename.split('.')
  return parts.length > 1 ? parts[parts.length - 1].toUpperCase() : 'FILE'
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}

function formatAttachmentType(type: string): string {
  return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

function handleDownload() {
  if (props.attachment.download_url) {
    const url = props.attachment.download_url.startsWith('http') 
      ? props.attachment.download_url 
      : `http://localhost:8000${props.attachment.download_url}`
    window.open(url, '_blank')
  }
}

function getUserInitials(firstName: string, lastName: string) {
  return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase()
}

async function loadThumbnail() {
  if (!props.attachment.thumbnail_url) return
  
  try {
    const response = await apiClient.get(props.attachment.thumbnail_url, {
      responseType: 'blob'
    })
    thumbnailBlobUrl.value = URL.createObjectURL(response.data)
  } catch (error) {
    console.error('Failed to load thumbnail:', error)
    imageError.value = true
  }
}

onMounted(() => {
  if (props.attachment.thumbnail_url) {
    loadThumbnail()
  }
})

onUnmounted(() => {
  // Clean up blob URL to prevent memory leaks
  if (thumbnailBlobUrl.value) {
    URL.revokeObjectURL(thumbnailBlobUrl.value)
  }
})
</script>
