import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useToast } from '../context/ToastContext'
import { toggleSubscription } from '../api/endpoints'
import { Check } from './icons'

/** Subscribe / Subscribed toggle for the site channel. */
export default function SubscribeButton({ compact = false }) {
  const { user, isAuthenticated, setUser } = useAuth()
  const toast = useToast()
  const navigate = useNavigate()
  const [busy, setBusy] = useState(false)

  const subscribed = !!user?.subscribed

  const onClick = async (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (!isAuthenticated) {
      navigate('/login')
      return
    }
    setBusy(true)
    try {
      const { subscribed } = await toggleSubscription()
      setUser({ ...user, subscribed })
      toast.success(subscribed ? 'Subscribed!' : 'Unsubscribed')
    } catch {
      toast.error('Something went wrong')
    } finally {
      setBusy(false)
    }
  }

  const size = compact ? 'px-2.5 py-1 text-[11px]' : 'px-4 py-1.5 text-sm'

  return (
    <button
      onClick={onClick}
      disabled={busy}
      className={`shrink-0 rounded-full font-bold transition-all duration-200 disabled:opacity-60 ${size} ${
        subscribed
          ? 'bg-gray-200 text-gray-600 ring-1 ring-gray-300 hover:bg-gray-300 dark:bg-gray-800 dark:text-gray-300 dark:ring-gray-700'
          : 'bg-brand-gradient text-white shadow-sm shadow-[var(--brand)]/30 hover:scale-[1.03] hover:opacity-95'
      }`}
    >
      {subscribed ? (
        <span className="inline-flex items-center gap-1">
          <Check width={12} height={12} /> Subscribed
        </span>
      ) : (
        'Subscribe'
      )}
    </button>
  )
}
