<script setup lang="ts">
import { ref, onMounted } from 'vue';

const props = defineProps<{
  modelValue: string[],
  availableTags?: string[],
  readonly?: boolean,
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', tags: string[]): void;
}>();

const allTags = ref<string[]>([]);

onMounted(async () => {
  if (props.availableTags && props.availableTags.length > 0) {
    allTags.value = [...props.availableTags];
  } else {
    try {
      const backendUrl = import.meta.env.VITE_BACKEND_URL;
      const response = await fetch(`${backendUrl}/questions/tags`);
      
      if (response.ok) {
        allTags.value = await response.json();
      } else {
        console.error('Failed to fetch tags');
        allTags.value = ['actor', 'athlete', 'video game', 'movie', 'animation', 'place', 'series', 'flag', 'animal'];
      }
    } catch (error) {
      console.error('Error fetching tags:', error);
      allTags.value = ['actor', 'athlete', 'video game', 'movie', 'animation', 'place', 'series', 'flag', 'animal'];
    }
  }
});

const addTag = (tag: string) => {
  if (props.readonly) return;
  
  if (!isSelected(tag)) {
    const newTags = [...props.modelValue, tag];
    emit('update:modelValue', newTags);
  }
};

const removeTag = (tag: string) => {
  if (props.readonly) return;
  
  const newTags = props.modelValue.filter(t => t !== tag);
  emit('update:modelValue', newTags);
};

function isSelected(tag: string): boolean {
  return props.modelValue.includes(tag);
}

function getSuggestedTags(): string[] {
  return allTags.value.filter(tag => !props.modelValue.includes(tag));
}

const tagColors = [
  'bg-blue-600/30 text-blue-300 border border-blue-500/50 hover:bg-blue-600/40',
  'bg-green-600/30 text-green-300 border border-green-500/50 hover:bg-green-600/40',
  'bg-purple-600/30 text-purple-300 border border-purple-500/50 hover:bg-purple-600/40',
  'bg-pink-600/30 text-pink-300 border border-pink-500/50 hover:bg-pink-600/40',
  'bg-yellow-600/30 text-yellow-300 border border-yellow-500/50 hover:bg-yellow-600/40',
  'bg-teal-600/30 text-teal-300 border border-teal-500/50 hover:bg-teal-600/40',
  'bg-indigo-600/30 text-indigo-300 border border-indigo-500/50 hover:bg-indigo-600/40',
  'bg-red-600/30 text-red-300 border border-red-500/50 hover:bg-red-600/40',
  'bg-orange-600/30 text-orange-300 border border-orange-500/50 hover:bg-orange-600/40',
  'bg-sky-600/30 text-sky-300 border border-sky-500/50 hover:bg-sky-600/40',
];

function getTagColorClass(tag: string, isAvailableTag: boolean = false): string {
  const hash = tag.split('').reduce((acc, char) => {
    return acc + char.charCodeAt(0);
  }, 0);
  
  const colorClass = tagColors[hash % tagColors.length];  
  if (isAvailableTag) {
    return colorClass.replace('/30', '/20').replace('/50', '/30');
  }
  
  return colorClass;
}
</script>

<template>
  <transition-group 
    name="tag-animation" 
    tag="div" 
    class="flex flex-wrap gap-2 mb-4"
  >
    <button
      v-for="tag in modelValue" 
      :key="tag" 
      type="button"
      :class="[
        getTagColorClass(tag),
        readonly ? 'cursor-default' : 'cursor-pointer'
      ]"
      class="inline-flex items-center px-4 py-1 rounded-full text-base font-medium bg-gray-700 border-blue-500/30 shadow-sm hover:bg-blue-600 hover:border-blue-400 transition-all"
      :disabled="readonly"
      @click="removeTag(tag)"
    >
      {{ tag }}
    </button>
    <p 
      v-if="modelValue.length === 0" 
      class="text-gray-400 italic text-sm mt-2 px-2"
    >
      All tags are used
    </p>
  </transition-group>

  <div
    v-if="!readonly"
    class="mt-8"
  >
    <transition-group
      name="tag-animation" 
      tag="div"
      class="flex flex-wrap gap-2"
    >
      <button
        v-for="tag in getSuggestedTags()"
        :key="`tag-${tag}`"
        type="button"
        class="inline-flex items-center px-4 py-1 rounded-full text-base font-medium bg-gray-700 shadow-sm hover:bg-blue-600 hover:border-blue-400 cursor-pointer"
        @click="addTag(tag)"
      >
        {{ tag }}
      </button>
    </transition-group>
  </div>
</template>

<style scoped>
/* Custom bounce animation that works with Vue's transition-group */
.tag-animation-enter-active {
  animation: tag-bounce-in 0.5s;
}

.tag-animation-leave-active {
  transition: all 0.2s;
  position: absolute;
}

.tag-animation-leave-to {
  opacity: 0;
  transform: scale(0.6);
}

.tag-animation-move {
  transition: transform 0.2s;
}

@keyframes tag-bounce-in {
  0% {
    transform: scale(0.6);
    opacity: 0;
  }
  50% {
    transform: scale(1.1);
    opacity: 1;
  }
  70% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1);
  }
}
</style>