<template>
  <div class="space-y-4">
    <div class="flex items-start gap-6">
      <!-- Current Thumbnail Display -->
      <div class="relative group">
        <div
          class="w-48 h-32 rounded-lg overflow-hidden bg-muted flex items-center justify-center border-2 border-border"
        >
          <img
            v-if="thumbnailBlobUrl"
            :src="getThumbnailUrl()"
            alt="Project Thumbnail"
            class="w-full h-full object-cover"
          />
          <div
            v-else
            class="flex flex-col items-center justify-center text-center p-4"
          >
            <ImageIcon class="h-12 w-12 text-muted-foreground mb-2" />
            <span class="text-sm text-muted-foreground">{{ projectInitials }}</span>
          </div>
        </div>
        
        <!-- Upload Button Overlay -->
        <Button
          v-if="!currentThumbnailUrl"
          variant="secondary"
          size="icon"
          class="absolute bottom-2 right-2 h-8 w-8 rounded-full shadow-md"
          @click="triggerFileInput"
          :disabled="isUploading"
        >
          <Camera class="h-4 w-4" />
        </Button>
        
        <!-- Hidden File Input -->
        <input
          ref="fileInput"
          type="file"
          accept=".jpg,.jpeg,.png,.gif,.webp"
          class="hidden"
          @change="handleFileSelect"
        />
      </div>

      <!-- Thumbnail Actions -->
      <div class="flex-1 space-y-3">
        <div>
          <h3 class="text-sm font-medium mb-1">Project Thumbnail</h3>
          <p class="text-xs text-muted-foreground">
            Upload a custom image to identify this project
          </p>
        </div>
        
        <div class="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            @click="triggerFileInput"
            :disabled="isUploading"
          >
            <Upload class="h-4 w-4 mr-2" />
            {{ currentThumbnailUrl ? 'Replace' : 'Upload' }} Thumbnail
          </Button>
          
          <Button
            v-if="currentThumbnailUrl"
            variant="outline"
            size="sm"
            @click="handleRemoveThumbnail"
            :disabled="isRemoving || isUploading"
          >
            <X class="h-4 w-4 mr-2" />
            Remove
          </Button>
        </div>
        
        <p class="text-xs text-muted-foreground">
          JPG, PNG, GIF or WEBP (max 10MB)
        </p>
        
        <!-- Upload Progress -->
        <div v-if="isUploading" class="flex items-center gap-2">
          <Loader2 class="h-4 w-4 animate-spin" />
          <span class="text-xs">Uploading and processing...</span>
        </div>
        
        <!-- Error Message -->
        <p v-if="errorMessage" class="text-xs text-destructive">
          {{ errorMessage }}
        </p>
      </div>
    </div>

    <!-- Drag and Drop Area (when no thumbnail) -->
    <div
      v-if="!currentThumbnailUrl"
      class="border-2 border-dashed rounded-lg p-8 text-center transition-colors"
      :class="{
        'border-primary bg-primary/5': isDragging,
        'border-border hover:border-primary/50': !isDragging
      }"
      @dragover.prevent="isDragging = true"
      @dragleave.prevent="isDragging = false"
      @drop.prevent="handleDrop"
    >
      <ImageIcon class="h-10 w-10 mx-auto text-muted-foreground mb-3" />
      <p class="text-sm font-medium mb-1">
        Drag and drop your thumbnail here
      </p>
      <p class="text-xs text-muted-foreground mb-3">
        or click the button above to browse
      </p>
      <p class="text-xs text-muted-foreground">
        Recommended: 800x600px or similar aspect ratio
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { Button } from '@/components/ui/button'
import { Upload, X, Loader2, Camera, ImageIcon } from 'lucide-vue-next'
import { useToast } from '@/components/ui/toast/use-toast'
import { projectService } from '@/services/project'
import { apiClient } from '@/services/api'

interface Props {
  projectId: number
  currentThumbnailUrl?: string | null
  projectName?: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'thumbnail-updated', thumbnailUrl: string): void
  (e: 'thumbnail-removed'): void
}>()

const { toast } = useToast()

const fileInput = ref<HTMLInputElement>()
const isUploading = ref(false)
const isRemoving = ref(false)
const errorMessage = ref('')
const isDragging = ref(false)
const thumbnailBlobUrl = ref<string | null>(null)

const projectInitials = computed(() => {
  if (!props.projectName) return '?'
  const words = props.projectName.split(' ')
  if (words.length >= 2) {
    return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase()
  }
  return props.projectName.substring(0, 2).toUpperCase()
})

const getThumbnailUrl = () => {
  return thumbnailBlobUrl.value || ''
}

async function loadThumbnail() {
  if (!props.currentThumbnailUrl) {
    thumbnailBlobUrl.value = null
    return
  }

  try {
    const response = await apiClient.get(props.currentThumbnailUrl, {
      responseType: 'blob'
    })
    
    // Revoke old blob URL if it exists
    if (thumbnailBlobUrl.value) {
      URL.revokeObjectURL(thumbnailBlobUrl.value)
    }
    
    // Create new blob URL
    thumbnailBlobUrl.value = URL.createObjectURL(response.data)
  } catch (error) {
    console.error('Failed to load thumbnail:', error)
    thumbnailBlobUrl.value = null
  }
}

const triggerFileInput = () => {
  fileInput.value?.click()
}

const validateFile = (file: File): boolean => {
  errorMessage.value = ''

  // Check file type
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    errorMessage.value = 'Invalid file format. Please upload JPG, PNG, GIF, or WEBP.'
    return false
  }

  // Check file size (10MB max)
  const maxSize = 10 * 1024 * 1024 // 10MB in bytes
  if (file.size > maxSize) {
    errorMessage.value = 'File too large. Maximum size is 10MB.'
    return false
  }

  return true
}

const uploadFile = async (file: File) => {
  if (!validateFile(file)) {
    toast({
      title: 'Invalid File',
      description: errorMessage.value,
      variant: 'destructive',
    })
    return
  }

  isUploading.value = true
  errorMessage.value = ''

  try {
    const response = await projectService.uploadThumbnail(props.projectId, file)
    
    emit('thumbnail-updated', response.thumbnail_url)
    
    toast({
      title: 'Success',
      description: 'Thumbnail uploaded successfully',
    })
    
  } catch (error: any) {
    errorMessage.value = error.response?.data?.detail || 'Failed to upload thumbnail'
    toast({
      title: 'Error',
      description: errorMessage.value,
      variant: 'destructive',
    })
  } finally {
    isUploading.value = false
    // Reset file input
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  await uploadFile(file)
}

const handleDrop = async (event: DragEvent) => {
  isDragging.value = false
  
  const file = event.dataTransfer?.files[0]
  if (!file) return
  
  await uploadFile(file)
}

const handleRemoveThumbnail = async () => {
  if (!confirm('Are you sure you want to remove the project thumbnail?')) {
    return
  }

  isRemoving.value = true
  errorMessage.value = ''

  try {
    await projectService.deleteThumbnail(props.projectId)
    
    emit('thumbnail-removed')
    
    toast({
      title: 'Success',
      description: 'Thumbnail removed successfully',
    })
  } catch (error: any) {
    errorMessage.value = error.response?.data?.detail || 'Failed to remove thumbnail'
    toast({
      title: 'Error',
      description: errorMessage.value,
      variant: 'destructive',
    })
  } finally {
    isRemoving.value = false
  }
}

onMounted(() => {
  loadThumbnail()
})

watch(() => props.currentThumbnailUrl, () => {
  loadThumbnail()
})

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