import { Link, useParams } from 'react-router-dom'
import { usePolls } from '../context/PollContext'

function formatVotes(n) {
  if (n >= 1000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
  return String(n)
}

export default function Results() {
  const { id } = useParams()
  const { getPoll } = usePolls()
  const poll = getPoll(id)

  if (!poll) {
    return (
      <div className="mx-auto max-w-xl px-4 py-20 text-center">
        <h1 className="brand-heading text-2xl font-bold">Results not available.</h1>
        <Link to="/dashboard" className="mt-4 inline-block text-brand-600 underline">
          Back to Leaderboard
        </Link>
      </div>
    )
  }

  const total = poll.options.reduce((sum, o) => sum + o.votes, 0)
  const ranked = [...poll.options].sort((a, b) => b.votes - a.votes)

  return (
    <div className="mx-auto max-w-3xl px-4 py-10 sm:px-6 lg:px-8">
      <p className="text-xs font-semibold uppercase tracking-[0.16em] text-brand-500">Results</p>
      <h1 className="brand-heading mt-2 text-3xl font-bold">{poll.title}</h1>
      <p className="mt-2 text-sm text-brand-700/75">Total ballots recorded: {formatVotes(total)}</p>

      <div className="mt-8 space-y-4">
        {ranked.map((option, index) => {
          const pct = total > 0 ? Math.round((option.votes / total) * 100) : 0
          return (
            <div key={option.id} className="rounded-3xl border border-brand-200 bg-white p-5 shadow-sm">
              <div className="flex items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                  <span className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-700 text-sm font-bold text-white">
                    {index + 1}
                  </span>
                  <div>
                    <p className="font-semibold">{option.name}</p>
                    <p className="text-xs text-brand-700/70">{option.title}</p>
                  </div>
                </div>
                <p className="text-sm font-semibold">
                  {formatVotes(option.votes)} · {pct}%
                </p>
              </div>
              <div className="mt-3 h-2.5 overflow-hidden rounded-full bg-brand-100">
                <div className="h-full rounded-full bg-brand-500" style={{ width: `${pct}%` }} />
              </div>
            </div>
          )
        })}
      </div>

      <div className="mt-8 flex gap-3">
        <Link to="/dashboard" className="rounded-full border border-brand-300 px-4 py-2 text-sm font-semibold">
          Back to Leaderboard
        </Link>
        {poll.status === 'open' && (
          <Link to={`/poll/${poll.id}`} className="rounded-full bg-brand-700 px-4 py-2 text-sm font-semibold text-white">
            Cast Ballot
          </Link>
        )}
      </div>
    </div>
  )
}
