"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";

type SubscriptionStatus = {
  plan_name: string;
  plan_slug: string;
  status: string;
  starts_at: string | null;
  ends_at: string | null;
  is_free_trial: boolean;
  days_remaining: number | null;
  cancel_at_period_end: boolean;
};

const TIER_BENEFITS: Record<string, string[]> = {
  free: [
    "Basic profile listing",
    "Up to 10 photos",
    "Up to 3 galleries",
    "Standard search placement",
  ],
  basic: [
    "Up to 25 photos",
    "Up to 5 galleries",
    "Basic analytics dashboard",
    "Priority search placement",
    "Unlimited messages",
  ],
  premium: [
    "Up to 50 photos",
    "Up to 10 galleries",
    "\"Available Now\" badge",
    "Advanced analytics dashboard",
    "Tour listings",
    "VIP badge",
    "Priority search placement",
    "Unlimited messages",
  ],
  "premium-plus": [
    "Unlimited photos & galleries",
    "Featured profile rotation",
    "Multiple home bases",
    "Exclusive provider tools",
    "Advanced analytics",
    "VIP badge",
    "Priority search placement",
    "Unlimited messages",
    "Dedicated support",
  ],
};

const UPGRADE_TIERS = [
  { slug: "basic", name: "Basic", price: 35 },
  { slug: "premium", name: "Premium", price: 100 },
  { slug: "premium-plus", name: "Premium+", price: 150 },
];

export default function SubscriptionPage() {
  const { data: session, status: authStatus } = useSession();
  const router = useRouter();
  const [sub, setSub] = useState<SubscriptionStatus | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (authStatus === "unauthenticated") {
      router.push("/login");
      return;
    }
    if (authStatus !== "authenticated") return;

    fetch("/api/subscriptions/status")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data && !data.error) setSub(data);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [authStatus, router]);

  if (loading || authStatus === "loading") {
    return (
      <div className="max-w-3xl mx-auto py-12 px-4">
        <div className="animate-pulse space-y-6">
          <div className="h-8 bg-surface-light rounded w-64" />
          <div className="h-48 bg-surface-light rounded-xl" />
          <div className="h-32 bg-surface-light rounded-xl" />
        </div>
      </div>
    );
  }

  if (!sub) {
    return (
      <div className="max-w-3xl mx-auto py-12 px-4 text-center">
        <p className="text-text-muted">Unable to load subscription data.</p>
        <Link href="/pricing" className="text-gold hover:underline mt-2 inline-block">
          View Plans
        </Link>
      </div>
    );
  }

  const isFreeTier = sub.plan_slug === "free";
  const benefits = TIER_BENEFITS[sub.plan_slug] ?? TIER_BENEFITS.free;

  // Calculate trial progress
  let trialProgress = 0;
  let totalTrialDays = 0;
  if (sub.is_free_trial && sub.starts_at && sub.ends_at) {
    const start = new Date(sub.starts_at).getTime();
    const end = new Date(sub.ends_at).getTime();
    const now = Date.now();
    totalTrialDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24));
    const elapsed = Math.ceil((now - start) / (1000 * 60 * 60 * 24));
    trialProgress = Math.min(100, Math.max(0, (elapsed / totalTrialDays) * 100));
  }

  // Determine which tiers to show for upgrade
  const currentTierIndex = UPGRADE_TIERS.findIndex((t) => t.slug === sub.plan_slug);
  const availableUpgrades = isFreeTier
    ? UPGRADE_TIERS
    : UPGRADE_TIERS.filter((_, i) => i > currentTierIndex);

  return (
    <div className="max-w-3xl mx-auto py-8 px-4 space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-text">Membership</h1>
        <p className="text-text-muted mt-1">Manage your subscription and membership benefits.</p>
      </div>

      {/* Current Plan Card */}
      <div className="rounded-2xl border border-surface-light bg-surface p-6 md:p-8">
        <div className="flex items-start justify-between mb-4">
          <div>
            <p className="text-sm text-text-muted uppercase tracking-wider font-medium">Current Plan</p>
            <h2 className="text-3xl font-bold text-gold mt-1">{sub.plan_name}</h2>
          </div>
          <span
            className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider ${
              sub.status === "active"
                ? "bg-green-500/20 text-green-400"
                : "bg-red-500/20 text-red-400"
            }`}
          >
            {sub.status}
          </span>
        </div>

        {/* Free Trial Notice */}
        {sub.is_free_trial && sub.days_remaining !== null && (
          <div className="mb-6 p-4 rounded-xl bg-gold/10 border border-gold/20">
            <div className="flex items-center gap-2 mb-2">
              <svg className="w-5 h-5 text-gold" fill="currentColor" viewBox="0 0 20 20">
                <path d="M10 2a8 8 0 100 16 8 8 0 000-16zm1 11H9v-2h2v2zm0-4H9V5h2v4z" />
              </svg>
              <p className="text-gold font-semibold">
                You have {sub.days_remaining} day{sub.days_remaining !== 1 ? "s" : ""} remaining on your free Premium trial
              </p>
            </div>

            {/* Progress Bar */}
            <div className="mt-3">
              <div className="flex justify-between text-xs text-text-muted mb-1">
                <span>Trial started</span>
                <span>{sub.days_remaining} days left of {totalTrialDays}</span>
              </div>
              <div className="w-full h-2 bg-surface-light rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-to-r from-gold to-amber-400 rounded-full transition-all duration-500"
                  style={{ width: `${trialProgress}%` }}
                />
              </div>
            </div>
          </div>
        )}

        {/* Expiry Date */}
        {sub.ends_at && !sub.is_free_trial && (
          <p className="text-sm text-text-muted mb-4">
            {sub.cancel_at_period_end ? "Expires" : "Renews"} on{" "}
            <span className="text-text font-medium">
              {new Date(sub.ends_at).toLocaleDateString(undefined, {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </span>
          </p>
        )}

        {/* Benefits List */}
        <div className="mt-6">
          <h3 className="text-sm font-semibold text-text-muted uppercase tracking-wider mb-3">
            Your Benefits
          </h3>
          <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {benefits.map((benefit, i) => (
              <li key={i} className="flex items-center gap-2 text-sm text-text">
                <svg className="w-4 h-4 text-green-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                {benefit}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Free Tier CTA */}
      {isFreeTier && (
        <div className="rounded-2xl border border-gold/30 bg-gradient-to-b from-gold/10 to-surface p-6 md:p-8 text-center">
          <h3 className="text-xl font-bold text-text mb-2">
            You&apos;re on the Free tier
          </h3>
          <p className="text-text-muted mb-6 max-w-md mx-auto">
            Upgrade to unlock more photos, analytics, priority search, and premium badges to boost your visibility.
          </p>
          <Link
            href="/pricing"
            className="inline-flex items-center gap-2 px-8 py-3 rounded-xl bg-gold text-black font-bold text-sm shadow-lg shadow-gold/30 hover:bg-gold/90 transition-all hover:-translate-y-0.5"
          >
            View Plans & Upgrade
          </Link>
        </div>
      )}

      {/* Available Upgrades */}
      {!isFreeTier && availableUpgrades.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold text-text mb-4">Available Upgrades</h3>
          <div className="grid gap-4">
            {availableUpgrades.map((tier) => (
              <div
                key={tier.slug}
                className="flex items-center justify-between rounded-xl border border-surface-light bg-surface p-5 hover:border-gold/40 transition-colors"
              >
                <div>
                  <h4 className="text-base font-bold text-text">{tier.name}</h4>
                  <p className="text-sm text-text-muted">
                    &euro;{tier.price}/month
                  </p>
                </div>
                <Link
                  href={`/pricing?upgrade=${tier.slug}`}
                  className="px-5 py-2 rounded-lg bg-gold/20 text-gold font-semibold text-sm hover:bg-gold/30 transition-colors"
                >
                  Upgrade
                </Link>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Link to Full Pricing Page */}
      <div className="text-center pt-4">
        <Link href="/pricing" className="text-sm text-text-muted hover:text-gold transition-colors">
          View full plan comparison &rarr;
        </Link>
      </div>
    </div>
  );
}
