'use client'

import { useEffect, Suspense } from 'react'
import { useAuth } from '@/lib/AuthContext'
import { useRouter, useSearchParams } from 'next/navigation'
import { Crown, Zap, Check, Loader2 } from 'lucide-react'

const TIERS = [
  {
    name: 'Free',
    price: '$0',
    period: 'forever',
    priceId: null,
    features: [
      'Access to Souq marketplace',
      'Nur AI coaching (basic)',
      'Forum access',
      'FLH wallet & cashouts',
    ],
    cta: 'Get Started',
    href: '/souq',
    highlighted: false,
    icon: Zap,
  },
  {
    name: 'Premium',
    price: '$5',
    period: '/month',
    priceId: 'price_premium_monthly',
    features: [
      'Everything in Free',
      'Nur AI unlimited coaching',
      'Scholar personas (Al-Ghazali, Ibn Abbas, Rabia)',
      'Priority support',
    ],
    cta: 'Subscribe',
    highlighted: true,
    icon: Crown,
  },
  {
    name: 'Pro',
    price: '$20',
    period: '/month',
    priceId: 'price_pro_monthly',
    features: [
      'Everything in Premium',
      'Early access to new features',
      'Custom integrations',
      'Direct line to the team',
    ],
    cta: 'Subscribe',
    highlighted: false,
    icon: Crown,
  },
]

function UpgradeContent() {
  const { token, loading: authLoading } = useAuth()
  const router = useRouter()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (!authLoading && !token) router.push('/login')
  }, [token, authLoading, router])

  useEffect(() => {
    const upgrade = searchParams.get('upgrade')
    const canceled = searchParams.get('canceled')
    if (upgrade === 'success') {
      alert('Welcome to Premium! Your account has been upgraded.')
      router.replace('/upgrade')
    } else if (canceled === 'true') {
      alert('Checkout canceled. Please try again if you changed your mind.')
      router.replace('/upgrade')
    }
  }, [searchParams, router])

  const handleSubscribe = async (priceId: string) => {
    if (!token) return
    try {
      const res = await fetch('/api/upgrade/create-checkout', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ priceId }),
      })
      const data = await res.json()
      if (res.ok && data.url) {
        window.location.href = data.url
      } else {
        alert(data.error || 'Failed to start checkout')
      }
    } catch {
      alert('Something went wrong. Please try again.')
    }
  }

  if (authLoading) return <div className="p-8 text-center text-gray-500">Loading...</div>
  if (!token) return null

  return (
    <div className="max-w-6xl mx-auto p-4 sm:p-6 space-y-8">
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold text-[#D4AF37]">Upgrade Your Experience</h1>
        <p className="text-gray-400">Choose the plan that fits your journey</p>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 items-start">
        {TIERS.map((tier) => {
          const Icon = tier.icon
          return (
            <div
              key={tier.name}
              className={`relative rounded-xl p-6 space-y-5 transition ${
                tier.highlighted
                  ? 'bg-gradient-to-b from-[#D4AF37]/10 to-[#111118] border-2 border-[#D4AF37] shadow-lg shadow-[#D4AF37]/5 scale-105'
                  : 'bg-[#111118] border border-gray-800 hover:border-gray-700'
              }`}
            >
              {tier.highlighted && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-[#D4AF37] text-[#0a0a0f] text-xs font-bold px-3 py-1 rounded-full">
                  BEST VALUE
                </div>
              )}
              <div className="text-center space-y-2">
                <Icon size={32} className={tier.highlighted ? 'text-[#D4AF37] mx-auto' : 'text-gray-500 mx-auto'} />
                <h2 className="text-xl font-bold">{tier.name}</h2>
                <div>
                  <span className="text-3xl font-bold">{tier.price}</span>
                  <span className="text-gray-500 text-sm">{tier.period}</span>
                </div>
              </div>
              <ul className="space-y-3">
                {tier.features.map((f) => (
                  <li key={f} className="flex items-start gap-2 text-sm text-gray-300">
                    <Check size={16} className="text-[#D4AF37] mt-0.5 shrink-0" />
                    <span>{f}</span>
                  </li>
                ))}
              </ul>
              {tier.priceId ? (
                <button
                  onClick={() => handleSubscribe(tier.priceId!)}
                  className="w-full bg-[#D4AF37] text-[#0a0a0f] py-2.5 rounded-lg font-bold hover:bg-[#C9A84C] transition flex items-center justify-center gap-2"
                >
                  <Loader2 size={16} className="animate-spin hidden" />
                  {tier.cta}
                </button>
              ) : (
                <button
                  onClick={() => router.push(tier.href)}
                  className="w-full border border-gray-700 text-gray-300 py-2.5 rounded-lg font-semibold hover:bg-gray-800 transition"
                >
                  {tier.cta}
                </button>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default function UpgradePage() {
  return (
    <Suspense fallback={<div className="p-8 text-center text-gray-500">Loading...</div>}>
      <UpgradeContent />
    </Suspense>
  )
}
