import type { Page } from '@star-kitten/discord/pages';
import type { SearchState } from '../search.command';
import {
  createContainer,
  createMediaGallery,
  createSection,
  createTextDisplay,
  createThumbnail,
  createURLButton,
} from '@star-kitten/discord/components';
import { getRoleBonuses, getSkillBonuses, getType } from '@star-kitten/eve/models/type.js';
import { cleanText } from '@star-kitten/eve/utils/markdown.js';
import { typeSearch } from '@star-kitten/eve/utils/typeSearch.js';
import { isApplicationCommand } from '@star-kitten/discord';
import { fetchPrice } from '@star-kitten/eve/third-party/evetycoon.js';
import { formatNumberToShortForm } from '@star-kitten/util/text.js';
import { searchActionRow } from './helpers';

const page: Page<SearchState> = {
  key: 'main',
  render: async (context) => {
    if (!context.state.data.type_id && isApplicationCommand(context.interaction)) {
      const typeName = context.interaction.data.options?.find((opt) => opt.name === 'name')?.value;
      const found = await typeSearch(typeName as string);

      if (!found) {
        return {
          components: [createTextDisplay(`No item found for: ${typeName}`)],
        };
      }

      context.state.data.type_id = found.type_id;
    }

    const type = getType(context.state.data.type_id);

    const skillBonuses = getSkillBonuses(type);
    const roleBonuses = getRoleBonuses(type);
    const price = await fetchPrice(type.type_id);

    return {
      components: [
        createContainer(
          {},
          createSection(
            createThumbnail(`https://images.evetech.net/types/${type.type_id}/icon`),
            createTextDisplay(`
# [${type.name.en}](https://everef.net/types/${type.type_id})

${skillBonuses
  .map((bonus) => {
    return `## Bonus per level of ${bonus.skill.name.en}
${bonus.bonuses
  .sort((a, b) => a.importance - b.importance)
  .map((b) => `${b.bonus}${b.unit?.display_name ?? '-'} ${cleanText(b.bonus_text.en)}`)
  .join('\n')}`;
  })
  .join('\n')}
  ${
    roleBonuses.length > 0
      ? `\n## Role Bonuses
${roleBonuses
  .sort((a, b) => a.importance - b.importance)
  .map((b) => `${b.bonus ?? ''}${b.unit?.display_name ?? '-'} ${cleanText(b.bonus_text.en)}`)
  .join('\n')}`
      : ''
  }
`),
          ),
          createMediaGallery({
            url: 'https://iili.io/KTPCFRt.md.webp',
          }),
          // createSeparator(Padding.LARGE),
          createSection(
            createURLButton('View on EVE Tycoon', `https://evetycoon.com/market/${type.type_id}`),
            createTextDisplay(
              `## Buy: ${price ? formatNumberToShortForm(price.buyAvgFivePercent) : '--'} ISK
## Sell: ${price ? formatNumberToShortForm(price.sellAvgFivePercent) : '--'} ISK`,
            ),
          ),
          createTextDisplay(`-# Type Id: ${type.type_id}`),
          searchActionRow('main'),
        ),
      ],
    };
  },
};

export default page;
