import React, { useMemo } from 'react';
import {
  Heart,
  ExternalLink,
  ChevronLeft,
  ChevronRight,
  TrendingUp,
  Facebook,
  Globe
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { Listing } from '../types';

/**
 * Format time since current bid was achieved
 * - Less than 1 hour -> "XX minutes ago"
 * - 1–23 hours -> "X hours ago"
 * - Around 1 day -> "yesterday"
 * - 2+ days -> "X days ago"
 * - 1+ week -> "X weeks ago"
 */
function formatBidAge(timestamp: string): string {
  if (!timestamp) return 'recently';
  const time = new Date(timestamp).getTime();
  if (isNaN(time)) return 'recently';

  const diffMs = Math.max(0, Date.now() - time);
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHours = Math.floor(diffMin / 60);
  const diffDays = Math.floor(diffHours / 24);
  const diffWeeks = Math.floor(diffDays / 7);

  if (diffMin < 1) {
    return 'just now';
  }
  if (diffMin < 60) {
    return `${diffMin} ${diffMin === 1 ? 'minute' : 'minutes'} ago`;
  }
  if (diffHours < 24) {
    return `${diffHours} ${diffHours === 1 ? 'hour' : 'hours'} ago`;
  }
  if (diffDays === 1) {
    return 'yesterday';
  }
  if (diffDays < 7) {
    return `${diffDays} days ago`;
  }
  return `${diffWeeks} ${diffWeeks === 1 ? 'week' : 'weeks'} ago`;
}

export const RankingList: React.FC = () => {
  const {
    paginatedListings,
    rankedListings,
    listings,
    categories,
    state,
    settings,
    texts,
    totalPages,
    theme,
    t,
    tCategory,
    tNum,
    formatBidAgeI18n,
    setCurrentPage,
    handleHeart,
    handleClick,
    openOutbidModal
  } = useApp();

  // Dynamically compute category rank for all active listings based on the project's exact ranking rules:
  // 1. Higher current_bid -> higher rank
  // 2. Same bid amount -> older last_bid_at timestamp first
  const categoryRankMap = useMemo(() => {
    const map: Record<string, number> = {};
    const activeListings = listings.filter(item => item.is_active);

    const byCategory: Record<string, Listing[]> = {};
    for (const item of activeListings) {
      if (!byCategory[item.category_id]) {
        byCategory[item.category_id] = [];
      }
      byCategory[item.category_id].push(item);
    }

    for (const catId of Object.keys(byCategory)) {
      const sorted = byCategory[catId].sort((a, b) => {
        if (b.current_bid !== a.current_bid) {
          return b.current_bid - a.current_bid;
        }
        return new Date(a.last_bid_at).getTime() - new Date(b.last_bid_at).getTime();
      });
      sorted.forEach((item, index) => {
        map[item.id] = index + 1;
      });
    }

    return map;
  }, [listings]);

  if (rankedListings.length === 0) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-16 text-center">
        <div
          className="w-16 h-16 rounded-2xl border flex items-center justify-center mx-auto mb-4 text-emerald-500"
          style={{
            backgroundColor: 'var(--sub-card-bg, #141A20)',
            borderColor: 'var(--border-color, #222A33)'
          }}
        >
          <TrendingUp className="w-8 h-8" />
        </div>
        <h3
          className="text-lg font-bold"
          style={{ color: 'var(--heading-color, #FFFFFF)' }}
        >
          {t('no_listings_title', undefined, 'No active listings in this category yet')}
        </h3>
        <p
          className="text-sm mt-1 max-w-md mx-auto"
          style={{ color: 'var(--muted-text-color, #8A99A8)' }}
        >
          {t('no_listings_desc', undefined, 'Be the first pioneer to claim the top spot in this category and dominate the leaderboard!')}
        </p>
        <button
          onClick={() => openOutbidModal(null)}
          className="mt-5 px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-sm transition-all shadow-lg shadow-emerald-950/40 cursor-pointer"
        >
          {t('claim_category_btn', { amount: `${settings.currency_symbol}${tNum(settings.initial_minimum_bid)}` }, `Claim This Category for ${settings.currency_symbol}${settings.initial_minimum_bid}`)}
        </button>
      </div>
    );
  }

  return (
    <div id="ranking-container" className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-2.5 pb-8">
      {paginatedListings.map((listing, index) => {
        const rank = listing.rank || index + 1;
        const isRank1 = rank === 1;
        const isRank2 = rank === 2;
        const isRank3 = rank === 3;
        const isTop3 = isRank1 || isRank2 || isRank3;

        // Visual background determination
        let cardBg = 'var(--card-color, #13181D)';
        let cardBorder = 'var(--border-color, #222A33)';

        if (isRank1) {
          cardBg = 'var(--rank1-bg, #1C2422)';
          cardBorder = 'var(--rank1-border, #EAB308)';
        } else if (isRank2) {
          cardBg = 'var(--rank2-bg, #171E24)';
          cardBorder = theme === 'dark' ? '#2A3744' : 'var(--border-color, #E2E8F0)';
        } else if (isRank3) {
          cardBg = 'var(--rank3-bg, #141B20)';
          cardBorder = theme === 'dark' ? '#26313C' : 'var(--border-color, #E2E8F0)';
        }

        const localizedCatName = tCategory(
          listing.category_id,
          listing.category_name || categories.find(c => c.id === listing.category_id)?.name || 'General'
        );

        return (
          <React.Fragment key={listing.id}>
            {/* Listing Card */}
            <div
              id={`ranking-item-${listing.id}`}
              className={`group relative rounded-xl sm:rounded-2xl border transition-all duration-200 hover:shadow-lg p-3 sm:p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3.5`}
              style={{
                backgroundColor: cardBg,
                borderColor: cardBorder,
              }}
            >
              {/* Left Details: Rank #, Profile Avatar, Name, Category, Link */}
              <div className="flex items-center gap-3 sm:gap-4 min-w-0 flex-1">
                {/* Rank Number Badge (#1, #2, #3 highlighted, actual numbers shown) */}
                <div
                  className={`w-9 h-9 sm:w-10 sm:h-10 shrink-0 rounded-xl border flex items-center justify-center font-mono font-bold text-sm sm:text-base`}
                  style={{
                    backgroundColor: isTop3 ? 'var(--rank-badge-top-bg)' : 'var(--rank-badge-default-bg)',
                    borderColor: isTop3 ? 'var(--rank-badge-top-border)' : 'var(--rank-badge-default-border)',
                    color: isTop3 ? 'var(--rank-badge-top-text)' : 'var(--rank-badge-default-text)',
                  }}
                >
                  <span>#{tNum(rank)}</span>
                </div>

                {/* 1:1 Profile Image Avatar */}
                <div className="relative shrink-0">
                  <img
                    src={listing.image_url}
                    alt={listing.name}
                    className="w-12 h-12 sm:w-14 sm:h-14 rounded-xl object-cover border shadow-sm"
                    style={{
                      borderColor: 'var(--border-color, #222A33)',
                      backgroundColor: 'var(--sub-card-bg, #0A0D0F)'
                    }}
                    loading="lazy"
                    onError={(e) => {
                      (e.target as HTMLElement).setAttribute(
                        'src',
                        'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200&auto=format&fit=crop&q=80'
                      );
                    }}
                  />
                  {isRank1 && (
                    <span className="absolute -top-1 -right-1 flex h-3 w-3">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-3 w-3 bg-amber-500"></span>
                    </span>
                  )}
                </div>

                {/* Name, External Link */}
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <h3
                      className="text-sm sm:text-base font-bold truncate group-hover:text-emerald-500 transition-colors"
                      style={{ color: 'var(--heading-color, #FFFFFF)' }}
                    >
                      {listing.name}
                    </h3>
                  </div>

                  {/* Compact Facebook & Website URL Buttons */}
                  <div className="flex items-center gap-1.5 mt-1 flex-wrap">
                    {listing.facebook_url && (
                      <a
                        href={listing.facebook_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() => handleClick(listing.id)}
                        className="inline-flex items-center gap-1 px-2 py-0.5 text-[11px] font-medium rounded-md border transition-colors hover:border-blue-500 hover:text-blue-500 cursor-pointer"
                        style={{
                          backgroundColor: 'var(--sub-card-bg, #141A20)',
                          borderColor: 'var(--border-color, #222A33)',
                          color: 'var(--muted-text-color, #8A99A8)'
                        }}
                        title="Visit Facebook"
                      >
                        <Facebook className="w-3 h-3 text-blue-500 shrink-0" />
                        <span>Facebook</span>
                        <ExternalLink className="w-2.5 h-2.5 shrink-0 opacity-70" />
                      </a>
                    )}
                    {listing.website_url && (
                      <a
                        href={listing.website_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() => handleClick(listing.id)}
                        className="inline-flex items-center gap-1 px-2 py-0.5 text-[11px] font-medium rounded-md border transition-colors hover:border-emerald-500 hover:text-emerald-500 cursor-pointer"
                        style={{
                          backgroundColor: 'var(--sub-card-bg, #141A20)',
                          borderColor: 'var(--border-color, #222A33)',
                          color: 'var(--muted-text-color, #8A99A8)'
                        }}
                        title="Visit Website"
                      >
                        <Globe className="w-3 h-3 text-emerald-500 shrink-0" />
                        <span>Website</span>
                      </a>
                    )}
                    {!listing.facebook_url && !listing.website_url && listing.url && (
                      <a
                        href={listing.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() => handleClick(listing.id)}
                        className="inline-flex items-center gap-1 px-2 py-0.5 text-[11px] font-medium rounded-md border transition-colors hover:border-emerald-500 hover:text-emerald-500 cursor-pointer"
                        style={{
                          backgroundColor: 'var(--sub-card-bg, #141A20)',
                          borderColor: 'var(--border-color, #222A33)',
                          color: 'var(--muted-text-color, #8A99A8)'
                        }}
                        title="Visit Website"
                      >
                        <Globe className="w-3 h-3 text-emerald-500 shrink-0" />
                        <span>Website</span>
                      </a>
                    )}
                  </div>

                  {/* Secondary Information Row: Bid Age & Category Rank */}
                  <div
                    className="flex items-center gap-1.5 text-[11px] mt-1 font-medium select-none flex-wrap"
                    style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                  >
                    <span>{formatBidAgeI18n(listing.last_bid_at)}</span>
                    <span className="text-slate-400 dark:text-slate-600 font-bold">•</span>
                    <span className="text-emerald-500 dark:text-emerald-400 font-medium">
                      {t('in_category_rank', { rank: tNum(categoryRankMap[listing.id] || 1), category: localizedCatName }, `#${categoryRankMap[listing.id] || 1} in ${localizedCatName}`)}
                    </span>
                  </div>

                  {/* Tablet ONLY: Micro Stats (Clicks & Heart button on the last line after time & category) */}
                  <div className="hidden sm:flex lg:hidden items-center gap-2 text-xs mt-2">
                    {/* Click counter showing Clicks + number */}
                    <span
                      className="flex items-center px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-lg border font-mono text-[11px] font-medium"
                      style={{
                        backgroundColor: 'var(--sub-card-bg, #141A20)',
                        borderColor: 'var(--border-color, #222A33)',
                        color: 'var(--muted-text-color, #8A99A8)'
                      }}
                      title={`${tNum(listing.clicks)} ${t('clicks_tooltip', undefined, 'total clicks recorded')}`}
                    >
                      {t('clicks_label', undefined, 'Clicks')} {tNum(listing.clicks)}
                    </span>

                    {/* Heart / Support Button */}
                    <button
                      id={`btn-heart-tablet-${listing.id}`}
                      onClick={() => handleHeart(listing.id)}
                      className="flex items-center gap-1 hover:text-rose-500 px-2 py-0.5 sm:py-1 rounded-lg border transition-all cursor-pointer group/heart active:scale-90"
                      style={{
                        backgroundColor: 'var(--sub-card-bg, #141A20)',
                        borderColor: 'var(--border-color, #222A33)',
                        color: 'var(--text-color, #F0F4F8)'
                      }}
                      title={t('support_listing_tooltip', undefined, 'Support this listing')}
                    >
                      <Heart className="w-3 h-3 text-rose-500 group-hover/heart:scale-110 transition-transform fill-rose-500/20" />
                      <span className="font-mono text-[11px] font-medium">{tNum(listing.hearts)}</span>
                    </button>
                  </div>
                </div>
              </div>

              {/* Right Side: Current Bid & OUTBID Button (and on Mobile + Desktop: Clicks & Hearts) */}
              <div
                className="flex items-center justify-between sm:justify-end gap-3 sm:gap-4 border-t sm:border-t-0 pt-2 sm:pt-0 shrink-0"
                style={{ borderColor: 'var(--border-color, #222A33)' }}
              >
                {/* Micro Stats: Clicks & Hearts (Mobile & Desktop) */}
                <div className="flex sm:hidden lg:flex items-center gap-2 text-xs">
                  {/* Click counter showing Clicks + number */}
                  <span
                    className="flex items-center px-2 py-1 sm:px-2.5 sm:py-1 rounded-lg border font-mono text-[11px] font-medium"
                    style={{
                      backgroundColor: 'var(--sub-card-bg, #141A20)',
                      borderColor: 'var(--border-color, #222A33)',
                      color: 'var(--muted-text-color, #8A99A8)'
                    }}
                    title={`${tNum(listing.clicks)} ${t('clicks_tooltip', undefined, 'total clicks recorded')}`}
                  >
                    {t('clicks_label', undefined, 'Clicks')} {tNum(listing.clicks)}
                  </span>

                  {/* Heart / Support Button */}
                  <button
                    id={`btn-heart-${listing.id}`}
                    onClick={() => handleHeart(listing.id)}
                    className="flex items-center gap-1 hover:text-rose-500 px-2 py-1 sm:px-2.5 sm:py-1 rounded-lg border transition-all cursor-pointer group/heart active:scale-90"
                    style={{
                      backgroundColor: 'var(--sub-card-bg, #141A20)',
                      borderColor: 'var(--border-color, #222A33)',
                      color: 'var(--text-color, #F0F4F8)'
                    }}
                    title={t('support_listing_tooltip', undefined, 'Support this listing')}
                  >
                    <Heart className="w-3 h-3 text-rose-500 group-hover/heart:scale-110 transition-transform fill-rose-500/20" />
                    <span className="font-mono text-[11px] font-medium">{tNum(listing.hearts)}</span>
                  </button>
                </div>

                {/* Bid Amount & Outbid Action */}
                <div className="flex items-center gap-2.5">
                  <div className="text-right">
                    <div
                      className="text-[10px] uppercase tracking-wider font-semibold"
                      style={{ color: 'var(--muted-text-color, #8A99A8)' }}
                    >
                      {t('current_bid_label', undefined, texts.current_bid_label || 'Current Bid')}
                    </div>
                    <div className="text-sm sm:text-base font-black font-mono text-emerald-500 dark:text-emerald-400">
                      {settings.currency_symbol}{tNum(listing.current_bid)}
                    </div>
                  </div>

                  <button
                    id={`btn-outbid-${listing.id}`}
                    onClick={() => openOutbidModal(listing)}
                    className="px-3.5 sm:px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs sm:text-sm tracking-wide shadow-md shadow-emerald-950/30 hover:scale-[1.03] active:scale-[0.97] transition-all cursor-pointer whitespace-nowrap"
                  >
                    {t('outbid_btn_text', undefined, texts.outbid_btn_text || 'OUTBID')}
                  </button>
                </div>
              </div>
            </div>

            {/* Separators: Top 3, Top 10, Top 20 */}
            {rank === 3 && rankedListings.length > 3 && (
              <div className="py-2.5 flex items-center gap-3">
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
                <span
                  className="text-[11px] font-mono font-bold tracking-widest text-amber-500 uppercase px-3 py-0.5 rounded-full border shadow-sm"
                  style={{
                    backgroundColor: 'var(--card-color, #13181D)',
                    borderColor: 'var(--border-color, #222A33)'
                  }}
                >
                  {t('top_3_badge', undefined, 'TOP 3')}
                </span>
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
              </div>
            )}

            {rank === 10 && rankedListings.length > 10 && (
              <div className="py-2.5 flex items-center gap-3">
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
                <span
                  className="text-[11px] font-mono font-bold tracking-widest uppercase px-3 py-0.5 rounded-full border"
                  style={{
                    backgroundColor: 'var(--card-color, #13181D)',
                    borderColor: 'var(--border-color, #222A33)',
                    color: 'var(--muted-text-color, #8A99A8)'
                  }}
                >
                  {t('top_10_badge', undefined, 'TOP 10')}
                </span>
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
              </div>
            )}

            {rank === 20 && rankedListings.length > 20 && (
              <div className="py-2.5 flex items-center gap-3">
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
                <span
                  className="text-[11px] font-mono font-bold tracking-widest uppercase px-3 py-0.5 rounded-full border"
                  style={{
                    backgroundColor: 'var(--card-color, #13181D)',
                    borderColor: 'var(--border-color, #222A33)',
                    color: 'var(--muted-text-color, #8A99A8)'
                  }}
                >
                  {t('top_20_badge', undefined, 'TOP 20')}
                </span>
                <div className="flex-1 h-px" style={{ backgroundColor: 'var(--border-color, #222A33)' }}></div>
              </div>
            )}
          </React.Fragment>
        );
      })}

      {/* Pagination Controls */}
      {totalPages > 1 && (
        <div id="ranking-pagination" className="pt-6 pb-2 flex items-center justify-between gap-4 text-xs">
          <span
            className="font-mono"
            style={{ color: 'var(--muted-text-color, #8A99A8)' }}
          >
            {t('showing_pagination', {
              start: tNum((state.currentPage - 1) * settings.pagination_size + 1),
              end: tNum(Math.min(state.currentPage * settings.pagination_size, rankedListings.length)),
              total: tNum(rankedListings.length)
            }, `Showing ${(state.currentPage - 1) * settings.pagination_size + 1}–${Math.min(state.currentPage * settings.pagination_size, rankedListings.length)} of ${rankedListings.length}`)}
          </span>

          <div className="flex items-center gap-1.5">
            <button
              onClick={() => setCurrentPage(Math.max(1, state.currentPage - 1))}
              disabled={state.currentPage === 1}
              className="p-2 rounded-lg border disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer transition-colors"
              style={{
                backgroundColor: 'var(--sub-card-bg, #141A20)',
                borderColor: 'var(--border-color, #222A33)',
                color: 'var(--text-color, #F0F4F8)'
              }}
            >
              <ChevronLeft className="w-4 h-4" />
            </button>

            {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
              <button
                key={page}
                onClick={() => setCurrentPage(page)}
                className={`w-8 h-8 rounded-lg font-mono font-semibold transition-all cursor-pointer ${
                  state.currentPage === page
                    ? 'bg-emerald-600 text-white'
                    : 'border hover:opacity-90'
                }`}
                style={
                  state.currentPage === page
                    ? {}
                    : {
                        backgroundColor: 'var(--sub-card-bg, #141A20)',
                        borderColor: 'var(--border-color, #222A33)',
                        color: 'var(--muted-text-color, #8A99A8)'
                      }
                }
              >
                {tNum(page)}
              </button>
            ))}

            <button
              onClick={() => setCurrentPage(Math.min(totalPages, state.currentPage + 1))}
              disabled={state.currentPage === totalPages}
              className="p-2 rounded-lg border disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer transition-colors"
              style={{
                backgroundColor: 'var(--sub-card-bg, #141A20)',
                borderColor: 'var(--border-color, #222A33)',
                color: 'var(--text-color, #F0F4F8)'
              }}
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
