'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 } from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

const tiers = [
  {
    id: 'scout',
    name: 'Scout',
    icon: Zap,
    price: '0',
    period: '',
    description: 'Test the waters. Zero risk.',
    features: [
      { text: '5 domains to track', highlight: false, available: true },
      { text: 'Daily availability scans', highlight: false, available: true },
      { text: 'Email alerts', highlight: false, available: true },
      { text: 'Raw auction feed', highlight: false, available: true, sublabel: 'Unfiltered' },
      { text: '2 domain listings', highlight: false, available: true, sublabel: 'For Sale' },
      { text: 'Deal scores & valuations', highlight: false, available: false },
      { text: 'Sniper Alerts', highlight: false, available: false },
    ],
    cta: 'Start Free',
    highlighted: false,
    badge: null,
    isPaid: false,
  },
  {
    id: 'trader',
    name: 'Trader',
    icon: TrendingUp,
    price: '9',
    period: '/mo',
    description: 'The smart investor\'s choice.',
    features: [
      { text: '50 domains to track', highlight: true, available: true },
      { text: 'Hourly scans', highlight: true, available: true, sublabel: '24x faster' },
      { text: 'Smart spam filter', highlight: true, available: true, sublabel: 'Curated list' },
      { text: 'Deal scores & valuations', highlight: true, available: true },
      { text: '10 domain listings', highlight: true, available: true, sublabel: 'For Sale' },
      { text: '5 Sniper Alerts', highlight: true, available: true },
      { text: 'Portfolio tracking (25)', highlight: true, available: true },
      { text: 'Expiry date tracking', highlight: true, available: true },
    ],
    cta: 'Upgrade to Trader',
    highlighted: true,
    badge: 'Best Value',
    isPaid: true,
  },
  {
    id: 'tycoon',
    name: 'Tycoon',
    icon: Crown,
    price: '29',
    period: '/mo',
    description: 'For serious domain investors.',
    features: [
      { text: '500 domains to track', highlight: true, available: true },
      { text: 'Real-time scans', highlight: true, available: true, sublabel: 'Every 10 min' },
      { text: '50 domain listings', highlight: true, available: true, sublabel: 'For Sale' },
      { text: 'Unlimited Sniper Alerts', highlight: true, available: true },
      { text: 'SEO Juice Detector', highlight: true, available: true, sublabel: 'Backlinks' },
      { text: 'Unlimited portfolio', highlight: true, available: true },
      { text: 'Full price history', highlight: true, available: true },
      { text: 'API access', highlight: true, available: true, sublabel: 'Coming soon' },
    ],
    cta: 'Go Tycoon',
    highlighted: false,
    badge: 'Full Power',
    isPaid: true,
  },
]

const comparisonFeatures = [
  { name: 'Watchlist Domains', scout: '5', trader: '50', tycoon: '500' },
  { name: 'Check Frequency', scout: 'Daily', trader: 'Hourly', tycoon: '10 min' },
  { name: 'Auction Feed', scout: 'Raw (unfiltered)', trader: 'Curated (spam-free)', tycoon: 'Curated (spam-free)' },
  { name: 'Deal Scores', scout: '—', trader: 'check', tycoon: 'check' },
  { name: 'For Sale Listings', scout: '2', trader: '10', tycoon: '50' },
  { name: 'Sniper Alerts', scout: '—', trader: '5', tycoon: 'Unlimited' },
  { name: 'Portfolio Domains', scout: '—', trader: '25', tycoon: 'Unlimited' },
  { name: 'SEO Juice Detector', scout: '—', trader: '—', tycoon: 'check' },
  { name: 'Price History', scout: '—', trader: '90 days', tycoon: 'Unlimited' },
  { name: 'Expiry Tracking', scout: '—', trader: 'check', tycoon: 'check' },
]

const faqs = [
  {
    q: 'How fast will I know when a domain drops?',
    a: 'Depends on your plan. Scout: daily. Trader: hourly. Tycoon: every 10 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/radar')
      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-background relative overflow-hidden">
      {/* Background Effects - matching landing page */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
        <div 
          className="absolute inset-0 opacity-[0.015]"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.1) 1px, transparent 1px)`,
            backgroundSize: '64px 64px',
          }}
        />
      </div>

      <Header />

      <main className="flex-1 relative pt-32 sm:pt-40 pb-20 sm:pb-28 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 rounded-xl flex items-start gap-3 animate-fade-in">
              <AlertCircle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
              <div className="flex-1">
                <p className="font-medium text-amber-400">Checkout cancelled</p>
                <p className="text-sm text-foreground-muted mt-1">
                  No worries! Your card was not charged. You can try again whenever you&apos;re ready, 
                  or continue with the free Scout plan.
                </p>
              </div>
              <button 
                onClick={() => setShowCancelledBanner(false)}
                className="p-1 text-foreground-muted hover:text-foreground transition-colors"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* Hero */}
          <div className="text-center mb-16 sm:mb-20 animate-fade-in">
            <span className="text-sm font-semibold text-accent uppercase tracking-wider">Pricing</span>
            <h1 className="mt-4 font-display text-[2.5rem] sm:text-[3.5rem] md:text-[4.5rem] lg:text-[5rem] leading-[0.95] tracking-[-0.03em] text-foreground">
              Pick your weapon.
            </h1>
            <p className="mt-5 text-lg sm:text-xl text-foreground-muted max-w-xl mx-auto">
              Start free. Scale when you&apos;re ready. All plans include core features.
            </p>
          </div>

          {/* Pricing Cards */}
          <div className="grid md:grid-cols-3 gap-6 mb-20 animate-slide-up items-stretch">
            {tiers.map((tier, index) => (
              <div
                key={tier.id}
                className={clsx(
                  "group relative p-6 sm:p-8 rounded-2xl border transition-all duration-500 flex flex-col",
                  tier.highlighted
                    ? "bg-background-secondary border-accent/30 shadow-lg shadow-accent/5"
                    : "bg-background-secondary/50 border-border hover:border-accent/20 hover:bg-background-secondary"
                )}
                style={{ animationDelay: `${index * 100}ms` }}
              >
                {/* Hover glow for non-highlighted */}
                {!tier.highlighted && (
                  <div className="absolute inset-0 rounded-2xl bg-accent/5 opacity-0 group-hover:opacity-100 transition-opacity" />
                )}
                
                {tier.badge && (
                  <div className="absolute -top-3 left-1/2 -translate-x-1/2 z-10">
                    <span className="px-3 py-1 bg-accent text-background text-ui-xs font-medium rounded-full whitespace-nowrap">
                      {tier.badge}
                    </span>
                  </div>
                )}

                <div className="relative flex-1 flex flex-col">
                  {/* Header */}
                  <div className="mb-6">
                    <div className="flex items-center gap-3 mb-3">
                      <div className={clsx(
                        "w-12 h-12 rounded-2xl flex items-center justify-center border transition-all duration-500",
                        tier.highlighted 
                          ? "bg-accent/10 border-accent/30" 
                          : "bg-foreground/5 border-border group-hover:border-accent/30 group-hover:bg-accent/5"
                      )}>
                        <tier.icon className={clsx(
                          "w-5 h-5 transition-colors duration-500",
                          tier.highlighted ? "text-accent" : "text-foreground-muted group-hover:text-accent"
                        )} />
                      </div>
                      <h3 className="text-xl font-semibold text-foreground">{tier.name}</h3>
                    </div>
                    <p className="text-body-sm text-foreground-muted mb-4">{tier.description}</p>
                    <div className="flex items-baseline gap-1">
                      {tier.price === '0' ? (
                        <span className="text-5xl font-display text-foreground">Free</span>
                      ) : (
                        <>
                          <span className="text-5xl font-display text-foreground">${tier.price}</span>
                          <span className="text-body text-foreground-muted">{tier.period}</span>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Features - flex-1 to push button to bottom */}
                  <ul className="space-y-3 mb-8 flex-1">
                    {tier.features.map((feature) => (
                      <li key={feature.text} className="flex items-start gap-3">
                        {feature.available ? (
                          <Check className={clsx(
                            "w-4 h-4 mt-0.5 shrink-0",
                            feature.highlight ? "text-accent" : "text-foreground-muted"
                          )} strokeWidth={2.5} />
                        ) : (
                          <X className="w-4 h-4 mt-0.5 shrink-0 text-foreground-subtle" strokeWidth={2} />
                        )}
                        <span className={clsx(
                          "text-body-sm",
                          feature.available ? "text-foreground" : "text-foreground-subtle line-through"
                        )}>
                          {feature.text}
                          {feature.sublabel && (
                            <span className="ml-1.5 text-xs text-accent font-medium">
                              {feature.sublabel}
                            </span>
                          )}
                        </span>
                      </li>
                    ))}
                  </ul>

                  {/* CTA - always at bottom */}
                  <button
                    onClick={() => handleSelectPlan(tier.id, tier.isPaid)}
                    disabled={loadingPlan === tier.id}
                    className={clsx(
                      "w-full flex items-center justify-center gap-2 py-4 rounded-xl text-ui font-medium transition-all duration-300 mt-auto",
                      tier.highlighted
                        ? "bg-accent text-background hover:bg-accent-hover shadow-[0_0_20px_rgba(16,185,129,0.15)]"
                        : "bg-foreground text-background hover:bg-foreground/90"
                    )}
                  >
                    {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-20">
            <h2 className="text-heading-md text-foreground text-center mb-8">Compare Plans</h2>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-border">
                    <th className="text-left py-4 px-4 text-body-sm font-medium text-foreground-muted">Feature</th>
                    <th className="text-center py-4 px-4 text-body-sm font-medium text-foreground-muted">Scout</th>
                    <th className="text-center py-4 px-4 text-body-sm font-medium text-accent">Trader</th>
                    <th className="text-center py-4 px-4 text-body-sm font-medium text-foreground-muted">Tycoon</th>
                  </tr>
                </thead>
                <tbody>
                  {comparisonFeatures.map((feature) => (
                    <tr key={feature.name} className="border-b border-border/50">
                      <td className="py-4 px-4 text-body-sm text-foreground">{feature.name}</td>
                      <td className="py-4 px-4 text-center text-body-sm text-foreground-muted">
                        {feature.scout === 'check' ? (
                          <Check className="w-5 h-5 text-accent mx-auto" strokeWidth={2.5} />
                        ) : feature.scout}
                      </td>
                      <td className="py-4 px-4 text-center text-body-sm text-foreground">
                        {feature.trader === 'check' ? (
                          <Check className="w-5 h-5 text-accent mx-auto" strokeWidth={2.5} />
                        ) : feature.trader}
                      </td>
                      <td className="py-4 px-4 text-center text-body-sm text-foreground">
                        {feature.tycoon === 'check' ? (
                          <Check className="w-5 h-5 text-accent mx-auto" strokeWidth={2.5} />
                        ) : feature.tycoon}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* FAQ */}
          <div className="max-w-3xl mx-auto">
            <h2 className="text-heading-md text-foreground text-center mb-8">Frequently Asked</h2>
            <div className="space-y-3">
              {faqs.map((faq, i) => (
                <div
                  key={i}
                  className="border border-border rounded-xl overflow-hidden"
                >
                  <button
                    onClick={() => setExpandedFaq(expandedFaq === i ? null : i)}
                    className="w-full flex items-center justify-between p-5 text-left hover:bg-foreground/5 transition-colors"
                  >
                    <span className="text-body font-medium text-foreground pr-4">{faq.q}</span>
                    <span className={clsx(
                      "shrink-0 w-6 h-6 flex items-center justify-center rounded-lg transition-all",
                      expandedFaq === i ? "bg-accent/10 text-accent rotate-45" : "bg-foreground/5 text-foreground-muted"
                    )}>
                      <span className="text-lg leading-none">+</span>
                    </span>
                  </button>
                  {expandedFaq === i && (
                    <div className="px-5 pb-5">
                      <p className="text-body-sm text-foreground-muted">{faq.a}</p>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Bottom CTA */}
          <div className="text-center mt-20 py-12 px-6 bg-background-secondary/50 border border-border rounded-2xl">
            <h2 className="text-heading-md text-foreground mb-3">Not sure yet?</h2>
            <p className="text-body text-foreground-muted mb-6">
              Start with Scout. It&apos;s free forever. Upgrade when you need more.
            </p>
            <Link
              href={isAuthenticated ? "/terminal/radar" : "/register"}
              className="btn-primary inline-flex items-center gap-2 px-6 py-3"
            >
              {isAuthenticated ? "Command Center" : "Join the Hunt"}
              <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}
