import { api, formatCredits, formatLastConnection, formatPlayTime, compareCents } from '../api';
import { useAuth } from '../AuthContext';
import ItemTile from '../components/ItemTile';
import ProfileCaseStats from '../components/ProfileCaseStats';
import ProfileCatalogBadges from '../components/ProfileCatalogBadges';
import ProfileAchievementBadges from '../components/ProfileAchievementBadges';
import ProfilePrestigeStats from '../components/ProfilePrestigeStats';
import { Link, Navigate, useParams } from 'react-router-dom';
import { useEffect, useMemo, useState } from 'react';

const PAGE_SIZE = 50;

export default function PlayerProfilePage() {
  const { username } = useParams();
  const { user } = useAuth();
  const [data, setData] = useState(null);
  const [error, setError] = useState('');
  const [sort, setSort] = useState('value');
  const [page, setPage] = useState(1);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const result = await api.playerProfile(username);
        if (!cancelled) setData(result);
      } catch (err) {
        if (!cancelled) setError(err.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [username]);

  const inventory = data?.inventory ?? [];

  const sorted = useMemo(() => {
    const list = [...inventory];
    if (sort === 'value') {
      list.sort((a, b) =>
        compareCents(
          b.valueCents ?? b.item?.valueCents ?? b.item?.marketValue,
          a.valueCents ?? a.item?.valueCents ?? a.item?.marketValue
        )
      );
    } else {
      list.sort((a, b) => new Date(b.obtainedAt) - new Date(a.obtainedAt));
    }
    return list;
  }, [inventory, sort]);

  const totalPages = Math.max(1, Math.ceil(sorted.length / PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const pageItems = useMemo(() => {
    const start = (currentPage - 1) * PAGE_SIZE;
    return sorted.slice(start, start + PAGE_SIZE);
  }, [sorted, currentPage]);

  useEffect(() => {
    setPage(1);
  }, [sort, username]);

  useEffect(() => {
    if (page > totalPages) setPage(totalPages);
  }, [page, totalPages]);

  if (user?.username === username) {
    return <Navigate to="/profile" replace />;
  }

  if (error) {
    return (
      <div>
        <div className="section-head">
          <div>
            <h1>Player profile</h1>
            <p className="muted">@{username}</p>
          </div>
        </div>
        <div className="error">{error}</div>
        <Link to="/leaderboard" className="btn secondary" style={{ marginTop: '1rem' }}>
          Back to leaderboard
        </Link>
      </div>
    );
  }

  if (!data) return <p className="muted">Loading…</p>;

  const { user: player, profile } = data;

  return (
    <div>
      <section className="section">
        <div className="section-head">
          <div>
            <h1>{player.username}</h1>
            <p className="muted">Player profile</p>
          </div>
          <Link to="/leaderboard" className="btn ghost">
            Leaderboard
          </Link>
        </div>

        <div className="profile-layout">
          <div className="profile-avatar-block admin-block">
            <div className="avatar-preview">
              {player.avatarUrl ? (
                <img src={player.avatarUrl} alt="" />
              ) : (
                <span>{player.username.slice(0, 2).toUpperCase()}</span>
              )}
            </div>
            {player.bio ? (
              <p style={{ marginTop: '0.75rem' }}>{player.bio}</p>
            ) : (
              <p className="muted" style={{ marginTop: '0.75rem' }}>
                No bio yet.
              </p>
            )}
            <div className="muted" style={{ marginTop: '0.75rem' }}>
              Balance {formatCredits(player.balance)} cr
            </div>
          </div>

          <div className="profile-stats admin-block">
            <h2>Stats</h2>
            <ul className="stat-list">
              <li>
                Status{' '}
                <strong
                  className={
                    profile.presence?.isConnected
                      ? 'presence-online'
                      : 'presence-offline'
                  }
                >
                  {profile.presence?.isConnected ? 'Online' : 'Offline'}
                </strong>
              </li>
              <li>
                Play time{' '}
                <strong>{formatPlayTime(profile.presence?.playTimeSeconds)}</strong>
              </li>
              <li>
                Last connection{' '}
                <strong>
                  {formatLastConnection(profile.presence?.lastConnection)}
                </strong>
              </li>
              <li>
                Joined <strong>{new Date(profile.createdAt).toLocaleDateString()}</strong>
              </li>
              <li>
                Inventory{' '}
                <strong>
                  {profile.inventoryCount} items · {formatCredits(profile.inventoryValue)} cr
                </strong>
              </li>
              <li>
                Cases opened <strong>{profile.casesOpened}</strong>
              </li>
              <li>
                Battle wins <strong>{profile.jackpotWins}</strong>
              </li>
            </ul>
            <ProfileAchievementBadges achievements={profile.achievements} />
            <ProfileCatalogBadges
              completed={profile.catalogCompleted}
              luckPercent={profile.catalogLuckPercent}
            />
            <ProfilePrestigeStats prestige={profile.prestige} />
            {profile.caseOpens?.length > 0 && (
              <div className="case-stats-block">
                <h3>Opens by case</h3>
                <ProfileCaseStats caseOpens={profile.caseOpens} />
              </div>
            )}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="section-head">
          <div>
            <h2>Inventory</h2>
            <p className="muted">Items currently held by this player.</p>
          </div>
        </div>

        {inventory.length > 0 && (
          <div className="inv-toolbar">
            <div className="inv-toolbar-left">
              <div className="sort-toggle" role="group" aria-label="Sort inventory">
                <button
                  type="button"
                  className={sort === 'value' ? 'active' : ''}
                  onClick={() => setSort('value')}
                >
                  Highest value
                </button>
                <button
                  type="button"
                  className={sort === 'recent' ? 'active' : ''}
                  onClick={() => setSort('recent')}
                >
                  Most recent
                </button>
              </div>
              <span className="muted inv-count">
                {inventory.length} item{inventory.length === 1 ? '' : 's'}
              </span>
            </div>
          </div>
        )}

        {inventory.length === 0 ? (
          <div className="empty">No items in inventory.</div>
        ) : (
          <>
            <div className="grid">
              {pageItems.map((inv) => (
                <ItemTile
                  key={inv.id}
                  item={inv.item}
                  favorite={inv.favorite}
                  staked={inv.staked}
                />
              ))}
            </div>
            {totalPages > 1 && (
              <div className="inv-pager">
                <button
                  type="button"
                  className="btn ghost"
                  disabled={currentPage <= 1}
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                >
                  Previous
                </button>
                <span className="muted">
                  Page {currentPage} / {totalPages}
                </span>
                <button
                  type="button"
                  className="btn ghost"
                  disabled={currentPage >= totalPages}
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                >
                  Next
                </button>
              </div>
            )}
          </>
        )}
      </section>
    </div>
  );
}
