'use client';

import { useMemo, useState } from 'react';
import { createCheckoutSession } from '@/lib/licenseServer';

type Plan = {
  code: string;
  name: string;
  price: string;
  period: string;
  description: string;
  savings?: string | null;
  highlighted?: boolean;
  features: string[];
};

export default function PricingCards() {
  const [loadingPlan, setLoadingPlan] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const plans = useMemo<Plan[]>(() => [
    {
      code: 'free',
      name: 'Free',
      price: '$0',
      period: 'forever',
      description: 'Everything you need to self-host DashCaddy for core use.',
      features: [
        'Dashboard and monitoring',
        'Container deployment',
        'Caddy management',
        'DNS management',
        'Health checks',
        'App templates'
      ]
    },
    {
      code: 'premium_1m',
      name: 'Premium, 1 Month',
      price: '$25',
      period: 'per month',
      description: 'Premium feature access for one month.',
      features: [
        'Auto-Login SSO',
        'Recipes (multi-container stack deployment)',
        'Docker Swarm orchestration'
      ]
    },
    {
      code: 'premium_3m',
      name: 'Premium, 3 Months',
      price: '$50',
      period: 'every 3 months',
      savings: 'Best short-term value',
      description: 'A better value plan for regular use.',
      highlighted: true,
      features: [
        'Auto-Login SSO',
        'Recipes (multi-container stack deployment)',
        'Docker Swarm orchestration'
      ]
    },
    {
      code: 'premium_6m',
      name: 'Premium, 6 Months',
      price: '$65',
      period: 'every 6 months',
      savings: 'Strong loyalty pricing',
      description: 'The commitment plan with aggressive value.',
      features: [
        'Auto-Login SSO',
        'Recipes (multi-container stack deployment)',
        'Docker Swarm orchestration'
      ]
    },
    {
      code: 'premium_12m',
      name: 'Premium, 12 Months',
      price: '$99',
      period: 'per year',
      savings: 'Best overall value',
      description: 'The best-value annual Premium plan.',
      features: [
        'Auto-Login SSO',
        'Recipes (multi-container stack deployment)',
        'Docker Swarm orchestration'
      ]
    }
  ], []);

  async function handleCheckout(planCode: string) {
    try {
      setError(null);
      setLoadingPlan(planCode);
      const result = await createCheckoutSession(planCode);
      window.location.href = result.url;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to start checkout');
    } finally {
      setLoadingPlan(null);
    }
  }

  return (
    <div className="space-y-6">
      {error && (
        <div className="rounded-lg border border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-200">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-6 max-w-7xl mx-auto">
        {plans.map((plan) => {
          const isFree = plan.code === 'free';
          const isLoading = loadingPlan === plan.code;

          return (
            <div
              key={plan.code}
              className={`relative rounded-2xl border transition-all duration-300 ${
                plan.highlighted
                  ? 'border-brand-500/50 bg-gradient-to-br from-surface-800 to-surface-900 shadow-2xl shadow-brand-500/20'
                  : 'border-surface-700/50 bg-surface-800/50 hover:border-surface-700 hover:bg-surface-800/80'
              }`}
            >
              {plan.highlighted && (
                <div className="absolute -top-4 left-1/2 -translate-x-1/2">
                  <span className="inline-block rounded-full bg-brand-500 px-4 py-1 text-xs font-bold uppercase tracking-wide text-white">
                    Recommended
                  </span>
                </div>
              )}

              <div className="p-8">
                <div className="mb-8">
                  <h3 className="text-2xl font-bold text-surface-50 mb-2">{plan.name}</h3>
                  <p className="text-surface-400 text-sm mb-6">{plan.description}</p>
                  <div className="flex items-baseline gap-2 mb-2">
                    <span className="text-4xl font-bold text-surface-50">{plan.price}</span>
                    <span className="text-surface-400 text-sm">/{plan.period}</span>
                  </div>
                  {plan.savings && <p className="text-sm text-brand-400 font-semibold">{plan.savings}</p>}
                </div>

                {isFree ? (
                  <a
                    href="/docs"
                    className="block w-full rounded-lg px-6 py-3 text-center font-semibold transition-all duration-200 mb-8 border border-surface-700 bg-surface-700/50 text-surface-50 hover:border-brand-400 hover:bg-surface-700 hover:text-brand-400"
                  >
                    Use Free Tier
                  </a>
                ) : (
                  <button
                    onClick={() => handleCheckout(plan.code)}
                    disabled={Boolean(loadingPlan)}
                    className={`block w-full rounded-lg px-6 py-3 text-center font-semibold transition-all duration-200 mb-8 ${
                      plan.highlighted
                        ? 'bg-brand-500 text-white hover:bg-brand-600 hover:shadow-lg hover:shadow-brand-500/30'
                        : 'border border-surface-700 bg-surface-700/50 text-surface-50 hover:border-brand-400 hover:bg-surface-700 hover:text-brand-400'
                    } disabled:opacity-60 disabled:cursor-not-allowed`}
                  >
                    {isLoading ? 'Opening Checkout...' : 'Buy Premium'}
                  </button>
                )}

                <div className="border-t border-surface-700/50 pt-8">
                  <ul className="space-y-4">
                    {plan.features.map((feature) => (
                      <li key={feature} className="flex items-start gap-3">
                        <svg className="h-5 w-5 flex-shrink-0 text-green-400 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                        </svg>
                        <span className="text-surface-300 text-sm">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
