import { Constants, type ChatInputApplicationCommandStructure } from '@projectdysnomia/dysnomia';
import { appraiseItems, type Appraisal } from '@star-kitten/eve/third-party/janice.js';
import { isModalSubmit } from '@star-kitten/discord/commands';
import { componentHasIdPrefix, isModalLabel, isModalSelect, isModalTextInput } from '@star-kitten/discord/components';
import type { CommandContext, ExecutableInteraction } from '@star-kitten/discord/commands';
import { PageType, usePages } from '@star-kitten/discord/pages';
import { renderAppraisal } from './renderAppraisal';
import { renderAppraisalModal } from './renderAppraisalModal';

const definition: ChatInputApplicationCommandStructure = {
  type: Constants.ApplicationCommandTypes.CHAT_INPUT,
  name: 'appraise',
  nameLocalizations: {
    de: 'bewerten',
    'es-ES': 'tasar',
    fr: 'estimer',
    ja: '査定',
    ko: '감정',
    ru: 'оценить',
    'zh-CN': '评估',
  },
  description: 'Evaluate the worth of your space junk',
  descriptionLocalizations: {
    de: 'Bewerten Sie den Wert Ihres Weltraumschrotts',
    'es-ES': 'Evalúa el valor de tu chatarra espacial',
    fr: 'Évaluez la valeur de vos déchets spatiaux',
    ja: 'あなたの宇宙のガラクタの価値を評価します',
    ko: '우주 쓰레기의 가치를 평가하십시오',
    ru: 'Оцените стоимость вашего космического мусора',
    'zh-CN': '评估您宇宙垃圾的价值',
  },
};

export interface AppraisalState {
  appraisal?: Appraisal;
}

async function execute(interaction: ExecutableInteraction, ctx: CommandContext) {
  return await usePages<AppraisalState>(
    {
      pages: {
        appraiseModal: {
          key: 'appraiseModal',
          type: PageType.MODAL,
          render: async () => renderAppraisalModal(interaction),
        },
        appraisalResult: {
          key: 'appraisalResult',
          render: async (pageCtx) => {
            if (!isModalSubmit(interaction)) {
              throw new Error('Expected a modal submit interaction for appraisalResult page');
            }
            let marketId = 2; // Default to Jita
            let items = '';

            interaction.data.components.forEach((comp) => {
              if (isModalLabel(comp)) {
                if (isModalSelect(comp.component) && componentHasIdPrefix(comp.component, `market`)) {
                  marketId = Number.parseInt(comp.component.values[0]) || marketId;
                } else if (isModalTextInput(comp.component) && componentHasIdPrefix(comp.component, `input`)) {
                  items = comp.component.value || items;
                }
              }
            });

            const appraisal = await appraiseItems(items, marketId);
            pageCtx.state.data.appraisal = appraisal;
            return renderAppraisal(appraisal, pageCtx, interaction);
          },
        },
        share: {
          key: 'share',
          type: PageType.FOLLOWUP,
          followUpFlags: Constants.MessageFlags.IS_COMPONENTS_V2,
          render: async (pageCtx) => renderAppraisal(pageCtx.state.data.appraisal!, pageCtx, interaction),
        },
      },
      initialPage: 'appraiseModal',
      timeout: 300, // 5 minutes
      ephemeral: true,
    },
    interaction,
    ctx,
  );
}

export default {
  definition,
  execute,
};
