<template>
  <div class="flex items-center gap-4">
    <!-- Current Avatar Display with Upload Button -->
    <div class="relative group">
      <div
        class="w-24 h-24 rounded-full overflow-hidden bg-muted flex items-center justify-center border-2 border-border"
      >
        <img
          v-if="currentAvatarUrl"
          :src="getAvatarUrl(currentAvatarUrl, firstName, lastName)"
          alt="Avatar"
          class="w-full h-full object-cover"
        />
        <div
          v-else
          class="text-3xl font-semibold text-muted-foreground"
        >
          {{ initials }}
        </div>
      </div>
      
      <!-- Upload Button Overlay -->
      <Button
        variant="secondary"
        size="icon"
        class="absolute bottom-0 right-0 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>

    <!-- Avatar Actions -->
    <div class="flex-1 space-y-2">
      <div class="flex items-center gap-2">
        <Button
          variant="outline"
          size="sm"
          @click="triggerFileInput"
          :disabled="isUploading"
        >
          <Upload class="h-4 w-4 mr-2" />
          Change Avatar
        </Button>
        
        <Button
          v-if="currentAvatarUrl"
          variant="outline"
          size="sm"
          @click="handleRemoveAvatar"
          :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 5MB)
      </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...</span>
      </div>
      
      <!-- Error Message -->
      <p v-if="errorMessage" class="text-xs text-destructive">
        {{ errorMessage }}
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Button } from '@/components/ui/button'
import { Upload, X, Loader2, Camera } from 'lucide-vue-next'
import { useToast } from '@/components/ui/toast/use-toast'
import { userService } from '@/services/user'
import { useAuthStore } from '@/stores/auth'
import { useAvatarUrl } from '@/composables/useAvatarUrl'


interface Props {
  currentAvatarUrl?: string | null
  firstName?: string
  lastName?: string
}

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

const { toast } = useToast()
const authStore = useAuthStore()

const fileInput = ref<HTMLInputElement>()
const isUploading = ref(false)
const isRemoving = ref(false)
const errorMessage = ref('')

const initials = computed(() => {
  const first = props.firstName?.charAt(0) || ''
  const last = props.lastName?.charAt(0) || ''
  return (first + last).toUpperCase() || '?'
})

const { getAvatarUrl } = useAvatarUrl()

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 (5MB max)
  const maxSize = 5 * 1024 * 1024 // 5MB in bytes
  if (file.size > maxSize) {
    errorMessage.value = 'File too large. Maximum size is 5MB.'
    return false
  }

  return true
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  if (!validateFile(file)) {
    toast({
      title: 'Invalid File',
      description: errorMessage.value,
      variant: 'destructive',
    })
    return
  }

  // Upload immediately after selection
  isUploading.value = true
  errorMessage.value = ''

  try {
    const response = await userService.uploadAvatar(file)
    
    // Update auth store with new avatar URL
    if (authStore.user) {
      authStore.user.avatar_url = response.avatar_url
    }

    emit('avatar-updated')
    
    toast({
      title: 'Success',
      description: 'Avatar uploaded successfully',
    })
    
  } catch (error: any) {
    errorMessage.value = error.response?.data?.detail || 'Failed to upload avatar'
    toast({
      title: 'Error',
      description: errorMessage.value,
      variant: 'destructive',
    })
  } finally {
    isUploading.value = false
    // Reset file input
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

const handleRemoveAvatar = async () => {
  if (!confirm('Are you sure you want to remove your avatar?')) {
    return
  }

  isRemoving.value = true
  errorMessage.value = ''

  try {
    await userService.removeAvatar()
    
    // Update auth store
    if (authStore.user) {
      authStore.user.avatar_url = null
    }

    emit('avatar-removed')
    
    toast({
      title: 'Success',
      description: 'Avatar removed successfully',
    })
  } catch (error: any) {
    errorMessage.value = error.response?.data?.detail || 'Failed to remove avatar'
    toast({
      title: 'Error',
      description: errorMessage.value,
      variant: 'destructive',
    })
  } finally {
    isRemoving.value = false
  }
}
</script>
