import React, { useMemo, useState } from 'react'
import WorldAnalyticsSummaryCard from './WorldAnalyticsSummaryCard'

function formatNumber(value) {
  return new Intl.NumberFormat('en-US').format(Number(value || 0))
}

function formatPercent(value) {
  return `${Math.round(Number(value || 0) * 100)}%`
}

function metricValue(row, key) {
  switch (key) {
    case 'conversion':
      return formatPercent(row.view_to_submission_conversion)
    case 'reward_grants':
      return `${formatNumber(row.reward_grants)} grants`
    case 'submissions':
      return `${formatNumber(row.submissions)} submissions`
    case 'unique_visitors':
      return `${formatNumber(row.unique_visitors)} visitors`
    case 'views':
    default:
      return `${formatNumber(row.views)} views`
  }
}

function LeaderboardColumn({ title, rows = [], metricKey = 'views' }) {
  return (
    <div className="rounded-[24px] border border-white/10 bg-black/20 p-5">
      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{title}</div>
      <div className="mt-4 grid gap-3">
        {rows.length > 0 ? rows.map((row, index) => (
          <a key={`${metricKey}-${row.world_id}`} href={row.edit_url} className="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 transition hover:border-white/20 hover:bg-white/[0.05]">
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0">
                <div className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">#{index + 1}</div>
                <div className="mt-1 truncate text-sm font-semibold text-white">{row.title}</div>
                <div className="mt-1 text-xs text-slate-400">/{row.slug}{row.edition_year ? ` • ${row.edition_year}` : ''}</div>
              </div>
              <div className="shrink-0 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100">{metricValue(row, metricKey)}</div>
            </div>
          </a>
        )) : <div className="rounded-2xl border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm text-slate-400">No activity recorded for this range yet.</div>}
      </div>
    </div>
  )
}

export default function WorldAnalyticsPortfolioPanel({ analytics = null }) {
  const rangeOptions = Array.isArray(analytics?.range_options) ? analytics.range_options : []
  const defaultRange = analytics?.default_range || rangeOptions[0]?.value || '30d'
  const [selectedRange, setSelectedRange] = useState(defaultRange)

  const range = useMemo(() => analytics?.ranges?.[selectedRange] || {}, [analytics, selectedRange])
  const summary = range.summary || {}
  const leaderboards = range.leaderboards || {}

  if (!analytics || rangeOptions.length === 0) {
    return null
  }

  const summaryCards = [
    {
      label: 'Tracked Worlds',
      value: formatNumber(summary.tracked_worlds),
      hint: 'Worlds with activity in this range.',
    },
    {
      label: 'Views',
      value: formatNumber(summary.views),
      hint: 'Portfolio traffic across all worlds.',
      tone: 'accent',
    },
    {
      label: 'Promotion Impressions',
      value: formatNumber(summary.promotion_impressions),
      hint: 'Observed spotlight, rail, and upload placements.',
    },
    {
      label: 'Submissions',
      value: formatNumber(summary.submissions),
      hint: `Rewards granted: ${formatNumber(summary.reward_grants)}`,
      tone: 'emerald',
    },
  ]

  return (
    <section className="rounded-[28px] border border-white/10 bg-white/[0.03] p-5">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Portfolio analytics</div>
          <h2 className="mt-2 text-2xl font-semibold tracking-[-0.03em] text-white">Cross-world performance</h2>
          <p className="mt-2 max-w-3xl text-sm leading-6 text-slate-400">Use this snapshot to see which worlds are drawing traffic, driving participation, and converting attention into submissions.</p>
        </div>
        <div className="inline-flex flex-wrap gap-2 rounded-full border border-white/10 bg-black/20 p-1">
          {rangeOptions.map((option) => {
            const active = option.value === selectedRange
            return (
              <button
                key={option.value}
                type="button"
                onClick={() => setSelectedRange(option.value)}
                className={`rounded-full px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${active ? 'bg-sky-400/15 text-sky-100' : 'text-slate-400 hover:text-white'}`}
              >
                {option.label}
              </button>
            )
          })}
        </div>
      </div>

      <div className="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        {summaryCards.map((card) => <WorldAnalyticsSummaryCard key={card.label} {...card} />)}
      </div>

      <div className="mt-6 grid gap-4 xl:grid-cols-2">
        <LeaderboardColumn title="Top by views" rows={leaderboards.views || []} metricKey="views" />
        <LeaderboardColumn title="Top by unique visitors" rows={leaderboards.unique_visitors || []} metricKey="unique_visitors" />
        <LeaderboardColumn title="Top by submissions" rows={leaderboards.submissions || []} metricKey="submissions" />
        <LeaderboardColumn title="Best view-to-submit conversion" rows={leaderboards.conversion || []} metricKey="conversion" />
      </div>
    </section>
  )
}