'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Check, ArrowRight, Zap, TrendingUp, Crown, Loader2, Clock, X, AlertCircle, Shield } from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

const tiers = [
  {
    id: 'scout',
    name: 'Scout',
    icon: Zap,
    price: '0',
    period: '',
    description: 'Taste the system. No commitment.',
    features: [
      { text: 'Market Feed', highlight: false, available: true, sublabel: 'Raw' },
      { text: 'Alert Speed', highlight: false, available: true, sublabel: 'Daily' },
      { text: '5 Watchlist Domains', highlight: false, available: true },
      { text: '5 Portfolio Domains', highlight: false, available: true },
      { text: 'Listings', highlight: false, available: false },
      { text: 'Sniper Alerts', highlight: false, available: false },
      { text: 'Pounce Score', highlight: false, available: true, sublabel: 'Basic' },
      { text: 'TLD Intel', highlight: false, available: true, sublabel: 'Public' },
    ],
    cta: 'Enter Terminal',
    highlighted: false,
    badge: null,
    isPaid: false,
  },
  {
    id: 'trader',
    name: 'Trader',
    icon: TrendingUp,
    price: '9',
    period: '/mo',
    description: 'Cut noise. Move faster.',
    features: [
      { text: 'Market Feed', highlight: true, available: true, sublabel: 'Curated' },
      { text: 'Alert Speed', highlight: true, available: true, sublabel: 'Hourly' },
      { text: '50 Watchlist Domains', highlight: true, available: true },
      { text: '50 Portfolio Domains', highlight: true, available: true },
      { text: '10 Listings', highlight: true, available: true, sublabel: '0% Fee' },
      { text: '10 Sniper Alerts', highlight: true, available: true },
      { text: 'Pounce Score', highlight: true, available: true, sublabel: 'Full' },
      { text: 'TLD Intel', highlight: true, available: true, sublabel: 'Renewal Prices' },
      { text: 'Yield Preview', highlight: true, available: true, sublabel: 'Landing only' },
    ],
    cta: 'Upgrade to Trader',
    highlighted: true,
    badge: 'Best Value',
    isPaid: true,
  },
  {
    id: 'tycoon',
    name: 'Tycoon',
    icon: Crown,
    price: '29',
    period: '/mo',
    description: 'Full firepower. No limits.',
    features: [
      { text: 'Market Feed', highlight: true, available: true, sublabel: 'Priority' },
      { text: 'Alert Speed', highlight: true, available: true, sublabel: '5 min' },
      { text: 'Unlimited Watchlist', highlight: true, available: true },
      { text: 'Unlimited Portfolio', highlight: true, available: true },
      { text: 'Unlimited Listings', highlight: true, available: true, sublabel: 'Featured' },
      { text: '50 Sniper Alerts', highlight: true, available: true },
      { text: 'Yield Active', highlight: true, available: true, sublabel: 'Full routing' },
      { text: 'Score + SEO Data', highlight: true, available: true },
      { text: 'API + Webhooks', highlight: true, available: true },
    ],
    cta: 'Go Tycoon',
    highlighted: false,
    badge: 'Full Power',
    isPaid: true,
  },
]

const comparisonFeatures = [
  { name: 'Market Feed', scout: 'Raw', trader: 'Curated', tycoon: 'Priority + Early' },
  { name: 'Alert Speed', scout: 'Daily', trader: 'Hourly', tycoon: 'Every 5 min' },
  { name: 'Watchlist', scout: '5 Domains', trader: '50 Domains', tycoon: 'Unlimited' },
  { name: 'Portfolio', scout: '5 Domains', trader: '50 Domains', tycoon: 'Unlimited' },
  { name: 'Listings', scout: '—', trader: '10 (0% Fee)', tycoon: 'Unlimited + Featured' },
  { name: 'Sniper Alerts', scout: '—', trader: '10', tycoon: '50' },
  { name: 'Valuation', scout: 'Basic Score', trader: 'Pounce Score', tycoon: 'Score + SEO' },
  { name: 'TLD Intel', scout: 'Public', trader: 'Renewal Prices', tycoon: 'Full History' },
  { name: 'Yield', scout: '—', trader: 'Preview', tycoon: 'Active Routing' },
  { name: 'API Access', scout: '—', trader: '—', tycoon: '✓' },
]

const faqs = [
  {
    q: 'How fast will I know when a domain drops?',
    a: 'Depends on your plan. Scout: daily. Trader: hourly. Tycoon: every 5 minutes. When it drops, you\'ll know.',
  },
  {
    q: 'What\'s domain valuation?',
    a: 'Our algorithm scores domains on length, TLD value, keywords, and brandability. Know what a domain is worth before you buy.',
  },
  {
    q: 'Can I track domains I already own?',
    a: 'Absolutely. Trader and Tycoon plans include portfolio tracking. See value changes, renewal dates, and ROI at a glance.',
  },
  {
    q: 'Can I upgrade or downgrade anytime?',
    a: 'Absolutely. You can change your plan at any time. Upgrades take effect immediately, and downgrades apply at the next billing cycle.',
  },
  {
    q: 'Is there a money-back guarantee?',
    a: 'Yes. We offer a 14-day money-back guarantee on all paid plans—no questions asked.',
  },
]

export default function PricingPage() {
  const router = useRouter()
  const { checkAuth, isLoading, isAuthenticated } = useStore()
  const [loadingPlan, setLoadingPlan] = useState<string | null>(null)
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null)
  const [showCancelledBanner, setShowCancelledBanner] = useState(false)

  useEffect(() => {
    checkAuth()
    
    // Check if user cancelled checkout
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search)
      if (params.get('cancelled') === 'true') {
        setShowCancelledBanner(true)
        // Clean up URL
        window.history.replaceState({}, '', '/pricing')
      }
    }
  }, [checkAuth])

  const handleSelectPlan = async (planId: string, isPaid: boolean) => {
    if (!isAuthenticated) {
      router.push(`/register?redirect=/pricing`)
      return
    }

    if (!isPaid) {
      router.push('/terminal/hunt')
      return
    }

    setLoadingPlan(planId)
    try {
      const response = await api.createCheckoutSession(
        planId,
        `${window.location.origin}/terminal/welcome?plan=${planId}`,
        `${window.location.origin}/pricing?cancelled=true`
      )
      window.location.href = response.checkout_url
    } catch (error) {
      console.error('Failed to create checkout:', error)
      setLoadingPlan(null)
    }
  }

  return (
    <div className="min-h-screen bg-[#020202] text-white relative overflow-x-hidden selection:bg-accent/30 selection:text-white">
      {/* Background Effects - matching landing page */}
      <div className="fixed inset-0 pointer-events-none z-0">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.03] mix-blend-overlay" />
        <div 
          className="absolute inset-0 opacity-[0.03]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '160px 160px',
          }}
        />
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.02] rounded-full blur-[150px]" />
      </div>

      <Header />

      <main className="flex-1 relative pt-20 sm:pt-32 pb-16 sm:pb-24 px-4 sm:px-6">
        <div className="max-w-6xl mx-auto">
          {/* Cancelled Banner */}
          {showCancelledBanner && (
            <div className="mb-8 p-4 bg-amber-500/10 border border-amber-500/20 flex items-start gap-3 animate-fade-in relative overflow-hidden">
              <div className="absolute inset-0 bg-amber-500/5 animate-pulse" />
              <AlertCircle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5 relative z-10" />
              <div className="flex-1 relative z-10">
                <p className="font-medium text-amber-400 font-mono text-sm uppercase tracking-wider">Transaction Cancelled</p>
                <p className="text-sm text-white/60 mt-1">
                  Operation aborted. No charges applied. Resume when ready.
                </p>
              </div>
              <button 
                onClick={() => setShowCancelledBanner(false)}
                className="p-1 text-white/40 hover:text-white transition-colors relative z-10"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* Hero */}
          <div className="text-left lg:text-center mb-12 sm:mb-16 animate-fade-in">
            <span className="text-accent font-mono text-[10px] sm:text-xs uppercase tracking-[0.2em] mb-3 sm:mb-4 block flex items-center gap-2 lg:justify-center">
               <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
               Clearance Levels
            </span>
            <h1 className="font-display text-[2.5rem] sm:text-[4rem] md:text-[5rem] lg:text-[6rem] leading-[0.9] tracking-[-0.03em] text-white">
              Pick your weapon.
            </h1>
            <p className="mt-5 sm:mt-8 text-sm sm:text-lg lg:text-xl text-white/50 max-w-xl lg:mx-auto font-light leading-relaxed">
              Enter Terminal. Upgrade when you need speed, filters, and deeper intel.
            </p>
          </div>

          {/* Pricing Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-8 mb-16 sm:mb-24 animate-slide-up items-stretch">
            {tiers.map((tier, index) => (
              <div
                key={tier.id}
                className={clsx(
                  "group relative p-6 sm:p-8 flex flex-col transition-all duration-500",
                  tier.highlighted
                    ? "bg-[#050505] border-2 border-accent shadow-[0_0_50px_-20px_rgba(16,185,129,0.2)] z-10 md:-translate-y-4"
                    : "bg-[#030303] border border-white/10 hover:border-white/20 hover:bg-[#050505]"
                )}
                style={{ animationDelay: `${index * 100}ms` }}
              >
                {/* Tech Corners for Highlighted */}
                {tier.highlighted && (
                    <>
                        <div className="absolute -top-px -left-px w-4 h-4 border-t border-l border-accent" />
                        <div className="absolute -top-px -right-px w-4 h-4 border-t border-r border-accent" />
                        <div className="absolute -bottom-px -left-px w-4 h-4 border-b border-l border-accent" />
                        <div className="absolute -bottom-px -right-px w-4 h-4 border-b border-r border-accent" />
                    </>
                )}
                
                {tier.badge && (
                  <div className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 z-20">
                    <span className="px-4 py-1.5 bg-accent text-black text-[10px] font-bold uppercase tracking-widest whitespace-nowrap shadow-lg shadow-accent/20">
                      {tier.badge}
                    </span>
                  </div>
                )}

                <div className="relative flex-1 flex flex-col">
                  {/* Header */}
                  <div className="mb-6 sm:mb-8 text-left lg:text-center pb-6 sm:pb-8 border-b border-white/10">
                    <h3 className="text-xl sm:text-2xl font-display text-white mb-3 sm:mb-4">{tier.name}</h3>
                    <div className="flex items-baseline justify-start lg:justify-center gap-1 mb-3 sm:mb-4">
                      {tier.price === '0' ? (
                        <span className="text-3xl sm:text-5xl font-mono text-white tracking-tight">Free</span>
                      ) : (
                        <>
                          <span className="text-3xl sm:text-5xl font-mono text-white tracking-tight">${tier.price}</span>
                          <span className="text-xs sm:text-sm font-mono text-white/40">{tier.period}</span>
                        </>
                      )}
                    </div>
                    <p className="text-xs sm:text-sm text-white/50 font-mono">{tier.description}</p>
                  </div>

                  {/* Features */}
                  <ul className="space-y-3 sm:space-y-4 mb-8 sm:mb-10 flex-1">
                    {tier.features.map((feature) => (
                      <li key={feature.text} className="flex items-start gap-3">
                        {feature.available ? (
                          <div className={clsx(
                              "w-5 h-5 flex items-center justify-center shrink-0 border",
                              feature.highlight ? "border-accent bg-accent/10 text-accent" : "border-white/20 bg-white/5 text-white/60"
                          )}>
                              <Check className="w-3 h-3" strokeWidth={3} />
                          </div>
                        ) : (
                          <div className="w-5 h-5 flex items-center justify-center shrink-0 border border-white/5 bg-transparent text-white/10">
                              <X className="w-3 h-3" strokeWidth={3} />
                          </div>
                        )}
                        <span className={clsx(
                          "text-sm font-mono leading-tight pt-0.5",
                          feature.available ? "text-white/80" : "text-white/20 line-through decoration-white/10"
                        )}>
                          {feature.text}
                          {feature.sublabel && (
                            <span className={clsx(
                                "ml-2 text-[10px] uppercase tracking-wider px-1.5 py-0.5 border",
                                tier.highlighted ? "text-accent border-accent/30 bg-accent/5" : "text-white/40 border-white/10 bg-white/5"
                            )}>
                              {feature.sublabel}
                            </span>
                          )}
                        </span>
                      </li>
                    ))}
                  </ul>

                  {/* CTA */}
                  <button
                    onClick={() => handleSelectPlan(tier.id, tier.isPaid)}
                    disabled={loadingPlan === tier.id}
                    className={clsx(
                      "w-full flex items-center justify-center gap-3 py-4 text-xs font-bold uppercase tracking-[0.2em] transition-all duration-300 mt-auto",
                      tier.highlighted
                        ? "bg-accent text-black hover:bg-white hover:text-black shadow-[0_0_20px_rgba(16,185,129,0.2)]"
                        : "border border-white/20 text-white hover:bg-white hover:text-black"
                    )}
                    style={{ clipPath: 'polygon(10px 0, 100% 0, 100% 100%, 0 100%, 0 10px)' }}
                  >
                    {loadingPlan === tier.id ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <>
                        {tier.cta}
                        <ArrowRight className="w-4 h-4" />
                      </>
                    )}
                  </button>
                </div>
              </div>
            ))}
          </div>

          {/* Comparison Table */}
          <div className="mb-16 sm:mb-24 border border-white/10 bg-[#050505] hidden sm:block">
            <div className="px-8 py-6 border-b border-white/10 bg-white/[0.02]">
                <h2 className="text-xl font-display text-white">Spec Sheet</h2>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-white/10 bg-[#0A0A0A]">
                    <th className="text-left py-5 px-8 text-xs font-bold uppercase tracking-widest text-white/40 font-mono">Feature Module</th>
                    <th className="text-center py-5 px-8 text-xs font-bold uppercase tracking-widest text-white/40 font-mono">Scout</th>
                    <th className="text-center py-5 px-8 text-xs font-bold uppercase tracking-widest text-accent font-mono">Trader</th>
                    <th className="text-center py-5 px-8 text-xs font-bold uppercase tracking-widest text-white/40 font-mono">Tycoon</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {comparisonFeatures.map((feature) => (
                    <tr key={feature.name} className="hover:bg-white/[0.02] transition-colors">
                      <td className="py-5 px-8 text-sm text-white font-mono">{feature.name}</td>
                      <td className="py-5 px-8 text-center text-sm text-white/40 font-mono">
                        {feature.scout}
                      </td>
                      <td className="py-5 px-8 text-center text-sm text-white font-mono bg-accent/[0.02]">
                        {feature.trader}
                      </td>
                      <td className="py-5 px-8 text-center text-sm text-white/40 font-mono">
                        {feature.tycoon}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* FAQ */}
          <div className="max-w-3xl mx-auto">
            <h2 className="text-2xl sm:text-3xl font-display text-white text-left lg:text-center mb-8 sm:mb-12">Mission Support</h2>
            <div className="space-y-4">
              {faqs.map((faq, i) => (
                <div
                  key={i}
                  className="border border-white/10 bg-[#050505] transition-all hover:border-white/20"
                >
                  <button
                    onClick={() => setExpandedFaq(expandedFaq === i ? null : i)}
                    className="w-full flex items-center justify-between p-6 text-left"
                  >
                    <span className="text-base font-mono text-white pr-8">{faq.q}</span>
                    <span className={clsx(
                      "shrink-0 w-6 h-6 flex items-center justify-center border border-white/10 transition-all",
                      expandedFaq === i ? "bg-accent text-black border-accent" : "text-white/40"
                    )}>
                      <span className={clsx("text-lg leading-none transition-transform duration-300", expandedFaq === i ? "rotate-45" : "")}>+</span>
                    </span>
                  </button>
                  <div className={clsx(
                      "overflow-hidden transition-all duration-300 ease-in-out",
                      expandedFaq === i ? "max-h-40 opacity-100" : "max-h-0 opacity-0"
                  )}>
                    <div className="px-6 pb-6 pt-0">
                      <div className="h-px w-full bg-white/5 mb-4" />
                      <p className="text-sm text-white/50 font-mono leading-relaxed pl-4 border-l border-accent/20">
                        {faq.a}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Bottom CTA */}
          <div className="text-center mt-24 py-16 px-6 bg-[#050505] border border-white/10 relative overflow-hidden">
            <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.05]" />
            <div className="relative z-10">
                <Shield className="w-12 h-12 text-white/20 mx-auto mb-6" />
                <h2 className="text-3xl font-display text-white mb-4">Not ready to commit?</h2>
                <p className="text-white/50 mb-10 font-mono text-sm">
                Start with Scout. It&apos;s free forever. Upgrade when you need more firepower.
                </p>
                <Link
                href={isAuthenticated ? "/terminal/hunt" : "/register"}
                className="inline-flex items-center gap-3 px-8 py-4 border border-white/20 text-white text-xs font-bold uppercase tracking-[0.2em] hover:bg-white hover:text-black transition-all"
                >
                {isAuthenticated ? "Command Center" : "Join the Hunt"}
                <ArrowRight className="w-4 h-4" />
                </Link>
            </div>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}
