import type React from '@teact';
import type { TeactNode } from '@teact';
import { memo, useMemo } from '@teact';
import { getActions } from '../../../global';

import type {
  ApiPeer,
  ApiSavedStarGift,
  ApiStarGiftAttributeBackdrop, ApiStarGiftAttributeModel, ApiStarGiftAttributePattern,
  ApiTypeCurrencyAmount,
} from '../../../api/types';

import { NNBSP } from '../../../config.ts';
import {
  formatStarsTransactionAmount,
} from '../../../global/helpers/payments';
import { IS_TOUCH_ENV } from '../../../util/browser/windowEnvironment.ts';
import buildClassName from '../../../util/buildClassName';
import buildStyle from '../../../util/buildStyle';
import { REM } from '../../common/helpers/mediaDimensions.ts';

import { useTransitionActiveKey } from '../../../hooks/animations/useTransitionActiveKey';
import useAppLayout from '../../../hooks/useAppLayout';
import useFlag from '../../../hooks/useFlag';
import useLang from '../../../hooks/useLang';

import AnimatedIconFromSticker from '../../common/AnimatedIconFromSticker';
import Icon from '../../common/icons/Icon';
import StarIcon from '../../common/icons/StarIcon';
import RadialPatternBackground from '../../common/profile/RadialPatternBackground';
import Transition from '../../ui/Transition';
import UniqueGiftManageButtons from './UniqueGiftManageButtons';

import styles from './UniqueGiftHeader.module.scss';

type OwnProps = {
  modelAttribute: ApiStarGiftAttributeModel;
  backdropAttribute: ApiStarGiftAttributeBackdrop;
  patternAttribute: ApiStarGiftAttributePattern;
  title?: TeactNode;
  badge?: TeactNode;
  subtitle?: TeactNode;
  subtitlePeer?: ApiPeer;
  className?: string;
  resellPrice?: ApiTypeCurrencyAmount;
  showManageButtons?: boolean;
  savedGift?: ApiSavedStarGift;
  noLoop?: boolean;
  onStickerAnimationEnded?: (modelName: string) => void;
  children?: React.ReactNode;
};

const STICKER_SIZE = 120;

const UniqueGiftHeader = ({
  modelAttribute,
  backdropAttribute,
  patternAttribute,
  title,
  badge,
  subtitle,
  subtitlePeer,
  className,
  resellPrice,
  showManageButtons,
  savedGift,
  noLoop,
  onStickerAnimationEnded,
  children,
}: OwnProps) => {
  const {
    openChat,
  } = getActions();

  const { isMobile } = useAppLayout();

  const lang = useLang();
  const [isGiftHover, markGiftHover, unmarkGiftHover] = useFlag(false);
  const activeKey = useTransitionActiveKey([modelAttribute, backdropAttribute, patternAttribute]);
  const subtitleColor = backdropAttribute?.textColor;

  const handleStickerEnded = () => {
    onStickerAnimationEnded?.(modelAttribute.name);
  };

  const radialPatternBackdrop = useMemo(() => {
    const backdropColors = [backdropAttribute.centerColor, backdropAttribute.edgeColor];

    return (
      <RadialPatternBackground
        className={styles.radialPattern}
        canvasClassName={styles.radialPatternCanvas}
        backgroundColors={backdropColors}
        patternIcon={patternAttribute.sticker}
        yPosition={7.5 * REM}
        maxRadius={0.26}
        patternSize={isMobile ? 14 : 16}
        ovalFactor={1.2}
      />
    );
  }, [backdropAttribute, patternAttribute, isMobile]);

  return (
    <div
      className={buildClassName(styles.root,
        'interactive-gift',
        showManageButtons && styles.withManageButtons,
        badge && styles.withBadge,
        className)}
      style={buildStyle(subtitleColor && `--tinted-text-color: ${subtitleColor}`)}
    >
      <Transition
        className={styles.transition}
        slideClassName={buildClassName(styles.transitionSlide)}
        activeKey={activeKey}
        direction={1}
        name="zoomBounceSemiFade"
      >
        {radialPatternBackdrop}
        <AnimatedIconFromSticker
          className={styles.sticker}
          sticker={modelAttribute.sticker}
          size={STICKER_SIZE}
          noLoop={noLoop ?? !isGiftHover}
          onEnded={handleStickerEnded}
          onMouseEnter={!IS_TOUCH_ENV ? markGiftHover : undefined}
          onMouseLeave={!IS_TOUCH_ENV ? unmarkGiftHover : undefined}
        />
      </Transition>
      {Boolean(badge) && (
        <div className={styles.badge}>{badge}</div>
      )}
      {Boolean(title) && <h1 className={styles.title}>{title}</h1>}
      {Boolean(subtitle) && (
        <div
          className={buildClassName(styles.subtitle, subtitlePeer && styles.subtitleBadge)}
          onClick={() => {
            if (subtitlePeer) {
              openChat({ id: subtitlePeer.id });
            }
          }}
        >
          {subtitle}
        </div>
      )}
      {savedGift && showManageButtons && (
        <UniqueGiftManageButtons
          savedGift={savedGift}
        />
      )}
      {resellPrice && (
        <span className={styles.amount}>
          {formatStarsTransactionAmount(lang, resellPrice)}
          {NNBSP}
          {resellPrice.currency === 'XTR' && <StarIcon type="gold" size="adaptive" />}
          {resellPrice.currency === 'TON' && <Icon className="in-text-icon" name="toncoin" />}
        </span>
      )}
      {children}
    </div>
  );
};

export default memo(UniqueGiftHeader);
