import { motion, useInView } from 'framer-motion';
import { useRef } from 'react';

interface PricingTier {
  name: string;
  price: string;
  period: string;
  description: string;
  features: string[];
  cta: string;
  ctaHref: string;
  highlighted?: boolean;
}

function PricingCard({ tier, delay = 0 }: { tier: PricingTier; delay?: number }) {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: '-80px' });

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 40 }}
      animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
      transition={{ duration: 0.6, delay, ease: 'easeOut' }}
      className={`relative bg-slate-800/50 backdrop-blur-sm border rounded-2xl p-8 flex flex-col ${
        tier.highlighted
          ? 'border-sky-400/50 shadow-lg shadow-sky-500/20 scale-105'
          : 'border-slate-700/50 hover:border-sky-400/30'
      } transition-all duration-300`}
    >
      {tier.highlighted && (
        <div className="absolute -top-4 left-1/2 -translate-x-1/2 bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 text-xs font-bold px-4 py-1 rounded-full">
          MOST POPULAR
        </div>
      )}

      {/* Tier Name */}
      <h3 className="text-2xl font-bold text-sky-400 mb-2">{tier.name}</h3>

      {/* Price */}
      <div className="mb-2">
        <span className="text-5xl font-black text-white">{tier.price}</span>
        {tier.period && <span className="text-slate-400 text-lg ml-2">{tier.period}</span>}
      </div>

      {/* Trial Badge */}
      <div className="mb-4">
        <span className="inline-block bg-sky-500/10 border border-sky-400/30 text-sky-400 text-xs font-semibold px-3 py-1 rounded-full">
          7-day free trial
        </span>
      </div>

      {/* Description */}
      <p className="text-slate-300 text-sm mb-6 leading-relaxed">{tier.description}</p>

      {/* CTA Button */}
      <a
        href={tier.ctaHref}
        target="_blank"
        rel="noopener noreferrer"
        className={`w-full py-3 rounded-xl font-semibold text-base text-center transition-all duration-200 mb-8 block focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950 ${
          tier.highlighted
            ? 'bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 shadow-lg shadow-sky-500/50 hover:shadow-sky-400/75 hover:-translate-y-1'
            : 'border-2 border-sky-400/50 text-sky-400 hover:bg-sky-400/10 hover:border-sky-400'
        }`}
      >
        {tier.cta}
      </a>

      {/* Features List */}
      <ul className="space-y-3 flex-1">
        {tier.features.map((feature, idx) => (
          <li key={idx} className="flex items-start gap-3 text-slate-300 text-sm">
            <span className="text-sky-400 text-lg flex-shrink-0 mt-0.5">&#10003;</span>
            <span>{feature}</span>
          </li>
        ))}
      </ul>
    </motion.div>
  );
}

export default function Pricing() {
  const soloLink = import.meta.env.VITE_STRIPE_SOLO_LINK || 'https://buy.stripe.com/9B628r9Lr7lCgws9K314403';
  const proLink = import.meta.env.VITE_STRIPE_PRO_LINK || 'https://buy.stripe.com/fZu5kD5vb7lC940f4n14404';

  const tiers: PricingTier[] = [
    {
      name: 'Solo',
      price: '$14.97',
      period: '/mo',
      description: 'Persistent AI memory for developers. Full brain pipeline, unlimited agents, swarm orchestration.',
      features: [
        'Full brain pipeline (read + write + extraction)',
        'Unlimited agents (bring your own LLM keys)',
        'Swarm orchestration (up to 5 workers)',
        'Full CLI (47 commands)',
        'Web dashboard + Brain Explorer',
        'Core daemons (bridge, neural, consolidation)',
        'Knowledge graph visualization',
        'Community + GitHub support',
      ],
      cta: 'Start Solo — Free for 7 Days',
      ctaHref: soloLink,
      highlighted: true,
    },
    {
      name: 'Pro',
      price: '$29.97',
      period: '/mo',
      description: 'The complete neural OS. Unlimited swarm, all daemons, graph RAG, browser automation, and self-hosting.',
      features: [
        'Everything in Solo',
        'Unlimited swarm workers',
        'All 36 daemons (synthesis, prediction, healing, sleep cycle)',
        'Full knowledge graph RAG + causal traversal',
        'Browser automation (agent web navigation)',
        'Docker + self-host ready',
        'Custom governance rules',
        'Priority support',
      ],
      cta: 'Start Pro — Free for 7 Days',
      ctaHref: proLink,
    },
  ];

  const features = [
    { name: 'Brain Pipeline', solo: 'Full Access', pro: 'Full Access' },
    { name: 'Agents', solo: 'Unlimited', pro: 'Unlimited' },
    { name: 'Swarm Workers', solo: 'Up to 5', pro: 'Unlimited' },
    { name: 'CLI Commands', solo: '47', pro: '47' },
    { name: 'Web Dashboard', solo: true, pro: true },
    { name: 'Brain Explorer', solo: true, pro: true },
    { name: 'Knowledge Graph', solo: 'View', pro: 'Full RAG + Causal' },
    { name: 'Core Daemons', solo: true, pro: true },
    { name: 'Synthesis Daemons (36 total)', solo: false, pro: true },
    { name: 'Browser Automation', solo: false, pro: true },
    { name: 'Docker + Self-Host', solo: false, pro: true },
    { name: 'Custom Governance Rules', solo: false, pro: true },
    { name: 'Support', solo: 'Community', pro: 'Priority' },
  ];

  return (
    <div className="relative min-h-screen bg-slate-950 px-4 sm:px-6 lg:px-8 py-24">
      {/* Background gradient */}
      <div className="absolute inset-0 bg-gradient-to-b from-slate-950 via-slate-900/50 to-slate-950 pointer-events-none" />

      {/* Content */}
      <div className="relative z-10 max-w-5xl mx-auto">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          className="text-center mb-16"
        >
          <h1 className="text-4xl sm:text-5xl font-black text-sky-400 mb-4 tracking-tight">
            Choose Your Plan
          </h1>
          <p className="text-lg text-slate-300 max-w-2xl mx-auto">
            Persistent AI memory that learns from every session. Your agents get smarter, your workflow gets faster.
          </p>
          <p className="text-sm text-slate-400 mt-2">
            Both plans include a 7-day free trial. Cancel anytime.
          </p>
        </motion.div>

        {/* Pricing Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl mx-auto mb-16">
          {tiers.map((tier, idx) => (
            <PricingCard key={tier.name} tier={tier} delay={idx * 0.15} />
          ))}
        </div>

        {/* Feature Comparison Table */}
        <motion.div
          initial={{ opacity: 0, y: 40 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.6 }}
          className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8 overflow-x-auto"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6">Feature Comparison</h2>

          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-slate-700/50">
                <th className="pb-4 text-slate-300 font-semibold">Feature</th>
                <th className="pb-4 text-center text-slate-300 font-semibold">Solo</th>
                <th className="pb-4 text-center text-slate-300 font-semibold">Pro</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {features.map((feature, idx) => (
                <tr key={idx} className={idx < features.length - 1 ? 'border-b border-slate-700/30' : ''}>
                  <td className="py-4 text-slate-300">{feature.name}</td>
                  <td className="py-4 text-center">
                    {typeof feature.solo === 'boolean' ? (
                      feature.solo ? (
                        <span className="text-sky-400">&#10003;</span>
                      ) : (
                        <span className="text-red-400">&#10007;</span>
                      )
                    ) : (
                      <span className={feature.solo === 'Community' ? 'text-slate-400' : 'text-sky-400'}>
                        {feature.solo}
                      </span>
                    )}
                  </td>
                  <td className="py-4 text-center">
                    {typeof feature.pro === 'boolean' ? (
                      feature.pro ? (
                        <span className="text-sky-400">&#10003;</span>
                      ) : (
                        <span className="text-red-400">&#10007;</span>
                      )
                    ) : (
                      <span className="text-sky-400">{feature.pro}</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </motion.div>

        {/* How It Works */}
        <motion.div
          initial={{ opacity: 0, y: 40 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.6, delay: 0.1 }}
          className="mt-16 bg-slate-800/30 border border-slate-700/30 rounded-2xl p-8"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6 text-center">How It Works</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8 text-center">
            <div>
              <div className="text-3xl mb-3">1</div>
              <h3 className="text-white font-semibold mb-2">Subscribe</h3>
              <p className="text-slate-400 text-sm">Pick a plan. 7-day free trial, cancel anytime.</p>
            </div>
            <div>
              <div className="text-3xl mb-3">2</div>
              <h3 className="text-white font-semibold mb-2">Install</h3>
              <p className="text-slate-400 text-sm">
                <code className="bg-slate-700/50 px-2 py-0.5 rounded text-sky-400">pip install pulse-os</code>
                {' '}then{' '}
                <code className="bg-slate-700/50 px-2 py-0.5 rounded text-sky-400">pulse init</code>
              </p>
            </div>
            <div>
              <div className="text-3xl mb-3">3</div>
              <h3 className="text-white font-semibold mb-2">Activate</h3>
              <p className="text-slate-400 text-sm">
                Copy your key from the checkout page and run{' '}
                <code className="bg-slate-700/50 px-2 py-0.5 rounded text-sky-400">pulse activate &lt;KEY&gt;</code>
              </p>
            </div>
            <div>
              <div className="text-3xl mb-3">4</div>
              <h3 className="text-white font-semibold mb-2">Ship</h3>
              <p className="text-slate-400 text-sm">Your AI agents now have persistent memory. Every session makes them smarter.</p>
            </div>
          </div>
        </motion.div>

        {/* FAQ Section */}
        <motion.div
          initial={{ opacity: 0, y: 40 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: '-80px' }}
          transition={{ duration: 0.6, delay: 0.2 }}
          className="mt-16 text-center"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-4">Questions?</h2>
          <p className="text-slate-300 mb-6">
            Check out our{' '}
            <a href="/docs" className="text-sky-400 hover:text-sky-300 underline">
              documentation
            </a>{' '}
            or{' '}
            <a
              href="https://github.com/Honesty0x/PULSE/issues"
              className="text-sky-400 hover:text-sky-300 underline"
              target="_blank"
              rel="noopener noreferrer"
            >
              open an issue
            </a>
            .
          </p>
        </motion.div>
      </div>
    </div>
  );
}
