import { useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import FinalistCard from '../components/FinalistCard'
import { useAuth } from '../context/AuthContext'
import { usePolls } from '../context/PollContext'

export default function Poll() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { user } = useAuth()
  const { getPoll, castVote, hasVoted } = usePolls()
  const poll = getPoll(id)
  const [selected, setSelected] = useState(null)
  const [message, setMessage] = useState('')
  const [busy, setBusy] = useState(false)

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

  const alreadyVoted = user ? hasVoted(poll.id, user.id) : false

  const submit = () => {
    if (!user) {
      navigate('/login')
      return
    }
    if (!selected) {
      setMessage('Select a finalist before casting your ballot.')
      return
    }
    setBusy(true)
    const result = castVote(poll.id, selected, user.id)
    setBusy(false)
    if (!result.ok) {
      setMessage(result.error)
      return
    }
    setMessage('Your vote has been recorded! Thank you for participating.')
    setTimeout(() => navigate(`/results/${poll.id}`), 900)
  }

  return (
    <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
      <p className="text-xs font-semibold uppercase tracking-[0.16em] text-brand-500">Cast Ballot</p>
      <h1 className="brand-heading mt-2 text-3xl font-bold text-brand-900">{poll.title}</h1>
      <p className="mt-2 max-w-2xl text-sm text-brand-800/80">{poll.description}</p>

      {poll.status !== 'open' && (
        <p className="mt-4 rounded-2xl border border-brand-200 bg-brand-50 px-4 py-3 text-sm text-brand-700">
          This poll is closed. You can still view results.
        </p>
      )}

      <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
        {poll.options.map((option) => (
          <FinalistCard
            key={option.id}
            option={option}
            selected={selected === option.id}
            onSelect={() => setSelected(option.id)}
            showVotes={false}
            showFollow={false}
          />
        ))}
      </div>

      <div className="mt-8 flex flex-col gap-3 sm:flex-row sm:items-center">
        <button
          type="button"
          disabled={busy || alreadyVoted || poll.status !== 'open'}
          onClick={submit}
          className="inline-flex items-center justify-center rounded-full bg-brand-700 px-6 py-3 text-sm font-semibold text-white transition hover:bg-brand-800 disabled:opacity-50"
        >
          {alreadyVoted ? 'Vote already cast' : 'Cast Vote'}
        </button>
        <Link to={`/results/${poll.id}`} className="text-sm font-medium text-accent-600 hover:underline">
          View Results
        </Link>
      </div>

      {message && <p className="mt-4 text-sm font-medium text-brand-700">{message}</p>}
      {!user && (
        <p className="mt-3 text-sm text-brand-700/75">
          Sign in with a verified identity before submitting.{' '}
          <Link to="/login" className="font-semibold text-brand-700 underline">
            Sign in
          </Link>
        </p>
      )}
    </div>
  )
}
