import { useMemo, useState } from 'react';
import type { GameRoom } from '../../navigation';
import { MahjongTile, type MahjongTileData } from './MahjongTile';
import './MahjongGame.css';

interface Props {
  room: GameRoom;
  onExit: () => void;
  onHome: () => void;
}

type SeatId = 'top' | 'left' | 'right' | 'hero';

interface SeatInfo {
  id: SeatId;
  name: string;
  avatar: string;
  coins: number;
  wind: string;
  active: boolean;
  handCount: number;
  discards: MahjongTileData[];
  melds: MahjongTileData[][];
}

const TILES = {
  wan1: { id: 'wan1', label: '1万', suit: 'wan', value: 1 },
  wan2: { id: 'wan2', label: '2万', suit: 'wan', value: 2 },
  wan3: { id: 'wan3', label: '3万', suit: 'wan', value: 3 },
  wan4: { id: 'wan4', label: '4万', suit: 'wan', value: 4 },
  wan5: { id: 'wan5', label: '5万', suit: 'wan', value: 5 },
  wan6: { id: 'wan6', label: '6万', suit: 'wan', value: 6 },
  wan7: { id: 'wan7', label: '7万', suit: 'wan', value: 7 },
  wan8: { id: 'wan8', label: '8万', suit: 'wan', value: 8 },
  wan9: { id: 'wan9', label: '9万', suit: 'wan', value: 9 },
  tong1: { id: 'tong1', label: '1筒', suit: 'tong', value: 1 },
  tong2: { id: 'tong2', label: '2筒', suit: 'tong', value: 2 },
  tong3: { id: 'tong3', label: '3筒', suit: 'tong', value: 3 },
  tong4: { id: 'tong4', label: '4筒', suit: 'tong', value: 4 },
  tong5: { id: 'tong5', label: '5筒', suit: 'tong', value: 5 },
  tong6: { id: 'tong6', label: '6筒', suit: 'tong', value: 6 },
  tong7: { id: 'tong7', label: '7筒', suit: 'tong', value: 7 },
  tong8: { id: 'tong8', label: '8筒', suit: 'tong', value: 8 },
  tong9: { id: 'tong9', label: '9筒', suit: 'tong', value: 9 },
  tiao1: { id: 'tiao1', label: '1条', suit: 'tiao', value: 1 },
  tiao2: { id: 'tiao2', label: '2条', suit: 'tiao', value: 2 },
  tiao3: { id: 'tiao3', label: '3条', suit: 'tiao', value: 3 },
  tiao4: { id: 'tiao4', label: '4条', suit: 'tiao', value: 4 },
  tiao5: { id: 'tiao5', label: '5条', suit: 'tiao', value: 5 },
  tiao6: { id: 'tiao6', label: '6条', suit: 'tiao', value: 6 },
  tiao7: { id: 'tiao7', label: '7条', suit: 'tiao', value: 7 },
  tiao8: { id: 'tiao8', label: '8条', suit: 'tiao', value: 8 },
  tiao9: { id: 'tiao9', label: '9条', suit: 'tiao', value: 9 },
  red: { id: 'red', label: '红中', suit: 'dragon', value: 0 },
} satisfies Record<string, MahjongTileData>;

const HERO_HAND: MahjongTileData[] = [
  TILES.wan1,
  TILES.wan2,
  TILES.wan3,
  TILES.wan4,
  TILES.wan5,
  TILES.wan6,
  TILES.tong4,
  TILES.tong5,
  TILES.tong6,
  TILES.tiao2,
  TILES.tiao3,
  TILES.tiao4,
  TILES.red,
  TILES.wan9,
];

const WALL_TILES: MahjongTileData[] = [
  TILES.wan1,
  TILES.wan2,
  TILES.wan3,
  TILES.wan4,
  TILES.wan5,
  TILES.wan6,
  TILES.wan7,
  TILES.wan8,
  TILES.wan9,
  TILES.tong1,
  TILES.tong2,
  TILES.tong3,
  TILES.tong4,
  TILES.tong5,
  TILES.tong6,
  TILES.tong7,
  TILES.tong8,
  TILES.tong9,
  TILES.tiao1,
  TILES.tiao2,
  TILES.tiao3,
  TILES.tiao4,
  TILES.tiao5,
  TILES.tiao6,
  TILES.tiao7,
  TILES.tiao8,
  TILES.tiao9,
  TILES.red,
];

const SEATS: SeatInfo[] = [
  {
    id: 'top',
    name: '幺妹',
    avatar: '幺',
    coins: 48_220,
    wind: '对家',
    active: false,
    handCount: 13,
    discards: [TILES.wan3, TILES.tong4, TILES.tiao8, TILES.red],
    melds: [[TILES.wan7, TILES.wan7, TILES.wan7], [TILES.tong2, TILES.tong2, TILES.tong2, TILES.tong2]],
  },
  {
    id: 'left',
    name: '老王',
    avatar: '王',
    coins: 65_840,
    wind: '上家',
    active: false,
    handCount: 14,
    discards: [TILES.tiao1, TILES.tong7, TILES.wan9],
    melds: [[TILES.tiao5, TILES.tiao5, TILES.tiao5]],
  },
  {
    id: 'right',
    name: '李四',
    avatar: '李',
    coins: 52_930,
    wind: '下家',
    active: false,
    handCount: 12,
    discards: [TILES.wan2, TILES.tong9, TILES.tiao6, TILES.wan8],
    melds: [[TILES.red, TILES.red, TILES.red]],
  },
  {
    id: 'hero',
    name: 'ericay',
    avatar: 'E',
    coins: 50_010,
    wind: '本人',
    active: true,
    handCount: HERO_HAND.length,
    discards: [TILES.wan1, TILES.tong3, TILES.tiao2],
    melds: [[TILES.tong1, TILES.tong1, TILES.tong1], [TILES.red, TILES.red, TILES.red, TILES.red]],
  },
];

const ACTION_BUTTONS = ['碰', '杠', '胡', '过', '出牌'] as const;
const TOOL_BUTTONS = ['托管', '排序'] as const;

function takeWallTiles(count: number, offset: number): MahjongTileData[] {
  const tiles: MahjongTileData[] = [];
  for (let i = 0; i < count; i += 1) {
    tiles.push(WALL_TILES[(offset + i) % WALL_TILES.length]);
  }
  return tiles;
}

function TileWall({ tiles, orientation }: { tiles: MahjongTileData[]; orientation: 'top' | 'bottom' | 'left' | 'right' }) {
  return (
    <div className={`mahjong-wall mahjong-wall--${orientation}`}>
      {tiles.map((tile, index) => (
        <MahjongTile
          key={`${orientation}-${tile.id}-${index}`}
          tile={tile}
          faceDown
          compact
          rotated={orientation === 'left' || orientation === 'right'}
          className={`mahjong-wall__tile mahjong-wall__tile--${orientation}`}
        />
      ))}
    </div>
  );
}

function MeldGroup({ tiles }: { tiles: MahjongTileData[] }) {
  return (
    <div className="mahjong-meld">
      {tiles.map((tile, index) => (
        <MahjongTile
          key={`${tile.id}-${index}`}
          tile={tile}
          compact
          className={`mahjong-meld__tile ${index === tiles.length - 1 ? 'mahjong-meld__tile--lift' : ''}`}
        />
      ))}
    </div>
  );
}

function DiscardPond({ tiles, orientation }: { tiles: MahjongTileData[]; orientation: 'top' | 'left' | 'right' | 'hero' }) {
  return (
    <div className={`mahjong-discards mahjong-discards--${orientation}`}>
      {tiles.map((tile, index) => (
        <MahjongTile key={`${orientation}-${tile.id}-${index}`} tile={tile} compact className="mahjong-discard" />
      ))}
    </div>
  );
}

function SeatBadge({ seat }: { seat: SeatInfo }) {
  return (
    <div className={`mahjong-seat-badge ${seat.active ? 'mahjong-seat-badge--active' : ''}`}>
      <div className="mahjong-seat-badge__avatar">{seat.avatar}</div>
      <div className="mahjong-seat-badge__meta">
        <div className="mahjong-seat-badge__name">{seat.name}</div>
        <div className="mahjong-seat-badge__coins">{seat.coins.toLocaleString()} 金币</div>
      </div>
    </div>
  );
}

export function MahjongGame({ room, onExit, onHome }: Props) {
  const [selectedTileId, setSelectedTileId] = useState<string>(HERO_HAND[HERO_HAND.length - 1]?.id ?? '');

  const heroSummary = useMemo(() => {
    const selected = HERO_HAND.find((tile) => tile.id === selectedTileId) ?? HERO_HAND[HERO_HAND.length - 1];
    return selected ? `已选：${selected.label}` : '已选：无';
  }, [selectedTileId]);

  const heroMelds = SEATS.find((seat) => seat.id === 'hero')?.melds ?? [];

  return (
    <div className="mahjong-screen">
      <header className="game-topbar mahjong-topbar">
        <div className="game-topbar__left">
          <button className="icon-btn icon-btn--round" aria-label="返回选择大厅" onClick={onExit}>
            ←
          </button>
          <div className="game-topbar__title">
            <span className="game-topbar__main">红中断勾卡</span>
            <span className="game-topbar__sub">{room.name} · 底注 {room.baseChip} · 四川血战到底 · 4人场 UI 框架</span>
          </div>
        </div>
        <div className="game-topbar__right">
          <button className="icon-btn" aria-label="返回大厅" onClick={onHome}>⌂</button>
        </div>
      </header>

      <main className="mahjong-body">
        <section className="mahjong-stage">
          <div className="mahjong-stage__frame">
            <div className="mahjong-stage__wood" />
            <div className="mahjong-stage__felt">
              <div className="mahjong-stage__grain" />
              <div className="mahjong-stage__glow" />
              <div className="mahjong-stage__watermark">红中断勾卡</div>
              <div className="mahjong-stage__indicator">
                <span className="mahjong-stage__indicator-num">54</span>
              </div>

              <TileWall tiles={takeWallTiles(18, 0)} orientation="top" />
              <TileWall tiles={takeWallTiles(12, 18)} orientation="left" />
              <TileWall tiles={takeWallTiles(12, 8)} orientation="right" />
              <TileWall tiles={takeWallTiles(16, 12)} orientation="bottom" />

              <div className="mahjong-seat mahjong-seat--top">
                <SeatBadge seat={SEATS[0]} />
                <div className="mahjong-seat__melds mahjong-seat__melds--top">
                  {SEATS[0].melds.map((meld) => <MeldGroup key={meld.map((tile) => tile.id).join('-')} tiles={meld} />)}
                </div>
                <DiscardPond tiles={SEATS[0].discards} orientation="top" />
              </div>

              <div className="mahjong-seat mahjong-seat--left">
                <SeatBadge seat={SEATS[1]} />
                <div className="mahjong-seat__melds mahjong-seat__melds--side">
                  {SEATS[1].melds.map((meld) => <MeldGroup key={meld.map((tile) => tile.id).join('-')} tiles={meld} />)}
                </div>
                <DiscardPond tiles={SEATS[1].discards} orientation="left" />
              </div>

              <div className="mahjong-seat mahjong-seat--right">
                <SeatBadge seat={SEATS[2]} />
                <div className="mahjong-seat__melds mahjong-seat__melds--side">
                  {SEATS[2].melds.map((meld) => <MeldGroup key={meld.map((tile) => tile.id).join('-')} tiles={meld} />)}
                </div>
                <DiscardPond tiles={SEATS[2].discards} orientation="right" />
              </div>

              <div className="mahjong-seat mahjong-seat--hero">
                <SeatBadge seat={SEATS[3]} />
                <div className="mahjong-seat__melds mahjong-seat__melds--hero">
                  {heroMelds.map((meld) => <MeldGroup key={meld.map((tile) => tile.id).join('-')} tiles={meld} />)}
                </div>
                <DiscardPond tiles={SEATS[3].discards} orientation="hero" />
              </div>
            </div>
          </div>
        </section>

        <section className="mahjong-hero-panel">
          <div className="mahjong-hero-panel__info">
            <div className="mahjong-seat-badge mahjong-seat-badge--hero-card mahjong-seat-badge--active">
              <div className="mahjong-seat-badge__avatar">{SEATS[3].avatar}</div>
              <div className="mahjong-seat-badge__meta">
                <div className="mahjong-seat-badge__name">{SEATS[3].name}</div>
                <div className="mahjong-seat-badge__coins">{heroSummary}</div>
              </div>
            </div>
            <div className="mahjong-hero-panel__melds">
              {heroMelds.map((meld) => <MeldGroup key={meld.map((tile) => tile.id).join('-')} tiles={meld} />)}
            </div>
          </div>

          <div className="mahjong-hand-row">
            <div className="mahjong-hand-row__label">手牌</div>
            <div className="mahjong-hand">
              {HERO_HAND.map((tile, index) => {
                const isDrawnTile = index === HERO_HAND.length - 1;
                const selected = selectedTileId === tile.id;
                return (
                  <MahjongTile
                    key={tile.id}
                    tile={tile}
                    selected={selected}
                    onClick={() => setSelectedTileId(tile.id)}
                    compact={isDrawnTile}
                    className={isDrawnTile ? 'mahjong-hand__tile mahjong-hand__tile--drawn' : 'mahjong-hand__tile'}
                  />
                );
              })}
            </div>
          </div>
        </section>

        <section className="mahjong-actions">
          <div className="mahjong-actions__tools">
            {TOOL_BUTTONS.map((action) => (
              <button key={action} type="button" className="mahjong-tool-btn">
                {action}
              </button>
            ))}
          </div>
          <div className="mahjong-actions__main">
            {ACTION_BUTTONS.map((action) => (
              <button key={action} type="button" className="mahjong-action-btn">
                {action}
              </button>
            ))}
          </div>
        </section>
      </main>
    </div>
  );
}
