import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import type { Metadata } from "next";
import Link from "next/link";

export const metadata: Metadata = {
  title: "Subscription Plans | AdultWorld",
  description:
    "Choose a subscription plan that fits your needs. From free to Premium+, unlock premium features on AdultWorld.",
  openGraph: {
    title: "Subscription Plans | AdultWorld",
    description: "Unlock premium features with a subscription plan.",
  },
  twitter: {
    card: "summary_large_image",
    title: "Subscription Plans | AdultWorld",
    description: "Unlock premium features with a subscription plan.",
  },
};

export const dynamic = "force-dynamic";

type Plan = {
  id: number;
  name: string;
  slug: string;
  description: string | null;
  price_monthly: number;
  price_yearly: number;
  features: string | null;
  max_photos: number;
  max_galleries: number;
  max_videos: number;
  analytics_access: boolean;
  priority_search: boolean;
  verified_badge: boolean;
  vip_badge: boolean;
  unlimited_messages: boolean;
  active: boolean;
};

type DisplayPlan = {
  id: number;
  name: string;
  slug: string;
  description: string;
  price_monthly: number;
  price_yearly: number;
  features: string[];
  max_photos: number | string;
  max_galleries: number | string;
  max_videos: number | string;
  analytics_access: boolean;
  priority_search: boolean;
  verified_badge: boolean;
  vip_badge: boolean;
  unlimited_messages: boolean;
  highlighted?: boolean;
};

const HARDCODED_PLANS: DisplayPlan[] = [
  {
    id: 1,
    name: "Free",
    slug: "free",
    description: "Get started with a basic listing",
    price_monthly: 0,
    price_yearly: 0,
    features: ["Basic profile listing", "10 photos", "3 galleries", "Standard search placement"],
    max_photos: 10,
    max_galleries: 3,
    max_videos: 0,
    analytics_access: false,
    priority_search: false,
    verified_badge: false,
    vip_badge: false,
    unlimited_messages: false,
  },
  {
    id: 2,
    name: "Basic",
    slug: "basic",
    description: "Stand out with priority search & analytics",
    price_monthly: 35,
    price_yearly: 350,
    features: [
      "25 photos",
      "5 galleries",
      "Basic analytics",
      "Priority search placement",
      "Unlimited messages",
    ],
    max_photos: 25,
    max_galleries: 5,
    max_videos: 2,
    analytics_access: true,
    priority_search: true,
    verified_badge: false,
    vip_badge: false,
    unlimited_messages: true,
  },
  {
    id: 3,
    name: "Premium",
    slug: "premium",
    description: "Maximum visibility with VIP badge & advanced tools",
    price_monthly: 100,
    price_yearly: 1000,
    features: [
      "50 photos",
      "10 galleries",
      "\"Available Now\" badge",
      "Advanced analytics",
      "Tour listings",
      "VIP badge",
      "Priority search",
      "Unlimited messages",
    ],
    max_photos: 50,
    max_galleries: 10,
    max_videos: 10,
    analytics_access: true,
    priority_search: true,
    verified_badge: true,
    vip_badge: true,
    unlimited_messages: true,
    highlighted: true,
  },
  {
    id: 4,
    name: "Premium+",
    slug: "premium-plus",
    description: "The ultimate package for top providers",
    price_monthly: 150,
    price_yearly: 1500,
    features: [
      "Unlimited photos & galleries",
      "Featured profile rotation",
      "Multiple home bases",
      "Exclusive provider tools",
      "Advanced analytics",
      "VIP badge",
      "Priority search",
      "Unlimited messages",
      "Dedicated support",
    ],
    max_photos: "Unlimited",
    max_galleries: "Unlimited",
    max_videos: "Unlimited",
    analytics_access: true,
    priority_search: true,
    verified_badge: true,
    vip_badge: true,
    unlimited_messages: true,
  },
];

const COMPARISON_FEATURES = [
  { label: "Photos", key: "max_photos" },
  { label: "Galleries", key: "max_galleries" },
  { label: "Videos", key: "max_videos" },
  { label: "Analytics", key: "analytics_access" },
  { label: "Priority Search", key: "priority_search" },
  { label: "Verified Badge", key: "verified_badge" },
  { label: "VIP Badge", key: "vip_badge" },
  { label: "Unlimited Messages", key: "unlimited_messages" },
] as const;

export default async function PricingPage() {
  const session = await auth();

  let dbPlans: Plan[] = [];
  try {
    dbPlans = await prisma.$queryRawUnsafe<Plan[]>(
      `SELECT id, name, slug, description, price_monthly, price_yearly, features,
              max_photos, max_galleries, max_videos, analytics_access, priority_search,
              verified_badge, vip_badge, unlimited_messages, active
       FROM subscription_plans WHERE active = true ORDER BY price_monthly ASC`
    );
  } catch {
    // Table may not exist yet
  }

  const plans: DisplayPlan[] =
    dbPlans.length > 0
      ? dbPlans.map((p) => ({
          ...p,
          description: p.description ?? "",
          price_monthly: Number(p.price_monthly),
          price_yearly: Number(p.price_yearly),
          max_photos: Number(p.max_photos),
          max_galleries: Number(p.max_galleries),
          max_videos: Number(p.max_videos),
          features: p.features
            ? (() => {
                try {
                  return JSON.parse(p.features);
                } catch {
                  return [];
                }
              })()
            : [],
          highlighted: p.slug === "premium",
        }))
      : HARDCODED_PLANS;

  let currentPlanSlug: string | null = null;
  let currentPlanEnd: string | null = null;
  if (session?.user) {
    try {
      const userSub = await prisma.$queryRawUnsafe<
        { plan_slug: string; current_period_end: Date | null }[]
      >(
        `SELECT sp.slug as plan_slug, us.current_period_end
         FROM user_subscriptions us
         JOIN subscription_plans sp ON sp.id = us.plan_id
         WHERE us.user_id = $1 AND us.status = 'active'
         ORDER BY us.created_at DESC LIMIT 1`,
        Number(session.user.id)
      );
      if (userSub.length > 0) {
        currentPlanSlug = userSub[0].plan_slug;
        currentPlanEnd = userSub[0].current_period_end
          ? new Date(userSub[0].current_period_end).toLocaleDateString(undefined, {
              year: "numeric",
              month: "long",
              day: "numeric",
            })
          : null;
      }
    } catch {
      // subscription tables may not exist
    }
  }

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai";
  // Offer / PriceSpecification per plan so AI answer engines and Google can
  // surface pricing directly. Free plans are emitted with price 0 — still
  // valuable as a structured "freemium" signal.
  const offerLd = plans.map((plan) => ({
    "@context": "https://schema.org",
    "@type": "Offer",
    name: plan.name,
    description: plan.description,
    url: `${baseUrl}/pricing#${plan.slug}`,
    price: plan.price_monthly,
    priceCurrency: "EUR",
    priceSpecification: {
      "@type": "UnitPriceSpecification",
      price: plan.price_monthly,
      priceCurrency: "EUR",
      billingDuration: "P1M",
      unitCode: "MON",
    },
    availability: "https://schema.org/InStock",
    eligibleRegion: { "@type": "Place", name: "Worldwide" },
    seller: {
      "@type": "Organization",
      name: "AdultWorld",
      url: baseUrl,
    },
  }));

  // FAQPage JSON-LD — common pricing questions structured for AI engines.
  // Short, hardcoded, AI-citable answers; update centrally here as policy
  // changes rather than spreading across help articles.
  const faqLd = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: [
      {
        "@type": "Question",
        name: "How do credits work?",
        acceptedAnswer: {
          "@type": "Answer",
          text: "Credits are AdultWorld's in-platform currency, priced in EUR. You buy a pack and use credits for messaging, livecam time, tips, gallery unlocks, and pay-per-view content. Your balance is shown in the dashboard.",
        },
      },
      {
        "@type": "Question",
        name: "Can I cancel my subscription anytime?",
        acceptedAnswer: {
          "@type": "Answer",
          text: "Yes. You can cancel your subscription from the Manage Subscription page at any time. You'll keep access until the end of the current billing period.",
        },
      },
      {
        "@type": "Question",
        name: "Do credits expire?",
        acceptedAnswer: {
          "@type": "Answer",
          text: "No. Credits you've purchased never expire. They stay in your wallet until you spend them.",
        },
      },
      {
        "@type": "Question",
        name: "Do you offer refunds?",
        acceptedAnswer: {
          "@type": "Answer",
          text: "Unused credit packs are refundable within 14 days of purchase. Once credits have been spent on services they are non-refundable. Subscription billing follows EU consumer protection rules — see the Terms for the full policy.",
        },
      },
      {
        "@type": "Question",
        name: "What payment methods do you accept?",
        acceptedAnswer: {
          "@type": "Answer",
          text: "We accept major credit and debit cards via Stripe. All transactions are processed securely; AdultWorld never stores your card details directly.",
        },
      },
    ],
  };

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(offerLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(faqLd) }}
      />
      {/* 6 Months FREE Premium Banner */}
      <div className="relative overflow-hidden rounded-2xl mb-12 bg-gradient-to-r from-yellow-600 via-amber-500 to-yellow-600 p-[1px]">
        <div className="relative rounded-2xl bg-gradient-to-r from-yellow-600/90 via-amber-500/90 to-yellow-600/90 px-6 py-6 md:px-10 md:py-8 text-center">
          <div className="absolute top-3 left-6 text-white/30 text-2xl select-none pointer-events-none" aria-hidden="true">&#10022;</div>
          <div className="absolute bottom-3 right-8 text-white/20 text-xl select-none pointer-events-none" aria-hidden="true">&#9733;</div>
          <h2 className="text-2xl md:text-3xl font-bold text-white mb-2">
            New Providers: Get 6 Months FREE Premium
          </h2>
          <p className="text-white/90 text-base md:text-lg max-w-2xl mx-auto">
            Sign up as a provider and automatically receive 6 months of Premium membership — no credit card required.
          </p>
          {!session?.user && (
            <Link
              href="/register"
              className="inline-flex items-center gap-2 mt-4 px-8 py-3 rounded-xl bg-white text-amber-700 font-bold text-base shadow-lg hover:bg-white/90 hover:shadow-xl transition-all duration-200 hover:-translate-y-0.5"
            >
              Sign Up Now — It&apos;s Free
            </Link>
          )}
        </div>
      </div>

      {/* Header */}
      <div className="text-center mb-12">
        <h1 className="text-4xl md:text-5xl font-bold text-gold mb-3 font-heading">
          Choose Your Plan
        </h1>
        <p className="text-text-muted text-lg max-w-2xl mx-auto">
          Unlock premium features and maximize your visibility on AdultWorld with a plan that fits your needs.
        </p>
      </div>

      {/* Current Plan Indicator */}
      {currentPlanSlug && (
        <div className="text-center mb-8">
          <span className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-gold/20 text-gold border border-gold/30 text-sm font-medium">
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
            Your current plan: <strong className="capitalize">{currentPlanSlug.replace("-", " ")}</strong>
            {currentPlanEnd && <span className="text-text-muted ml-1">(until {currentPlanEnd})</span>}
          </span>
        </div>
      )}

      {/* Pricing Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-16">
        {plans.map((plan) => {
          const isCurrent = currentPlanSlug === plan.slug;
          const isHighlighted = plan.highlighted;

          return (
            <div
              key={plan.id}
              className={`relative rounded-2xl border p-6 flex flex-col transition-all duration-300 hover:-translate-y-1 hover:shadow-xl ${
                isHighlighted
                  ? "border-gold bg-gradient-to-b from-gold/10 via-surface to-surface shadow-gold/20 shadow-lg"
                  : "border-surface-light bg-surface hover:border-gold/40"
              }`}
            >
              {isHighlighted && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-4 py-1 rounded-full bg-gold text-black text-xs font-bold uppercase tracking-wider">
                  Most Popular
                </div>
              )}

              {isCurrent && (
                <div className="absolute -top-3 right-4 px-3 py-1 rounded-full bg-green-500 text-white text-xs font-bold">
                  Current Plan
                </div>
              )}

              <div className="mb-4 mt-2">
                <h3 className="text-xl font-bold text-text">{plan.name}</h3>
                <p className="text-sm text-text-muted mt-1">{plan.description}</p>
              </div>

              <div className="mb-6">
                <div className="flex items-baseline gap-1">
                  <span className="text-4xl font-bold text-gold">
                    {plan.price_monthly === 0 ? "Free" : `€${plan.price_monthly}`}
                  </span>
                  {plan.price_monthly > 0 && (
                    <span className="text-text-muted text-sm">/month</span>
                  )}
                </div>
                {plan.price_yearly > 0 && (
                  <p className="text-xs text-text-muted mt-1">
                    or €{plan.price_yearly}/year (save {Math.round((1 - plan.price_yearly / (plan.price_monthly * 12)) * 100)}%)
                  </p>
                )}
              </div>

              <ul className="space-y-3 mb-8 flex-1">
                {plan.features.map((feature, i) => (
                  <li key={i} className="flex items-start gap-2 text-sm text-text">
                    <svg
                      className={`w-5 h-5 flex-shrink-0 mt-0.5 ${isHighlighted ? "text-gold" : "text-green-400"}`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                    {feature}
                  </li>
                ))}
              </ul>

              {isCurrent ? (
                <Link
                  href="/manage/subscription"
                  className="block w-full text-center py-3 px-4 rounded-xl border border-gold/30 text-gold font-semibold text-sm hover:bg-gold/10 transition-colors"
                >
                  Manage Subscription
                </Link>
              ) : plan.price_monthly === 0 ? (
                <div className="block w-full text-center py-3 px-4 rounded-xl border border-surface-light text-text-muted font-semibold text-sm">
                  Included Free
                </div>
              ) : (
                <Link
                  href={session?.user ? `/manage/subscription?upgrade=${plan.slug}` : "/register"}
                  className={`block w-full text-center py-3 px-4 rounded-xl font-semibold text-sm transition-all duration-200 ${
                    isHighlighted
                      ? "bg-gold text-black hover:bg-gold/90 shadow-lg shadow-gold/30"
                      : "bg-surface-light text-text hover:bg-gold/20 hover:text-gold border border-surface-light"
                  }`}
                >
                  {session?.user ? "Upgrade" : "Sign Up"}
                </Link>
              )}
            </div>
          );
        })}
      </div>

      {/* Comparison Table */}
      <div className="mb-16">
        <h2 className="text-2xl font-bold text-text text-center mb-8">Compare All Plans</h2>
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="border-b border-surface-light">
                <th className="text-left py-4 px-4 text-text-muted text-sm font-medium w-48">Feature</th>
                {plans.map((plan) => (
                  <th
                    key={plan.id}
                    className={`text-center py-4 px-4 text-sm font-bold ${
                      plan.highlighted ? "text-gold" : "text-text"
                    }`}
                  >
                    {plan.name}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              <tr className="border-b border-surface-light/50">
                <td className="py-3 px-4 text-sm text-text-muted">Price</td>
                {plans.map((plan) => (
                  <td key={plan.id} className="text-center py-3 px-4 text-sm font-semibold text-text">
                    {plan.price_monthly === 0 ? "Free" : `€${plan.price_monthly}/mo`}
                  </td>
                ))}
              </tr>
              {COMPARISON_FEATURES.map((feature) => (
                <tr key={feature.key} className="border-b border-surface-light/50">
                  <td className="py-3 px-4 text-sm text-text-muted">{feature.label}</td>
                  {plans.map((plan) => {
                    const value = plan[feature.key as keyof DisplayPlan];
                    return (
                      <td key={plan.id} className="text-center py-3 px-4">
                        {typeof value === "boolean" ? (
                          value ? (
                            <svg className="w-5 h-5 text-green-400 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                            </svg>
                          ) : (
                            <svg className="w-5 h-5 text-text-muted/40 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          )
                        ) : (
                          <span className="text-sm text-text font-medium">{value}</span>
                        )}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Footer */}
      <div className="text-center">
        <p className="text-text-muted text-sm">
          All plans auto-renew. You can cancel anytime from your dashboard.
          Payments are processed securely by Stripe.
        </p>
      </div>
    </div>
  );
}
