import React from 'react'
import ProfileWorldStatsRow from './ProfileWorldStatsRow'
import ProfileWorldRecognitionBadge from './ProfileWorldRecognitionBadge'

function formatDate(value) {
  if (!value) return null

  try {
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) return null

    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  } catch {
    return null
  }
}

export default function ProfileWorldHistorySummary({ history }) {
  const summary = history?.summary || {}
  const recent = summary?.most_recent_world_activity
  const recentRecognition = recent?.primary_recognition || (recent?.recognition_label
    ? { key: String(recent.recognition_label).toLowerCase().replace(/\s+/g, '_'), label: recent.recognition_label, tone: 'sky' }
    : null)

  return (
    <div className="space-y-4">
      <ProfileWorldStatsRow summary={summary} />

      {recent ? (
        <div className="rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_18px_46px_rgba(2,6,23,0.18)] md:p-6">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <div className="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500">Most Recent World Activity</div>
              <div className="mt-2 text-xl font-semibold tracking-[-0.02em] text-white">{recent.world_title}</div>
              <div className="mt-2 flex flex-wrap items-center gap-2">
                {recentRecognition ? <ProfileWorldRecognitionBadge recognition={recentRecognition} isPrimary /> : null}
                {formatDate(recent.occurred_at) ? <span className="text-xs text-slate-400">{formatDate(recent.occurred_at)}</span> : null}
              </div>
            </div>
            {recent.world_url ? (
              <a
                href={recent.world_url}
                className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
              >
                <i className="fa-solid fa-arrow-up-right-from-square text-xs" />
                View world
              </a>
            ) : null}
          </div>
        </div>
      ) : null}
    </div>
  )
}