import {
  createChatCommand,
  isAutocomplete,
  stringOption,
  type CommandContext,
  type ExecutableInteraction,
} from '@star-kitten/discord';
import { usePages } from '@star-kitten/discord/pages';
import { initializeTypeSearch, typeSearchAutoComplete } from '@star-kitten/eve/utils/typeSearch.js';

import main from './pages/main';
import attributes from './pages/attributes';

let now = Date.now();
console.debug('Initializing type search...');
await initializeTypeSearch().catch((e) => {
  console.error('Failed to initialize type search', e);
  process.exit(1);
});
console.debug(`Type search initialized. Took ${Date.now() - now}ms`);

export interface SearchState {
  type_id: number;
}

export default createChatCommand(
  {
    name: 'search',
    description: 'Search for a type',
    options: [
      stringOption({
        name: 'name',
        description: 'The type name to search for',
        autocomplete: true,
        required: true,
      }),
    ],
  },
  execute,
);

async function execute(interaction: ExecutableInteraction, ctx: CommandContext) {
  if (isAutocomplete(interaction)) {
    const focusedOption = interaction.data.options?.find((opt) => opt.focused);
    if (focusedOption?.name === 'name') {
      const value = focusedOption.value as string;
      const results = await typeSearchAutoComplete(value);
      if (results) {
        await interaction.result(results);
      } else {
        await interaction.result([]);
      }
    }
    return;
  }

  usePages<SearchState>(
    {
      pages: {
        main,
        attributes,
      },
      initialPage: 'main',
      ephemeral: false,
    },
    interaction,
    ctx,
  );
}
