import { renderSubroutes, type Page } from '@star-kitten/discord/pages';
import type { SearchState } from '../search.command';
import {
  ButtonStyle,
  createContainer,
  createSection,
  createSeparator,
  createTextDisplay,
  createThumbnail,
  Padding,
} from '@star-kitten/discord/components';
import {
  getGroup,
  getType,
  getUnit,
  renderUnit,
  typeGetAttribute,
  typeHasAnyAttribute,
  type Type,
} from '@star-kitten/eve/models';
import { attributeOrdering } from '@star-kitten/eve';
import { searchActionRow } from './helpers';
import { toTitleCase } from '@star-kitten/util/text.js';

enum Images {
  ATTRIBUTES = 'https://iili.io/KTbaMR2.md.webp',
  DEFENSES = 'https://iili.io/KTbSVoX.md.webp',
  FITTING = 'https://iili.io/KufiFYG.md.webp',
  FACILITIES = 'https://iili.io/KufikGt.md.webp',
}

const attributeCategoryMap = {
  structure: 'UI/Fitting/Structure',
  armor: 'UI/Common/Armor',
  shield: 'UI/Common/Shield',
  ewar: 'UI/Common/EWarResistances',
  capacitor: 'UI/Fitting/FittingWindow/Capacitor',
  targeting: 'UI/Fitting/FittingWindow/Targeting',
  facilities: 'UI/InfoWindow/SharedFacilities',
  fighters: 'UI/InfoWindow/FighterFacilities',
  on_death: 'UI/InfoWindow/OnDeath',
  jump_drive: 'UI/InfoWindow/JumpDriveSystems',
  propulsion: 'UI/Compare/Propulsion',
};

const groupedCategories = [
  // defenses
  ['shield', 'armor', 'structure', 'ewar'],
  // fittings
  ['capacitor', 'targeting', 'propulsion'],
  // facilities
  ['facilities', 'fighters', 'on_death', 'jump_drive'],
];

function getAttributeOrdering(type: Type) {
  const group = getGroup(type.group_id);
  switch (group.category_id) {
    case 11:
      return attributeOrdering['11'];
    case 87:
      return attributeOrdering['87'];
    default:
      return attributeOrdering.default;
  }
}

const bannerMap = {
  shield: Images.DEFENSES,
  armor: Images.DEFENSES,
  structure: Images.DEFENSES,
  ewar: Images.DEFENSES,

  capacitor: Images.FITTING,
  targeting: Images.FITTING,
  propulsion: Images.FITTING,

  facilities: Images.FACILITIES,
  fighters: Images.FACILITIES,
  on_death: Images.FACILITIES,
  jump_drive: Images.FACILITIES,
};

const page: Page<SearchState> = {
  key: 'attributes',
  render: (context) => {
    const type = getType(context.state.data.type_id);
    const ordering = getAttributeOrdering(type);

    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})\n## Attributes`),
          ),
          ...renderSubroutes(
            context,
            'attributes',
            groupedCategories.map((group) =>
              group.map((cat) => {
                const attrCat = ordering[attributeCategoryMap[cat]];
                const attrs = attrCat.groupedCategories
                  ? attrCat.groupedCategories.map(([name, id]) => id).concat(attrCat.normalAttributes) || []
                  : attrCat.normalAttributes;
                if (!typeHasAnyAttribute(type, attrs)) {
                  return undefined;
                }
                return {
                  label: toTitleCase(cat.replace('_', ' ')),
                  value: cat,
                  banner: bannerMap[cat],
                };
              }),
            ),
            (currentRoute) => {
              const lines: string[] = [];
              const attrCat = ordering[attributeCategoryMap[currentRoute]];
              const attrs = attrCat.groupedCategories
                ? attrCat.groupedCategories.map(([name, id]) => id).concat(attrCat.normalAttributes) || []
                : attrCat.normalAttributes;
              attrs.map((attrId) => {
                const attr = typeGetAttribute(type, attrId);
                if (!attr) return;
                const unit = attr.attribute.unit_id ? renderUnit(getUnit(attr.attribute.unit_id), attr.value) : '';
                lines.push(`${attr.attribute.display_name.en.padEnd(24)} ${unit}`);
              });
              return createTextDisplay('```\n' + lines.join('\n') + '\n```');
            },
            { style: ButtonStyle.SECONDARY },
          ),
          createSeparator(Padding.LARGE),
          searchActionRow('attributes'),
        ),
      ],
    };
  },
};

export default page;
