"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import {
  CheckCircle2,
  XCircle,
  Crown,
  Zap,
  Star,
  Download,
  Headphones,
  Volume2,
  Sparkles,
  AlertCircle,
} from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchPackages } from "@/store/slices/packageSlice";
import { Package } from "@/services/packageService";
import { PaymentModal, type PaymentContext } from "@/components/payment/PaymentModal";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";

/* ─────────────────────────────────────────────────────────────────────────────
   Tier colour + icon palette
───────────────────────────────────────────────────────────────────────────── */

interface TierTheme {
  accent: string;
  glow: string;
  badge: string;
  bg: string;
  border: string;
  icon: React.ReactNode;
  label: string;
}

const TIER_THEMES: TierTheme[] = [
  {
    accent: "#4a9eff",
    glow: "rgba(74,158,255,0.25)",
    badge: "rgba(74,158,255,0.12)",
    bg: "linear-gradient(160deg,rgba(74,158,255,0.06) 0%,transparent 60%)",
    border: "rgba(74,158,255,0.25)",
    icon: <Zap size={18} strokeWidth={1.8} />,
    label: "Starter",
  },
  {
    accent: "var(--accent)",
    glow: "rgba(var(--accent-rgb),0.28)",
    badge: "rgba(var(--accent-rgb),0.12)",
    bg: "linear-gradient(160deg,rgba(var(--accent-rgb),0.07) 0%,transparent 60%)",
    border: "rgba(var(--accent-rgb),0.28)",
    icon: <Star size={18} strokeWidth={1.8} />,
    label: "Popular",
  },
  {
    accent: "var(--accent-gold)",
    glow: "rgba(var(--accent-gold-rgb),0.3)",
    badge: "rgba(var(--accent-gold-rgb),0.12)",
    bg: "linear-gradient(160deg,rgba(var(--accent-gold-rgb),0.07) 0%,transparent 60%)",
    border: "rgba(var(--accent-gold-rgb),0.35)",
    icon: <Crown size={18} strokeWidth={1.8} />,
    label: "Best Value",
  },
];

function getTierTheme(index: number): TierTheme {
  return TIER_THEMES[Math.min(index, TIER_THEMES.length - 1)];
}

/* ─────────────────────────────────────────────────────────────────────────────
   Feature icon mapping
───────────────────────────────────────────────────────────────────────────── */

function featureIcon(key: string) {
  if (key.toLowerCase().includes("ad")) return <Volume2 size={13} strokeWidth={1.8} />;
  if (key.toLowerCase().includes("download")) return <Download size={13} strokeWidth={1.8} />;
  if (key.toLowerCase().includes("background")) return <Headphones size={13} strokeWidth={1.8} />;
  return <Sparkles size={13} strokeWidth={1.8} />;
}

/* ─────────────────────────────────────────────────────────────────────────────
   Plan card
───────────────────────────────────────────────────────────────────────────── */

function PlanCard({
  pkg,
  index,
  totalPlans,
  onBuy,
}: {
  pkg: Package;
  index: number;
  totalPlans: number;
  onBuy: (pkg: Package) => void;
}) {
  const theme = getTierTheme(index);
  const isFeatured = pkg.isBestValue || index === totalPlans - 1;
  const delay = index * 100;
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";

  return (
    <div
      className="relative flex flex-col rounded-3xl overflow-hidden transition-all duration-300 hover:-translate-y-1"
      style={{
        background: `var(--card)`,
        border: `1px solid ${isFeatured ? theme.border : "var(--border)"}`,
        boxShadow: isFeatured
          ? `0 8px 40px ${theme.glow}, 0 2px 8px rgba(0,0,0,0.4)`
          : "0 2px 16px rgba(0,0,0,0.3)",
        animation: `plan-rise 0.5s ease forwards`,
        animationDelay: `${delay}ms`,
        opacity: 0,
        transform: isFeatured ? "scale(1.03)" : "scale(1)",
      }}
    >
      {/* Animated glow blob behind featured card */}
      {isFeatured && (
        <div
          className="absolute inset-0 rounded-3xl pointer-events-none"
          style={{
            background: theme.bg,
            animation: "plan-glow 3s ease-in-out infinite",
          }}
        />
      )}

      {/* Shimmer overlay on hover */}
      <div
        className="absolute inset-0 pointer-events-none overflow-hidden rounded-3xl"
        style={{ zIndex: 0 }}
      >
        <div
          className="absolute top-0 bottom-0 w-[60%] opacity-0 hover:opacity-100"
          style={{
            background: "linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.03) 50%, transparent 100%)",
            animation: "shimmer-slide 2s ease infinite",
          }}
        />
      </div>

      {/* Content */}
      <div className="relative z-10 flex flex-col h-full p-6">

        {/* Tier badge */}
        <div className="flex items-center justify-between mb-5">
          <div
            className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-[0.18em]"
            style={{ background: theme.badge, color: theme.accent }}
          >
            {theme.icon}
            {theme.label}
          </div>

          {/* Owned indicator */}
          {pkg.isOwned && (
            <span
              className="flex items-center gap-1 text-[10px] font-bold px-2.5 py-1 rounded-full"
              style={{ background: "rgba(34,197,94,0.12)", color: "#4ade80", border: "1px solid rgba(34,197,94,0.22)" }}
            >
              <CheckCircle2 size={10} strokeWidth={2.5} />
              Active
            </span>
          )}
        </div>

        {/* Package image + name */}
        <div className="flex items-center gap-3 mb-4">
          {pkg.image && (
            <div
              className="relative w-12 h-12 rounded-xl overflow-hidden shrink-0"
              style={{
                border: `1px solid ${theme.border}`,
                background: "var(--deep)",
              }}
            >
              <Image
                src={pkg.image}
                alt={pkg.name}
                fill
                className="object-cover"
                unoptimized
                sizes="48px"
              />
            </div>
          )}
          <h3
            className="text-xl font-black tracking-tight"
            style={{ letterSpacing: "-0.03em", color: "var(--text-primary)" }}
          >
            {pkg.name}
          </h3>
        </div>

        {/* Pricing block */}
        <div className="mb-5">
          <div className="flex items-baseline gap-1.5">
            <span
              className="text-4xl font-black"
              style={{ color: theme.accent, letterSpacing: "-0.04em" }}
            >
              {sym}{pkg.price}
            </span>
            <span className="text-sm font-semibold" style={{ color: "var(--text-muted)" }}>
              / {pkg.duration}
            </span>
          </div>
          <p className="text-[11px] mt-1 font-medium" style={{ color: "var(--text-muted)" }}>
            {pkg.monthlyEquivalent} · billed {pkg.durationUnit === "Year" ? "yearly" : `every ${pkg.durationCount > 1 ? pkg.duration.toLowerCase() : "month"}`}
          </p>
        </div>

        {/* Divider */}
        <div className="mb-4" style={{ height: 1, background: "var(--border)" }} />

        {/* Feature list */}
        <div className="flex flex-col gap-2.5 flex-1 mb-6">
          {pkg.features.map((feature, fi) => (
            <div
              key={fi}
              className="flex items-start gap-2.5"
              style={{
                animation: `feature-check-in 0.3s ease forwards`,
                animationDelay: `${delay + 200 + fi * 60}ms`,
                opacity: 0,
              }}
            >
              {feature.enabled ? (
                <span
                  className="flex items-center justify-center w-5 h-5 rounded-full shrink-0 mt-0.5"
                  style={{
                    background: `${theme.accent}22`,
                    color: theme.accent,
                  }}
                >
                  <CheckCircle2 size={12} strokeWidth={2.5} />
                </span>
              ) : (
                <span
                  className="flex items-center justify-center w-5 h-5 rounded-full shrink-0 mt-0.5"
                  style={{ background: "var(--border-soft)", color: "var(--text-muted)" }}
                >
                  <XCircle size={12} strokeWidth={2} />
                </span>
              )}
              <div className="flex items-center gap-1.5 min-w-0">
                <span
                  style={{ color: feature.enabled ? "var(--text-muted)" : "#555" }}
                  className="flex-shrink-0"
                >
                  {featureIcon(feature.key)}
                </span>
                <span
                  className="text-[12px] font-medium leading-snug"
                  style={{
                    color: feature.enabled ? "var(--text-muted)" : "#555",
                    textDecoration: feature.enabled ? "none" : "line-through",
                  }}
                >
                  {feature.key}
                </span>
              </div>
            </div>
          ))}
        </div>

        {/* CTA button */}
        <button
          onClick={() => !pkg.isOwned && onBuy(pkg)}
          disabled={pkg.isOwned}
          className="w-full py-3 rounded-2xl text-[13px] font-black tracking-wide transition-all duration-200 active:scale-[0.98] disabled:cursor-default relative overflow-hidden"
          style={
            pkg.isOwned
              ? {
                  background: "rgba(34,197,94,0.1)",
                  color: "#4ade80",
                  border: "1px solid rgba(34,197,94,0.25)",
                }
              : {
                  background: theme.accent,
                  color: isFeatured ? "#1a1200" : "white",
                  boxShadow: `0 4px 24px ${theme.glow}`,
                }
          }
        >
          <span className="relative z-10">
            {pkg.isOwned ? "✓ Current Plan" : `Get ${pkg.name}`}
          </span>
        </button>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Skeleton
───────────────────────────────────────────────────────────────────────────── */

function PlanSkeleton() {
  return (
    <div
      className="rounded-3xl p-6 flex flex-col gap-4 animate-pulse"
      style={{ background: "var(--card)", border: "1px solid var(--border-soft)" }}
    >
      <div className="flex justify-between">
        <div className="h-6 w-20 rounded-full" style={{ background: "var(--deep)" }} />
        <div className="h-6 w-14 rounded-full" style={{ background: "var(--deep)" }} />
      </div>
      <div className="flex items-center gap-3">
        <div className="w-12 h-12 rounded-xl" style={{ background: "var(--deep)" }} />
        <div className="h-6 w-24 rounded-full" style={{ background: "var(--deep)" }} />
      </div>
      <div>
        <div className="h-10 w-28 rounded-full" style={{ background: "var(--deep)" }} />
        <div className="h-3 w-36 rounded-full mt-2" style={{ background: "var(--deep)" }} />
      </div>
      <div className="flex flex-col gap-2.5">
        {[1, 2, 3].map((i) => (
          <div key={i} className="flex items-center gap-2.5">
            <div className="w-5 h-5 rounded-full shrink-0" style={{ background: "var(--deep)" }} />
            <div className="h-3 rounded-full flex-1" style={{ background: "var(--deep)", width: "70%" }} />
          </div>
        ))}
      </div>
      <div className="h-12 rounded-2xl" style={{ background: "var(--deep)" }} />
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   SubscriptionPage
───────────────────────────────────────────────────────────────────────────── */

export default function SubscriptionPage() {
  const dispatch = useAppDispatch();
  const { packages, isLoading, error } = useAppSelector((s) => s.packages);
  const [payCtx, setPayCtx] = useState<PaymentContext | null>(null);

  useEffect(() => {
    dispatch(fetchPackages());
  }, [dispatch]);

  const ownedPlan = packages.find((p) => p.isOwned);

  const handleBuyPlan = (pkg: Package) => {
    setPayCtx({
      type: "subscription",
      packageId: pkg.id,
      packageName: pkg.name,
      price: pkg.price,
    });
  };

  return (
    <div className="min-h-screen pb-28" style={{ background: "var(--bg)" }}>
      {/* ══ Hero ═════════════════════════════════════════════════════════════ */}
      <div
        className="relative overflow-hidden px-5 pt-10 pb-10 text-center"
        style={{
          background: "linear-gradient(180deg, rgba(var(--accent-rgb),0.05) 0%, rgba(var(--accent-gold-rgb),0.03) 50%, transparent 100%)",
        }}
      >
        {/* Glow orbs */}
        <div
          className="absolute top-0 left-1/4 w-72 h-72 rounded-full pointer-events-none"
          style={{ background: "radial-gradient(circle,rgba(var(--accent-rgb),0.09) 0%,transparent 70%)", transform: "translate(-50%,-40%)" }}
        />
        <div
          className="absolute top-0 right-1/4 w-72 h-72 rounded-full pointer-events-none"
          style={{ background: "radial-gradient(circle,rgba(var(--accent-gold-rgb),0.07) 0%,transparent 70%)", transform: "translate(50%,-40%)" }}
        />

        <div className="relative z-10 max-w-xl mx-auto">
          {/* Eyebrow */}
          <div
            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[10px] font-black uppercase tracking-[0.22em] mb-4"
            style={{
              background: "rgba(var(--accent-gold-rgb),0.1)",
              color: "var(--accent-gold)",
              border: "1px solid rgba(var(--accent-gold-rgb),0.2)",
            }}
          >
            <Crown size={11} strokeWidth={2} />
            Premium Plans
          </div>

          <h1
            className="text-3xl font-black leading-tight mb-3"
            style={{ letterSpacing: "-0.04em", color: "var(--text-primary)" }}
          >
            Unlock the Full
            <br />
            <span
              className="relative"
              style={{
                background: "linear-gradient(90deg, var(--accent) 0%, var(--accent-gold) 100%)",
                WebkitBackgroundClip: "text",
                WebkitTextFillColor: "transparent",
              }}
            >
              Doliplay Experience
            </span>
          </h1>

          <p className="text-[13px] leading-relaxed" style={{ color: "var(--text-muted)" }}>
            Ad-free streaming, offline downloads, and background play. <br className="hidden sm:block" />
            Cancel anytime, no hidden fees.
          </p>

          {/* Currently active banner */}
          {ownedPlan && (
            <div
              className="inline-flex items-center gap-2 mt-5 px-4 py-2 rounded-full text-[11px] font-bold"
              style={{ background: "rgba(34,197,94,0.1)", color: "#4ade80", border: "1px solid rgba(34,197,94,0.22)" }}
            >
              <CheckCircle2 size={12} strokeWidth={2.5} />
              You&apos;re on the <strong>{ownedPlan.name}</strong> plan · {ownedPlan.duration}
            </div>
          )}
        </div>
      </div>

      {/* ══ Plan cards ═══════════════════════════════════════════════════════ */}
      <div className="px-4 sm:px-5">
        {isLoading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 max-w-4xl mx-auto">
            {[1, 2, 3].map((i) => <PlanSkeleton key={i} />)}
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <AlertCircle size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>{error}</p>
            <button
              onClick={() => dispatch(fetchPackages())}
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              Try again
            </button>
          </div>
        ) : packages.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <Crown size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>No plans available</p>
          </div>
        ) : (
          <div
            className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 max-w-4xl mx-auto"
            style={{ alignItems: "start" }}
          >
            {packages.map((pkg, i) => (
              <PlanCard key={pkg.id} pkg={pkg} index={i} totalPlans={packages.length} onBuy={handleBuyPlan} />
            ))}
          </div>
        )}
      </div>

      {/* ══ Trust strip ══════════════════════════════════════════════════════ */}
      {!isLoading && packages.length > 0 && (
        <div className="flex items-center justify-center gap-6 mt-10 px-5 flex-wrap">
          {[
            { icon: "🔒", text: "Secure payment" },
            { icon: "↩", text: "Cancel anytime" },
            { icon: "🌐", text: "All devices" },
            { icon: "🎬", text: "HD quality" },
          ].map((item, i) => (
            <div
              key={i}
              className="flex items-center gap-1.5 text-[11px] font-medium"
              style={{ color: "var(--text-muted)" }}
            >
              <span style={{ fontSize: 14 }}>{item.icon}</span>
              {item.text}
            </div>
          ))}
        </div>
      )}

      <PaymentModal
        context={payCtx}
        onClose={() => setPayCtx(null)}
        onSuccess={() => { setPayCtx(null); dispatch(fetchPackages()); }}
      />
    </div>
  );
}
