import type { ReactNode } from 'react';
import './MahjongTile.css';

export type MahjongSuit = 'wan' | 'tong' | 'tiao' | 'dragon';

export interface MahjongTileData {
  id: string;
  label: string;
  suit: MahjongSuit;
  value: number;
}

interface Props {
  tile: MahjongTileData;
  selected?: boolean;
  faceDown?: boolean;
  compact?: boolean;
  rotated?: boolean;
  className?: string;
  onClick?: () => void;
}

function SuitFace({ tile }: { tile: MahjongTileData }) {
  let content: ReactNode;

  if (tile.suit === 'wan') {
    const wanTone = tile.value % 2 === 0 ? 'black' : 'red';
    content = (
      <>
        <span className={`mjtile__wan-text mjtile__wan-text--${wanTone}`}>{tile.value}</span>
        <span className="mjtile__wan-char">万</span>
        <span className={`mjtile__wan-text mjtile__wan-text--${wanTone} mjtile__wan-text--ghost`}>
          {tile.value}
        </span>
      </>
    );
  } else if (tile.suit === 'tong') {
    content = (
      <div className="mjtile__pip-grid mjtile__pip-grid--tong" aria-hidden>
        {Array.from({ length: tile.value }).map((_, index) => (
          <span key={index} className="mjtile__pip mjtile__pip--circle" />
        ))}
      </div>
    );
  } else if (tile.suit === 'tiao') {
    content = (
      <div className="mjtile__pip-grid mjtile__pip-grid--tiao" aria-hidden>
        {Array.from({ length: tile.value }).map((_, index) => (
          <span key={index} className="mjtile__pip mjtile__pip--bamboo" />
        ))}
      </div>
    );
  } else {
    content = <span className="mjtile__dragon">中</span>;
  }

  return (
    <div className={`mjtile__face mjtile__face--${tile.suit}`}>
      <span className="mjtile__label">{tile.label}</span>
      {content}
    </div>
  );
}

export function MahjongTile({
  tile,
  selected = false,
  faceDown = false,
  compact = false,
  rotated = false,
  className,
  onClick,
}: Props) {
  const classes = [
    'mjtile',
    `mjtile--${tile.suit}`,
    compact ? 'mjtile--compact' : '',
    selected ? 'mjtile--selected' : '',
    faceDown ? 'mjtile--back' : '',
    rotated ? 'mjtile--rotated' : '',
    onClick ? 'mjtile--interactive' : '',
    className ?? '',
  ]
    .filter(Boolean)
    .join(' ');

  const ariaLabel = faceDown ? '麻将牌背' : tile.label;

  if (onClick) {
    return (
      <button type="button" className={classes} onClick={onClick} aria-label={ariaLabel}>
        {faceDown ? <span className="mjtile__backmark" aria-hidden>川</span> : <SuitFace tile={tile} />}
      </button>
    );
  }

  return (
    <div className={classes} aria-label={ariaLabel}>
      {faceDown ? <span className="mjtile__backmark" aria-hidden>川</span> : <SuitFace tile={tile} />}
    </div>
  );
}
