'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { api } from '@/lib/api'
import { useAuth } from '@/lib/auth'
import type { SubscriptionTier } from '@/lib/types'
import { money } from '@/lib/format'

const LABELS: Record<string, string> = {
  category: 'shop categories',
  vendor: 'partner shops',
  product: 'selected products',
  provider_type: 'consultations',
}
function benefitLabel(appliesTo: string): string {
  return LABELS[appliesTo] ?? appliesTo
}

export default function PlansPage() {
  const router = useRouter()
  const { user } = useAuth()
  const [tiers, setTiers] = useState<SubscriptionTier[]>([])
  const [loading, setLoading] = useState(true)
  const [busy, setBusy] = useState<number | null>(null)
  const [msg, setMsg] = useState<string | null>(null)

  useEffect(() => {
    api.get<{ data: SubscriptionTier[] } | SubscriptionTier[]>('/subscription/tiers')
      .then((r) => setTiers((r as { data?: SubscriptionTier[] }).data ?? (r as SubscriptionTier[])))
      .catch(() => setTiers([]))
      .finally(() => setLoading(false))
  }, [])

  const subscribe = async (tier: SubscriptionTier) => {
    if (!user) { router.push('/login?redirect=/plans'); return }
    setBusy(tier.id); setMsg(null)
    try {
      const res = await api.post<{ payment?: { checkout_url?: string | null; status?: string } }>('/subscription/subscribe', { subscription_tier_id: tier.id, source: 'web' }, true)
      const url = res.payment?.checkout_url
      if (url) {
        window.location.href = url
        return
      }
      setMsg(`You're subscribed to ${tier.name}.`)
    } catch {
      setMsg('Could not complete subscription. Please try again.')
    } finally { setBusy(null) }
  }

  return (
    <div className="container-x py-10">
      <div className="text-center">
        <h1 className="text-3xl font-extrabold">Membership plans</h1>
        <p className="mt-2 text-muted">Unlock gym access, consultations and member-only perks.</p>
      </div>

      {msg && <div className="mx-auto mt-6 max-w-md rounded-lg bg-brand-soft p-3 text-center text-sm text-brand-dark">{msg}</div>}

      <div className="mt-8 grid gap-5 md:grid-cols-3">
        {loading ? (
          Array.from({ length: 3 }).map((_, i) => <div key={i} className="card h-80 animate-pulse bg-soft" />)
        ) : tiers.length === 0 ? (
          <div className="col-span-full card p-12 text-center text-muted">No plans available right now.</div>
        ) : (
          tiers.map((t, i) => (
            <div key={t.id} className={`card flex flex-col p-6 ${i === 1 ? 'border-brand ring-1 ring-brand' : ''}`}>
              {i === 1 && <span className="tag tag-otc mb-2 self-start">Popular</span>}
              <h2 className="text-lg font-bold">{t.name}</h2>
              <div className="mt-2 text-3xl font-extrabold">{money(t.price)}<span className="text-sm font-normal text-muted">/{t.interval || t.billing_period || 'month'}</span></div>
              {t.description && <p className="mt-2 text-sm text-muted">{t.description}</p>}
              <ul className="mt-4 flex-1 space-y-2 text-sm">
                <li className="flex gap-2">
                  <span className="text-accent">✓</span>
                  {t.gym_access === 'all'
                    ? 'Access to all gyms'
                    : t.gym_access === 'selected'
                      ? `Access to ${t.gyms?.length ?? 0} gym${(t.gyms?.length ?? 0) === 1 ? '' : 's'}`
                      : 'No gym access'}
                </li>
                {typeof t.checkin_limit === 'number' && (
                  <li className="flex gap-2"><span className="text-accent">✓</span>{t.checkin_limit} check-ins / month</li>
                )}
                {(t.checkin_limit === null || t.checkin_limit === undefined) && t.gym_access !== 'none' && (
                  <li className="flex gap-2"><span className="text-accent">✓</span>Unlimited check-ins</li>
                )}
                {(t.benefits ?? []).filter((b) => b.applies_to !== 'check_in' && b.discount_percent).map((b, bi) => (
                  <li key={bi} className="flex gap-2">
                    <span className="text-accent">✓</span>
                    {`${Number(b.discount_percent)}% off ${benefitLabel(b.applies_to)}`}
                  </li>
                ))}
              </ul>
              <button onClick={() => subscribe(t)} disabled={busy === t.id} className={`btn mt-6 w-full ${i === 1 ? 'btn-primary' : 'btn-brand'} disabled:opacity-60`}>
                {busy === t.id ? 'Processing…' : 'Choose plan'}
              </button>
            </div>
          ))
        )}
      </div>
    </div>
  )
}
