import {FC, HTMLProps, useMemo} from "react"
import {Entity} from "../../../src/types"
import {useDetails} from "../../../src/hooks/useDetails"
import styles from './EntitySpan.module.css'
import {RecipeSpan} from "../Recipe/Recipe";
import {LeftClickIcon} from "../LeftClickIcon/LeftClickIcon";

interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
  value: Entity|string
  leftClickText?: string
  rightClickText?: string
}

export const EntitySpan: FC<Props> = ({value, leftClickText, rightClickText, ...rest}) => {
  const details = useDetails()
  const entity = useMemo<Entity>(() => {
    return typeof value === "object"
      ? value
      : details.find(detail => detail.href === value) ?? {
        href: value,
        name: value,
        image: value,
        recipe: undefined
      }
  }, [details, value])

  return <span className={styles.span} {...rest}>
    {/* eslint-disable-next-line @next/next/no-img-element */}
    <img className={styles.img} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/>
    {entity.name}
    <div className={styles.tooltip}>
      {entity.recipe && (
        <>
          <div className={styles.strong}>Recipe</div>
          <RecipeSpan recipe={entity.recipe}/>
        </>
      )}
      {(leftClickText || rightClickText) && (
        <>
          <div className={styles.strong}>Actions</div>
          {leftClickText && <div><LeftClickIcon className={styles.leftClick} classClick={styles.clickBtn}/> {leftClickText}</div>}
          {rightClickText && <div><LeftClickIcon className={styles.rightClick} classClick={styles.clickBtn}/> {rightClickText}</div>}
        </>
      )}
    </div>
  </span>
}
