import { db } from "@/lib/db";
import { videos, plans, products, categories, posts, postReactions } from "@/lib/db/schema";
import { desc, eq } from "drizzle-orm";
import VideoCard from "@/components/VideoCard";
import Link from "next/link";
import { ArrowRight } from "lucide-react";
import { formatCount } from "@/lib/formatCount";
import { getSetting } from "@/lib/settings";
import StickyCategoryBar from "@/components/StickyCategoryBar";

export const dynamic = "force-dynamic";

const TIER_STYLE: Record<string, { gradient: string; border: string; badge: string }> = {
  starter: { gradient: "from-blue-900/60 to-blue-950/60", border: "border-blue-700/50", badge: "bg-blue-600" },
  plus: { gradient: "from-purple-900/60 to-purple-950/60", border: "border-purple-700/50", badge: "bg-purple-600" },
  premium: { gradient: "from-amber-700/60 via-red-800/60 to-red-950/60", border: "border-amber-500/50", badge: "bg-gradient-to-r from-amber-500 to-red-600" },
};

export default async function HomePage() {
  const featured = (await db.select().from(videos).where(eq(videos.featured, true))).slice(0, 6);
  const latest = (await db.select().from(videos).orderBy(desc(videos.createdAt))).slice(0, 8);
  const popular = (await db.select().from(videos).orderBy(desc(videos.views))).slice(0, 6);
  const plansList = await db.select().from(plans).where(eq(plans.active, true));
  const shopItems = (await db.select().from(products)).slice(0, 3);
  const cats = await db.select().from(categories);

  // Real counts (actual posts + actual "prayed" reactions), plus an
  // admin-configurable starting number so a brand-new site doesn't show 1 or 2.
  // Every increase from here on is 100% real activity — the base is just a
  // fixed starting point, same as a store starting its "customers served"
  // counter above zero at launch.
  const allPosts = await db.select().from(posts);
  const allPrayedReactions = (await db.select().from(postReactions)).filter((r) => r.type === "prayed");
  const requestBase = parseInt(await getSetting("communityRequestBase", "1234"), 10);
  const prayerBase = parseInt(await getSetting("communityPrayerBase", "123456"), 10);
  const requestsShared = allPosts.length + requestBase;
  const prayersLifted = allPrayedReactions.length + prayerBase;

  return (
    <div className="max-w-[1400px] mx-auto">
      {/* category bar — sticky, breaks out of padding via negative margins on the bar itself */}
      <StickyCategoryBar categories={cats} />

      <div className="flex flex-col md:flex-row gap-6 pt-5">
        {/* ============ MAIN COLUMN ============ */}
        <div className="flex-1 min-w-0 space-y-10">
          {/* community hero */}
          <div className="rounded-xl p-4 sm:p-5 bg-gradient-to-br from-[#3d1220] to-[#1a0d12] border border-[#4d1a28]">
            <div className="flex items-start justify-between gap-3 mb-3">
              <div>
                <h2 className="text-base sm:text-xl font-bold">Our Community</h2>
                <p className="text-xs sm:text-sm text-neutral-300">Pray together. Grow together.</p>
              </div>
              <Link
                href="/community"
                className="shrink-0 border border-red-500 text-red-400 hover:bg-red-600 hover:text-white rounded-lg px-3 py-1.5 text-xs sm:text-sm transition-colors font-medium whitespace-nowrap"
              >
                Pray with us →
              </Link>
            </div>
            <p className="text-xs text-neutral-400 mb-3 hidden sm:block">
              Share prayer requests, encourage one another, and grow in faith with believers from around the world.
            </p>
            <div className="flex gap-2 flex-wrap">
              <span className="bg-[#6b5313]/60 border border-[#8a6d1c] rounded-full px-3 py-1 text-xs">
                ❤️ <strong>{requestsShared.toLocaleString()}</strong> requests
              </span>
              <span className="bg-[#6b5313]/60 border border-[#8a6d1c] rounded-full px-3 py-1 text-xs">
                🕐 <strong>{prayersLifted.toLocaleString()}</strong> prayers lifted
              </span>
            </div>
          </div>

          {/* Featured */}
          <section>
            <h2 className="text-xl font-bold mb-4">Featured</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
              {featured.slice(0, 2).map((v) => <VideoCard key={v.id} video={v} large />)}
            </div>
            {featured.length > 2 && (
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-5">
                {featured.slice(2).map((v) => <VideoCard key={v.id} video={v} />)}
              </div>
            )}
            {featured.length === 0 && (
              <p className="text-neutral-500 text-sm">No featured videos yet — add some from the admin panel.</p>
            )}
          </section>

          {/* Latest */}
          <section>
            <h2 className="text-xl font-bold mb-4">Latest</h2>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {latest.map((v) => <VideoCard key={v.id} video={v} />)}
              {latest.length === 0 && (
                <p className="text-neutral-500 text-sm col-span-full">No videos yet — add some from the admin panel.</p>
              )}
            </div>
          </section>

          {/* Shop */}
          <section>
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold">Shop</h2>
              <Link href="/shop" className="text-red-500 text-sm font-semibold">View all</Link>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {shopItems.map((p) => (
                <Link key={p.id} href={`/shop/${p.slug}`} className="card overflow-hidden hover:border-neutral-600 transition-colors">
                  <div className="aspect-square bg-neutral-800">
                    {p.imageUrl && <img src={p.imageUrl} className="w-full h-full object-cover" />}
                  </div>
                  <div className="p-3">
                    <div className="flex gap-2 mb-1">
                      <span className="text-xs bg-green-900 text-green-300 px-2 py-0.5 rounded-full">Digital</span>
                      {p.featured && <span className="text-xs bg-amber-900 text-amber-300 px-2 py-0.5 rounded-full">Featured</span>}
                    </div>
                    <h3 className="font-semibold mt-1 text-sm line-clamp-2">{p.title}</h3>
                    <p className="mt-1">
                      {p.compareAtPrice && <span className="line-through text-neutral-500 mr-2 text-sm">${p.compareAtPrice.toFixed(2)}</span>}
                      <span className="font-bold">${p.price?.toFixed(2)}</span>
                    </p>
                  </div>
                </Link>
              ))}
            </div>
          </section>
        </div>

        {/* ============ RIGHT SIDEBAR ============ */}
        <aside className="w-full md:w-72 shrink-0 space-y-6">
          {/* Most Popular */}
          <div className="card p-4">
            <h2 className="text-lg font-bold mb-1">Most Popular</h2>
            <p className="text-xs text-neutral-500 mb-4">Videos our community watches most</p>
            <div className="space-y-4">
              {popular.map((v) => (
                <Link key={v.id} href={`/contents/${v.slug}`} className="flex gap-3 group">
                  <div className="w-24 aspect-video rounded-md overflow-hidden bg-neutral-800 shrink-0">
                    <img
                      src={v.thumbnailUrl || `https://img.youtube.com/vi/${v.youtubeId}/hqdefault.jpg`}
                      alt={v.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="min-w-0">
                    <h3 className="text-sm font-semibold line-clamp-2 group-hover:text-red-500">{v.title}</h3>
                    <p className="text-xs text-neutral-500 mt-1">{formatCount(v.views)} views</p>
                  </div>
                </Link>
              ))}
              {popular.length === 0 && <p className="text-neutral-500 text-sm">No videos yet.</p>}
            </div>
          </div>

          {/* Membership plans box */}
          <div className="card p-4 overflow-hidden">
            <h2 className="text-lg font-bold mb-1">Our Membership Plans</h2>
            <p className="text-xs text-neutral-500 mb-4">Unlock more devotionals</p>
            <div className="space-y-3">
              {plansList
                .filter((p) => p.tier !== "free")
                .sort((a, b) => a.price - b.price) // small to big
                .map((p) => {
                const features = JSON.parse(p.features) as string[];
                const style = TIER_STYLE[p.tier] || TIER_STYLE.starter;
                const isPremium = p.tier === "premium";
                return (
                  <Link
                    key={p.id}
                    href="/subscription/plans"
                    className={`relative block rounded-lg p-3 bg-gradient-to-br ${style.gradient} border ${style.border} cursor-pointer transform transition-transform duration-150 hover:scale-105 active:scale-95 ${
                      isPremium ? "shadow-md shadow-red-900/20" : ""
                    }`}
                  >
                    {isPremium && (
                      <span className="absolute -top-2 right-3 bg-gradient-to-r from-amber-400 to-red-500 text-black text-[9px] font-bold px-2 py-0.5 rounded-full whitespace-nowrap">
                        POPULAR
                      </span>
                    )}
                    <div className="flex items-center justify-between gap-2 mb-1">
                      <div className="flex items-center gap-1.5 min-w-0">
                        <span className={`inline-block ${style.badge} text-white text-[10px] font-semibold px-2 py-0.5 rounded-full shrink-0`}>
                          {p.name}
                        </span>
                      </div>
                      <p className="font-bold text-sm whitespace-nowrap shrink-0">
                        ${p.price.toFixed(2)}<span className="text-[10px] text-neutral-400 font-normal">/{p.interval}</span>
                      </p>
                    </div>
                    <ul className="text-xs text-neutral-300 mt-1.5 space-y-0.5">
                      {features.slice(0, 2).map((f, i) => <li key={i} className="truncate">• {f}</li>)}
                    </ul>
                  </Link>
                );
              })}
            </div>
            <Link
              href="/subscription/plans"
              className="flex items-center justify-center gap-2 bg-gradient-to-r from-amber-500 to-red-600 hover:from-amber-400 hover:to-red-500 rounded-lg text-center mt-4 py-3 px-3 text-sm font-semibold leading-snug transition-colors"
            >
              See all membership plans
              <ArrowRight size={15} className="shrink-0" />
            </Link>
          </div>
        </aside>
      </div>
    </div>
  );
}
