import { Link } from 'react-router-dom'
import { ArrowRight } from 'lucide-react'
import AuthGate from '../components/AuthGate'
import { useAuth } from '../context/AuthContext'
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 Dashboard() {
  const { user } = useAuth()
  const { polls } = usePolls()

  if (!user) {
    return <AuthGate />
  }

  return (
    <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.16em] text-brand-500">Live Board</p>
          <h1 className="brand-heading mt-1 text-3xl font-bold text-brand-900">Finalist Leaderboard</h1>
          <p className="mt-2 max-w-2xl text-sm text-brand-700/75">
            Monitor live standings as the tally updates throughout the voting period.
          </p>
        </div>
      </div>

      {polls.length === 0 ? (
        <p className="mt-10 rounded-3xl border border-dashed border-brand-300 bg-white p-8 text-center text-brand-700">
          No polls yet. Check back soon!
        </p>
      ) : (
        <div className="mt-8 space-y-6">
          {polls.map((poll) => {
            const total = poll.options.reduce((sum, o) => sum + o.votes, 0)
            const ranked = [...poll.options].sort((a, b) => b.votes - a.votes)

            return (
              <section key={poll.id} className="rounded-3xl border border-brand-200 bg-white p-6 shadow-sm">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <div className="flex items-center gap-2">
                      <h2 className="brand-heading text-xl font-bold">{poll.title}</h2>
                      <span
                        className={`rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${
                          poll.status === 'open'
                            ? 'bg-emerald-100 text-green-700'
                            : 'bg-brand-100 text-brand-700'
                        }`}
                      >
                        {poll.status}
                      </span>
                    </div>
                    <p className="mt-1 text-sm text-brand-700/70">{poll.description}</p>
                  </div>
                  <div className="flex gap-2">
                    <Link
                      to={`/poll/${poll.id}`}
                      className="inline-flex items-center gap-2 rounded-full bg-brand-700 px-4 py-2 text-sm font-semibold text-white"
                    >
                      Cast Ballot <ArrowRight className="h-4 w-4" />
                    </Link>
                    <Link
                      to={`/results/${poll.id}`}
                      className="inline-flex items-center rounded-full border border-brand-300 px-4 py-2 text-sm font-medium text-accent-600"
                    >
                      View Results
                    </Link>
                  </div>
                </div>

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