import React, { JSX } from 'react';

import type { UiAccessibleConfig } from '@redocly/config';

import { EntityType } from '@redocly/theme/core/types';
import { CodeIcon } from '@redocly/theme/icons/CodeIcon/CodeIcon';
import { GraphIcon } from '@redocly/theme/icons/GraphIcon/GraphIcon';
import { PeopleIcon } from '@redocly/theme/icons/PeopleIcon/PeopleIcon';
import { UserIcon } from '@redocly/theme/icons/UserIcon/UserIcon';
import { MoleculesIcon } from '@redocly/theme/icons/MoleculesIcon/MoleculesIcon';
import { HierarchyIcon } from '@redocly/theme/icons/HierarchyIcon/HierarchyIcon';
import { Image } from '@redocly/theme/components/Image/Image';
import { PREDEFINED_ENTITY_TYPES, useThemeConfig } from '@redocly/theme/core';
import { NoteIcon } from '@redocly/theme/icons/NoteIcon/NoteIcon';
import { CubeIcon } from '@redocly/theme/icons/CubeIcon/CubeIcon';

export type CatalogEntityIconProps = {
  entityType: string;
  defaultColor?: boolean;
  forceColor?: string;
  entitiesCatalogConfig?: UiAccessibleConfig['entitiesCatalog'];
};

const getIconColor = (entityType: EntityType) => `var(--catalog-entity-icon-color-${entityType})`;

const getEntityIcon = ({
  entityType,
  defaultColor,
  forceColor,
  entitiesCatalogConfig,
}: CatalogEntityIconProps) => {
  if (PREDEFINED_ENTITY_TYPES.includes(entityType)) {
    const iconColor =
      forceColor ??
      (defaultColor ? `var(--catalog-entity-icon-color)` : getIconColor(entityType as EntityType));

    const entityIconMap: Record<EntityType, JSX.Element> = {
      service: <CodeIcon color={iconColor} />,
      domain: <GraphIcon color={iconColor} />,
      team: <PeopleIcon color={iconColor} />,
      user: <UserIcon color={iconColor} />,
      'api-description': <NoteIcon color={iconColor} />,
      'data-schema': <HierarchyIcon color={iconColor} />,
      'api-operation': <MoleculesIcon color={iconColor} />,
    };

    return entityIconMap[entityType as EntityType];
  }

  const iconConfig = entitiesCatalogConfig?.entityTypes?.[entityType]?.icon;

  if (iconConfig?.src || iconConfig?.srcSet) {
    return (
      <Image
        src={iconConfig?.src}
        srcSet={iconConfig?.srcSet}
        alt={`${entityType} icon`}
        width="16"
        height="16"
      />
    );
  }

  return <CubeIcon color="var(--catalog-entity-icon-color)" />;
};

export function CatalogEntityIcon({
  entityType,
  defaultColor = false,
  forceColor,
}: CatalogEntityIconProps): JSX.Element {
  const themeConfig = useThemeConfig();

  const icon = getEntityIcon({
    entityType,
    defaultColor,
    forceColor,
    entitiesCatalogConfig: themeConfig.entitiesCatalog,
  });

  if (!icon) {
    throw new Error(`Unhandled entity type: ${entityType}`);
  }

  return icon;
}
