<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import SearchIcon from 'pixelarticons/svg/search.svg'
import PlusIcon from 'pixelarticons/svg/plus.svg'
import NoteSearchResult from './SearchResult.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';
import { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry';
import { useCampaignService } from '~/services/Campaign.js';

const { Campaign } = useCampaignService();

const inputText = ref('');
const notes = ref([]);

const showResults = ref(false);
const selectedIndex = ref(-1);

const focusInput = ref(null);

// ---- Keyboard shortcut to open search ----
function globalKeydown(e) {
  const modKey = e.metaKey || e.ctrlKey;
  if ((modKey && e.key === 'k') || (e.key === '/' && !isInputFocused())) {
    e.preventDefault();
    focusInput.value?.focus();
  }
  if (e.key === 'Escape' && showResults.value) {
    closeResults();
  }
}

function isInputFocused() {
  const tag = document.activeElement?.tagName.toLowerCase();
  return tag === 'input' || tag === 'textarea' || document.activeElement?.isContentEditable;
}

// ---- Registration of create-note action (extensibile for future commands) ----
function registerCreateNoteAction() {
  const action = {
    id: 'create_note',
    label: 'New note',
    description: 'Create a new note in the current campaign',
    execute: async () => {
      if (!Campaign.value) return;
      const campaignId = Campaign.value?._id ?? Campaign.value?.id;
      try {
        const response = await Server().post('/note/create', {
          title: 'New note',
          content: '',
          campaign: campaignId
        });
        if (response.data.status !== 'ok') return;
        emitter.emit('note-created', response.data.note);
      } catch (err) {
        console.error('[ActionRegistry] Failed to create note:', err);
      }
    }
  };
  register(action);
}

// ---- Note search ----
async function fetchNotes() {
  if (!Campaign.value) return;
  
  const campaignId = Campaign.value?._id ?? Campaign.value?.id;
  try {
    const response = await Server().get('/note/list', { params: { campaign: campaignId } });
    if (response.data.status !== 'ok') {
      notes.value = [];
      return;
    }
    notes.value = response.data.notes.map(n => ({
      key: n._id,
      title: n.title || 'Untitled',
      date: n.date
    }));
  } catch (err) {
    notes.value = [];
  }
}

function openNote(note) {
  emitter.emit('push-note', note);
  closeResults();
}

// ---- Unified results: notes + command actions ----
function getCombinedResults(query) {
  const combined = [];

  if (query && query.trim().length > 0) {
    const q = query.normalize("NFD").replace(/[\u036f]/g, "").toLowerCase().trim();

    // Filter notes that match the query text
    const matchingNotes = notes.value.filter(note => {
      const title = (note.title || '').normalize("NFD").replace(/[\u036f]/g, "").toLowerCase();
      return title.includes(q);
    });

    for (const note of matchingNotes) {
      combined.push({ type: 'note', data: note });
    }

    // Search command actions
    const matchedActions = searchActions(query);
    for (const action of matchedActions) {
      combined.push({ type: 'action', data: action });
    }
  } else if (query === '' || query === null) {
    // Empty query - show all notes + all actions
    for (const note of notes.value) {
      combined.push({ type: 'note', data: note });
    }
    const allActions = searchActions('');
    for (const action of allActions) {
      combined.push({ type: 'action', data: action });
    }
  }

  return combined;
}

// ---- Input handling ----
function onInput(event) {
  const query = event.target.value;
  inputText.value = query;
  selectedIndex.value = -1;

  if (!query || query.trim() === '') {
    showResults.value = false;
    return;
  }

  showResults.value = true;
}

function onFocus() {
  if (notes.value.length === 0) {
    fetchNotes().then(() => {
      showResults.value = true;
    });
  } else {
    showResults.value = true;
  }
}

function onBlur(event) {
  // Delay closing to allow click on results
  setTimeout(() => {
    closeResults();
  }, 150);
}

async function onKeydown(event) {
  const combined = getCombinedResults(inputText.value);

  if (event.key === 'ArrowDown') {
    event.preventDefault();
    selectedIndex.value = Math.min(selectedIndex.value + 1, combined.length - 1);
    return;
  }

  if (event.key === 'ArrowUp') {
    event.preventDefault();
    selectedIndex.value = Math.max(selectedIndex.value - 1, 0);
    return;
  }

  if (event.key === 'Enter') {
    event.preventDefault();
    if (selectedIndex.value >= 0) {
      const item = combined[selectedIndex.value];
      if (!item) return;

      if (item.type === 'note') {
        openNote(item.data);
      } else if (item.type === 'action') {
        executeAction(item.data.id);
        closeResults();
      }
    }
  }

  if (event.key === 'Escape') {
    closeResults();
  }
}

function onSelect(result) {
  if (!result) return;

  if (result.link) {
    const note = notes.value.find(n => n.key === result.link);
    if (note) openNote(note);
  }
  closeResults();
}

function handleActionSelect(actionData) {
  executeAction(actionData.id);
  closeResults();
}

function closeResults() {
  showResults.value = false;
  selectedIndex.value = -1;
  inputText.value = '';
}

// ---- Clean up register action on mount/unmount ----
onMounted(() => {
  document.addEventListener('keydown', globalKeydown);
  registerCreateNoteAction();
});

onUnmounted(() => {
  document.removeEventListener('keydown', globalKeydown);
});
</script>

<template>
  <div class="top-search-container">
    <div class="top-search-box">
      <img class="icon search-icon" :src="SearchIcon" alt="" aria-hidden="true">
      <input
        ref="focusInput"
        type="text"
        class="search-prompt"
        placeholder="Search or press Cmd+K..."
        v-model="inputText"
        @input="onInput"
        @focus="onFocus"
        @blur="onBlur"
        @keydown="onKeydown"
        autocomplete="off"
        spellcheck="false"
      >
    </div>

    <div class="search-container" v-if="showResults">
      <template v-if="getCombinedResults(inputText).length === 0 && inputText.trim()">
        <div class="search-empty">No results found</div>
      </template>

      <div class="search-container-list">
        <NoteSearchResult
          v-for="(item, index) in getCombinedResults(inputText)"
          :key="(item.data.key || item.data.id) + '-' + index"
          :title="item.type === 'note' ? item.data.title : item.data.label"
          :subtitle="item.type === 'action' ? item.data.description : ''"
          :link="item.type === 'note' ? item.data.key : null"
          :icon="item.type === 'action' ? PlusIcon : ''"
          :class="{ selected: index === selectedIndex }"
          @select="onSelect"
          @click.stop.prevent="() => { if (item.type === 'note') openNote(item.data); else handleActionSelect(item.data); }"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.top-search-container {
  height: 100%;
  align-items: center;
  display: flex;
  position: relative;
}
    
.top-search-box {
  align-items: center;
  display: flex;
  background-color: var(--color-search-background);
  padding: 2px;
  border-radius: 5px;
}

.search-prompt {
  border: none;
  padding: 5px;
  width: 30vw;
  max-width: 400px;
  background: none;
  margin-left: -5px;
  font-family: inherit;
}

.search-prompt:focus {
  outline: none;
}

.search-icon {
  padding: 5px;
  filter: invert(var(--color-icon-invert));
}

.search-container {
  position: absolute;
  background-color: var(--color-search-background-container);
  top: 45px;
  margin-left: auto;
  margin-right: auto;
  max-width: 600px;
  max-height: 400px;
  overflow-y: auto;
  left: 0;
  right: 0;
  backdrop-filter: blur(15px);
  border-radius: 10px;
  width: calc(30vw + 400px);
  min-width: 320px;
  z-index: 99999;
  display: flex;
  flex-direction: column;
}

.search-container-list {
  display: flex;
  flex-direction: column;
  padding: 4px;
}

.search-empty {
  padding: 16px;
  text-align: center;
  opacity: 0.5;
  font-size: 14px;
}
</style>
