<template>
  <q-page padding class="tag-selector-page">
    <div class="row justify-center">
      <div class="col-12 col-md-8 col-lg-6">
        <q-card>
          <q-card-section>
            <div class="text-h5">Select Tags</div>
            <div class="text-subtitle2 text-grey">Add tags to describe the mood and nature of this event</div>
          </q-card-section>

          <q-card-section>
            <!-- Search bar -->
            <q-input
              v-model="searchQuery"
              label="Search tags..."
              filled
              clearable
              class="q-mb-md"
            >
              <template v-slot:prepend>
                <q-icon name="search" />
              </template>
            </q-input>

            <!-- Tag categories -->
            <div class="tag-categories q-mb-md">
              <q-btn-toggle
                v-model="selectedTagCategory"
                :options="tagCategoryOptions"
                color="primary"
                unelevated
                class="full-width"
              />
            </div>

            <!-- Tag grid -->
            <div class="tag-grid">
              <div
                v-for="tag in filteredTags"
                :key="tag.id"
                class="tag-item"
                :class="{ 'selected': isTagSelected(tag.id) }"
                @click="toggleTagSelection(tag.id)"
              >
                <div class="tag-content">
                  <q-icon :name="tag.icon" size="20px" class="tag-icon" />
                  <span class="tag-label">{{ tag.label }}</span>
                  
                  <!-- Selection indicator -->
                  <q-icon
                    v-if="isTagSelected(tag.id)"
                    name="check_circle"
                    color="positive"
                    size="18px"
                    class="selection-indicator"
                  />
                </div>
              </div>
            </div>
          </q-card-section>

          <!-- Selected tags section -->
          <q-card-section v-if="selectedTags.length > 0" class="selected-section">
            <q-separator class="q-mb-md" />
            
            <div class="text-subtitle2 q-mb-md">Selected Tags ({{ selectedTags.length }})</div>
            
            <div class="selected-tags-container">
              <div class="selected-tags-list">
                <q-chip
                  v-for="tag in selectedTagsData"
                  :key="tag.id"
                  removable
                  @remove="removeTagSelection(tag.id)"
                  color="secondary"
                  text-color="white"
                  :icon="tag.icon"
                  class="selected-tag-chip"
                >
                  {{ tag.label }}
                </q-chip>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>

    <!-- Fixed Footer with Action Buttons -->
    <q-footer elevated class="bg-white text-dark selector-footer">
      <q-toolbar class="justify-between">
        <q-btn
          icon="arrow_back"
          color="grey"
          flat
          round
          @click="onCancel"
          class="q-ml-sm"
        >
          <q-tooltip class="bg-grey">Cancel</q-tooltip>
        </q-btn>
        
        <q-btn
          label="Add Tags"
          color="primary"
          unelevated
          :disable="selectedTags.length === 0"
          @click="onAddTags"
          class="q-mr-sm"
        />
      </q-toolbar>
    </q-footer>
  </q-page>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { tagOptions } from '../utils/editFormOptions.js'

export default {
  name: 'TagSelector',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // State
    const searchQuery = ref('')
    const selectedTags = ref([])
    const selectedTagCategory = ref('all')
    
    // Tag category options
    const tagCategoryOptions = [
      { label: 'All', value: 'all' },
      { label: 'Emotions', value: 'emotions' },
      { label: 'Significance', value: 'significance' },
      { label: 'Social', value: 'social' },
      { label: 'Intensity', value: 'intensity' },
      { label: 'Time', value: 'time' }
    ]
    
    // Tag categorization and icons
    const tagCategories = {
      'emotions': ['happy', 'sad', 'exciting', 'stressful', 'memorable', 'important', 'fun', 'challenging', 'rewarding', 'disappointing', 'surprising', 'life-changing', 'routine', 'special', 'difficult', 'joyful', 'overwhelming', 'peaceful', 'anxious', 'proud', 'grateful', 'emotional', 'touching', 'inspiring', 'motivating', 'healing'],
      'significance': ['milestone', 'achievement', 'breakthrough', 'turning-point', 'first-time', 'last-time', 'once-in-a-lifetime', 'unexpected', 'planned', 'spontaneous', 'tradition', 'new-experience'],
      'social': ['family', 'friends', 'colleagues', 'community', 'solo', 'group', 'intimate', 'public', 'private', 'celebration'],
      'intensity': ['intense', 'mild', 'dramatic', 'subtle', 'overwhelming', 'gradual', 'sudden', 'anticipated', 'shocking', 'gentle'],
      'time': ['brief', 'extended', 'momentary', 'lasting', 'temporary', 'permanent', 'seasonal', 'annual', 'weekly', 'daily']
    }
    
    const tagIcons = {
      // Emotions
      'happy': 'sentiment_very_satisfied',
      'sad': 'sentiment_very_dissatisfied',
      'exciting': 'bolt',
      'stressful': 'stress_management',
      'memorable': 'star',
      'important': 'priority_high',
      'fun': 'sports_esports',
      'challenging': 'fitness_center',
      'rewarding': 'emoji_events',
      'disappointing': 'thumb_down',
      'surprising': 'surprise',
      'life-changing': 'transform',
      'routine': 'repeat',
      'special': 'auto_awesome',
      'difficult': 'warning',
      'joyful': 'celebration',
      'overwhelming': 'waves',
      'peaceful': 'spa',
      'anxious': 'psychology',
      'proud': 'military_tech',
      'grateful': 'volunteer_activism',
      'emotional': 'favorite',
      'touching': 'touch_app',
      'inspiring': 'lightbulb',
      'motivating': 'trending_up',
      'healing': 'healing',
      
      // Significance
      'milestone': 'flag',
      'achievement': 'workspace_premium',
      'breakthrough': 'psychology_alt',
      'turning-point': 'turn_right',
      'first-time': 'new_releases',
      'last-time': 'last_page',
      'once-in-a-lifetime': 'diamond',
      'unexpected': 'help_outline',
      'planned': 'event_note',
      'spontaneous': 'flash_on',
      'tradition': 'history',
      'new-experience': 'explore',
      
      // Social
      'family': 'family_restroom',
      'friends': 'group',
      'colleagues': 'business',
      'community': 'diversity_3',
      'solo': 'person',
      'group': 'groups',
      'intimate': 'favorite_border',
      'public': 'public',
      'private': 'lock',
      'celebration': 'cake',
      
      // Default for others
      'default': 'tag'
    }
    
    // Convert tag options to objects with categories and icons
    const tags = ref(
      tagOptions.map((tag, index) => {
        // Find which category this tag belongs to
        let category = 'other'
        for (const [cat, tagList] of Object.entries(tagCategories)) {
          if (tagList.includes(tag)) {
            category = cat
            break
          }
        }
        
        return {
          id: index + 1,
          label: tag,
          value: tag,
          category: category,
          icon: tagIcons[tag] || tagIcons['default']
        }
      })
    )
    
    // Computed
    const filteredTags = computed(() => {
      let filtered = tags.value
      
      // Filter by category
      if (selectedTagCategory.value !== 'all') {
        filtered = filtered.filter(tag => tag.category === selectedTagCategory.value)
      }
      
      // Filter by search query
      if (searchQuery.value) {
        filtered = filtered.filter(tag =>
          tag.label.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      return filtered
    })
    
    const selectedTagsData = computed(() => {
      return tags.value.filter(tag => selectedTags.value.includes(tag.id))
    })
    
    // Methods
    const isTagSelected = (tagId) => {
      return selectedTags.value.includes(tagId)
    }
    
    const toggleTagSelection = (tagId) => {
      const index = selectedTags.value.indexOf(tagId)
      if (index > -1) {
        selectedTags.value.splice(index, 1)
      } else {
        selectedTags.value.push(tagId)
      }
    }
    
    const removeTagSelection = (tagId) => {
      const index = selectedTags.value.indexOf(tagId)
      if (index > -1) {
        selectedTags.value.splice(index, 1)
      }
    }
    
    const onCancel = () => {
      router.go(-1)
    }
    
    const onAddTags = () => {
      // Pass selected tags back to the edit page
      const selectedTagsLabels = selectedTagsData.value.map(tag => tag.label)
      
      // Navigate back with the selected tags data
      router.push({
        name: 'edit',
        query: {
          ...route.query,
          selectedTags: JSON.stringify(selectedTagsLabels)
        }
      })
    }
    
    // Load previously selected tags from route query
    onMounted(() => {
      if (route.query.currentSelection) {
        try {
          const currentSelection = JSON.parse(route.query.currentSelection)
          // Convert labels back to IDs
          selectedTags.value = tags.value
            .filter(tag => currentSelection.includes(tag.label))
            .map(tag => tag.id)
        } catch (error) {
          console.error('Error parsing current selection:', error)
        }
      }
    })
    
    return {
      searchQuery,
      selectedTags,
      selectedTagCategory,
      tagCategoryOptions,
      tags,
      filteredTags,
      selectedTagsData,
      isTagSelected,
      toggleTagSelection,
      removeTagSelection,
      onCancel,
      onAddTags
    }
  }
}
</script>

<style scoped>
.tag-selector-page {
  min-height: 100vh;
  padding-bottom: 80px; /* Space for footer */
}

.tag-categories {
  margin-bottom: 16px;
}

.tag-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 8px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.tag-item {
  position: relative;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 2px solid rgba(0, 0, 0, 0.1);
  background: rgba(0, 0, 0, 0.02);
  min-height: 44px;
}

.tag-item:hover {
  background-color: rgba(25, 118, 210, 0.1);
  border-color: rgba(25, 118, 210, 0.3);
  transform: translateY(-1px);
}

.tag-item.selected {
  background-color: rgba(25, 118, 210, 0.15);
  border-color: var(--q-primary);
}

.tag-content {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  gap: 8px;
}

.tag-icon {
  flex-shrink: 0;
  color: var(--q-primary);
}

.tag-label {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  text-transform: capitalize;
}

.selection-indicator {
  flex-shrink: 0;
}

.selected-section {
  background-color: rgba(0, 0, 0, 0.02);
}

.selected-tags-container {
  max-height: 200px;
  overflow-y: auto;
}

.selected-tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag-chip {
  font-size: 13px;
  min-height: 32px;
}

/* Responsive design */
@media (max-width: 600px) {
  .tag-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 6px;
  }
  
  .tag-content {
    padding: 6px 10px;
    gap: 6px;
  }
  
  .tag-label {
    font-size: 13px;
  }
  
  .selected-tags-list {
    gap: 6px;
  }
}

/* Footer styling */
.selector-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  border-top: 1px solid #e0e0e0;
}

.selector-footer .q-toolbar {
  min-height: 60px;
  padding: 8px 16px;
}
</style>