'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 } 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: 'TLD price overview', highlight: false, available: true },
    ],
    cta: 'Hunt Free',
    highlighted: false,
    badge: null,
    isPaid: false,
  },
  {
    id: 'trader',
    name: 'Trader',
    icon: TrendingUp,
    price: '19',
    period: '/mo',
    description: 'Hunt with precision. Daily intel.',
    features: [
      { text: '50 domains to track', highlight: true, available: true },
      { text: 'Hourly scans', highlight: true, available: true },
      { text: 'Email alerts', highlight: false, available: true },
      { text: 'Full TLD market data', highlight: false, available: true },
      { text: 'Domain valuation', highlight: true, available: true },
      { text: 'Portfolio (25 domains)', highlight: true, available: true },
      { text: '90-day price history', highlight: false, available: true },
      { text: 'Expiry tracking', highlight: true, available: true },
    ],
    cta: 'Start Trading',
    highlighted: true,
    badge: 'Most Popular',
    isPaid: true,
  },
  {
    id: 'tycoon',
    name: 'Tycoon',
    icon: Crown,
    price: '49',
    period: '/mo',
    description: 'Dominate the market. No limits.',
    features: [
      { text: '500 domains to track', highlight: true, available: true },
      { text: 'Real-time scans (10 min)', highlight: true, available: true },
      { text: 'Priority email alerts', highlight: false, available: true },
      { text: 'Unlimited portfolio', highlight: true, available: true },
      { text: 'Full price history', highlight: true, available: true },
      { text: 'Advanced valuation', highlight: true, available: true },
    ],
    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: 'Portfolio Domains', scout: '—', trader: '25', tycoon: 'Unlimited' },
  { name: 'Domain Valuation', scout: '—', trader: '✓', tycoon: '✓' },
  { name: 'Price History', scout: '—', trader: '90 days', tycoon: 'Unlimited' },
  { name: 'Expiry Tracking', 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 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)

  useEffect(() => {
    checkAuth()
  }, [checkAuth])

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

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

    setLoadingPlan(planId)
    try {
      const response = await api.createCheckoutSession(
        planId,
        `${window.location.origin}/dashboard?upgraded=true`,
        `${window.location.origin}/pricing`
      )
      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">
          {/* 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">
            {tiers.map((tier, index) => (
              <div
                key={tier.id}
                className={clsx(
                  "group relative p-6 sm:p-8 rounded-2xl border transition-all duration-500",
                  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">
                  {/* 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 */}
                  <ul className="space-y-3 mb-8">
                    {tier.features.map((feature) => (
                      <li key={feature.text} className="flex items-start gap-3">
                        <Check className={clsx(
                          "w-4 h-4 mt-0.5 shrink-0",
                          feature.highlight ? "text-accent" : "text-foreground-muted"
                        )} strokeWidth={2.5} />
                        <span className={clsx(
                          "text-body-sm",
                          feature.highlight ? "text-foreground" : "text-foreground-muted"
                        )}>
                          {feature.text}
                        </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-2 py-4 rounded-xl text-ui font-medium transition-all duration-300",
                      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}</td>
                      <td className="py-4 px-4 text-center text-body-sm text-foreground">{feature.trader}</td>
                      <td className="py-4 px-4 text-center text-body-sm text-foreground">{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 ? "/dashboard" : "/register"}
              className="btn-primary inline-flex items-center gap-2 px-6 py-3"
            >
              {isAuthenticated ? "Go to Dashboard" : "Get Started Free"}
              <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}
