import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { formatCredits, compareCents } from '../api';
import CaseReel from './CaseReel';
import { useCountdown } from '../hooks/useCountdown';
import { rarityColor } from '../rarities';

const TOP_ITEMS = 5;

function depositsToReelItems(deposits) {
  return (deposits || [])
    .filter((d) => d.item)
    .map((d) => ({
      ...d.item,
      id: d.id,
      ownerUsername: d.username,
      ownerAvatarUrl: d.avatarUrl || '',
    }));
}

/**
 * Live battle preview card for the hub (mode-card-live).
 */
export default function BattleLiveCard({ battle, spinEvent }) {
  const [spinning, setSpinning] = useState(false);
  const [spinActive, setSpinActive] = useState(false);
  const [spinDeposits, setSpinDeposits] = useState([]);
  const [reelWinnerItemId, setReelWinnerItemId] = useState(null);
  const [lastWinner, setLastWinner] = useState(null);
  const [revealWinner, setRevealWinner] = useState(false);

  useEffect(() => {
    if (!spinEvent || spinEvent.id !== battle?.id) return;
    setSpinDeposits(spinEvent.deposits || []);
    setSpinActive(true);
    setSpinning(true);
    setRevealWinner(false);
    setReelWinnerItemId(spinEvent.reelWinnerItemId);
    setLastWinner(spinEvent.winnerUsername);
  }, [spinEvent, battle?.id]);

  useEffect(() => {
    if (battle?.status === 'spinning' && !spinActive) {
      setSpinDeposits(battle.deposits || []);
      setSpinActive(true);
      setSpinning(true);
      setLastWinner(battle.winnerUsername || null);
    }
  }, [battle, spinActive]);

  useEffect(() => {
    if (!revealWinner) return undefined;
    const t = setTimeout(() => {
      setSpinActive(false);
      setRevealWinner(false);
    }, 4000);
    return () => clearTimeout(t);
  }, [revealWinner]);

  const topItems = useMemo(() => {
    const deposits = [...(battle?.deposits || [])].filter((d) => d.item);
    deposits.sort((a, b) => compareCents(b.valueCents, a.valueCents));
    return deposits.slice(0, TOP_ITEMS);
  }, [battle]);

  const potItems = useMemo(
    () =>
      depositsToReelItems(
        spinActive && spinDeposits.length ? spinDeposits : battle?.deposits
      ),
    [battle, spinDeposits, spinActive]
  );

  const showReel = spinActive && potItems.length > 0;

  const liveTimerEndsAt =
    battle?.status === 'open' &&
    battle?.endsAt &&
    !battle?.waitingForPlayers &&
    !spinning
      ? battle.endsAt
      : null;
  const { label: liveTimerLabel } = useCountdown(liveTimerEndsAt);

  const playerCount = battle?.players?.length ?? 0;
  const potValue = battle?.totalValue ?? 0;
  const itemCount = battle?.deposits?.length ?? 0;
  const statusLabel =
    battle?.status === 'spinning' || spinning
      ? 'Spinning'
      : battle?.waitingForPlayers
        ? 'Waiting for players'
        : battle?.status === 'open'
          ? liveTimerEndsAt
            ? `Live ${liveTimerLabel}`
            : 'Live'
          : battle?.status || '…';

  if (!battle) return null;

  return (
    <Link to={`/battle/${battle.id}`} className="mode-card mode-card-live">
      <div className="mode-card-top">
        <h2>{battle.name || `Battle ${battle.id}`}</h2>
        <span
          className={`mode-status${
            battle.status === 'spinning' || spinning ? ' spinning' : ''
          }`}
        >
          {statusLabel}
        </span>
      </div>
      <p className="muted mode-blurb">
        Join the pot. Bet up to {battle.maxItemsPerPlayer || 3} items — chance scales with value.
      </p>

      <div className="mode-pot-stats">
        <div>
          <span className="muted">Pot</span>
          <strong>{formatCredits(potValue)} cr</strong>
        </div>
        <div>
          <span className="muted">Players</span>
          <strong>{playerCount}</strong>
        </div>
        <div>
          <span className="muted">Items</span>
          <strong>{itemCount}</strong>
        </div>
      </div>

      {showReel ? (
        <div className="mode-card-reel">
          <CaseReel
            items={potItems}
            winnerId={reelWinnerItemId || potItems[0]?.id}
            spinning={spinning || battle.status === 'spinning'}
            showOwners
            compact
            onDone={() => {
              setSpinning(false);
              setRevealWinner(true);
            }}
          />
          {revealWinner && lastWinner && (
            <p className="mode-card-winner">
              Winner: <strong>{lastWinner}</strong>
            </p>
          )}
        </div>
      ) : topItems.length > 0 ? (
        <div className="mode-pot-items" aria-label="Top items in pot">
          {topItems.map((d) => (
            <div
              key={d.id}
              className="mode-pot-thumb"
              style={{ borderColor: rarityColor(d.item.rarity) }}
              title={`${d.item.name} · ${formatCredits(d.valueCents)} cr`}
            >
              {d.item.imageUrl ? (
                <img src={d.item.imageUrl} alt="" loading="lazy" />
              ) : (
                <span>{d.item.name.slice(0, 2).toUpperCase()}</span>
              )}
            </div>
          ))}
          {itemCount > topItems.length && (
            <span className="mode-pot-more muted">+{itemCount - topItems.length}</span>
          )}
        </div>
      ) : (
        <p className="muted mode-pot-empty">No items in the pot yet — be the first.</p>
      )}
    </Link>
  );
}
