import { db } from "@/lib/db";
import { users, posts, postReactions, comments, videoPlays, tips } from "@/lib/db/schema";
import { eq, desc, asc } from "drizzle-orm";
import { notFound } from "next/navigation";
import { getUserMissionProgress } from "@/lib/missions";
import CrossBadge from "@/components/CrossBadge";
import { Target } from "lucide-react";
import ProfilePostsClient from "@/components/ProfilePostsClient";

export const dynamic = "force-dynamic";

const TIER_STYLE: Record<string, { label: string; className: string }> = {
  starter: { label: "Starter", className: "bg-blue-900/50 text-blue-400 border border-blue-700/50" },
  plus: { label: "Plus", className: "bg-purple-900/50 text-purple-400 border border-purple-700/50" },
  premium: { label: "Premium", className: "bg-gradient-to-r from-amber-500 to-red-600 text-white" },
};

export default async function PublicProfilePage({ params }: { params: Promise<{ userId: string }> }) {
  const { userId } = await params;
  const user = (await db.select().from(users).where(eq(users.id, userId)))[0];
  if (!user) return notFound();

  const myPosts = await db.select().from(posts).where(eq(posts.userId, userId)).orderBy(desc(posts.createdAt));
  const myReactionsGiven = await db.select().from(postReactions).where(eq(postReactions.userId, userId));
  const prayedGiven = myReactionsGiven.filter((r) => r.type === "prayed").length;
  const myComments = await db.select().from(comments).where(eq(comments.userId, userId));
  const myVideoPlays = await db.select().from(videoPlays).where(eq(videoPlays.userId, userId));

  const allPostsByDate = await db.select().from(posts).orderBy(asc(posts.createdAt));
  const firstEverPostId = allPostsByDate.find((p) => p.userId === userId)?.id;

  const isPrayerWarrior = prayedGiven >= 5;
  const isCommunityHelper = myComments.length >= 3;

  // Real check — has this person ever actually given a confirmed tip?
  const mySupport = await db.select().from(tips).where(eq(tips.userId, userId));
  const isSupporter = mySupport.some((t) => t.status === "paid" || t.status === "active");

  const missionProgress = await getUserMissionProgress(userId);
  const tierInfo = TIER_STYLE[user.tier];

  const postsForDisplay = myPosts.slice(0, 5).map((p) => ({
    id: p.id,
    content: p.content,
    createdAt: p.createdAt ? p.createdAt.toString() : new Date().toString(),
    prayedCount: p.prayedCount,
    heartCount: p.heartCount,
    sparkleCount: p.sparkleCount,
    likeCount: p.likeCount,
  }));

  return (
    <div className="max-w-3xl mx-auto">
      {/* Cover + avatar — avatar sits OUTSIDE the overflow-hidden cover box so it never gets clipped */}
      <div className="relative mb-16">
        <div className="h-48 rounded-xl overflow-hidden bg-gradient-to-br from-[#3d1220] to-[#1a0d12] border border-[#4d1a28]">
          {user.coverUrl && <img src={user.coverUrl} className="w-full h-full object-cover" />}
        </div>
        <div className="absolute -bottom-12 left-6 w-24 h-24 rounded-full bg-neutral-800 border-4 border-black overflow-hidden flex items-center justify-center text-2xl font-bold z-10">
          {user.avatarUrl ? <img src={user.avatarUrl} className="w-full h-full object-cover" /> : user.name.charAt(0).toUpperCase()}
        </div>
      </div>

      <div className="px-1 mb-6">
        <div className="flex items-center gap-2 flex-wrap">
          <h1 className="text-xl font-bold">{user.name}</h1>
          <CrossBadge size={16} />
          {tierInfo && (
            <span className={`text-xs font-semibold px-2.5 py-0.5 rounded-full ${tierInfo.className}`}>
              ⭐ {tierInfo.label} Member
            </span>
          )}
          {isSupporter && (
            <span className="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-red-900/50 text-red-400 border border-red-700/50">
              ❤️ Supporter
            </span>
          )}
        </div>
        <p className="text-neutral-500 text-sm capitalize">{user.role === "admin" ? "Admin" : "Member"}</p>

        {(isPrayerWarrior || isCommunityHelper || firstEverPostId) && (
          <div className="flex flex-wrap gap-2 mt-3">
            {isPrayerWarrior && <span className="text-xs bg-amber-900/40 text-amber-400 px-3 py-1 rounded-full">🙏 Prayer Warrior</span>}
            {isCommunityHelper && <span className="text-xs bg-blue-900/40 text-blue-400 px-3 py-1 rounded-full">💬 Community Helper</span>}
            {firstEverPostId && <span className="text-xs bg-purple-900/40 text-purple-400 px-3 py-1 rounded-full">🌟 First Post</span>}
          </div>
        )}
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        <div className="card p-4 text-center bg-gradient-to-br from-red-950/40 to-transparent border-red-900/30">
          <p className="text-2xl font-bold text-red-400">{myPosts.length}</p>
          <p className="text-xs text-neutral-500 mt-1">Prayer requests shared</p>
        </div>
        <div className="card p-4 text-center bg-gradient-to-br from-amber-950/40 to-transparent border-amber-900/30">
          <p className="text-2xl font-bold text-amber-400">{prayedGiven}</p>
          <p className="text-xs text-neutral-500 mt-1">Times prayed for others</p>
        </div>
        <div className="card p-4 text-center bg-gradient-to-br from-blue-950/40 to-transparent border-blue-900/30">
          <p className="text-2xl font-bold text-blue-400">{myComments.length}</p>
          <p className="text-xs text-neutral-500 mt-1">Encouragement comments</p>
        </div>
        <div className="card p-4 text-center bg-gradient-to-br from-purple-950/40 to-transparent border-purple-900/30">
          <p className="text-2xl font-bold text-purple-400">{myVideoPlays.length}</p>
          <p className="text-xs text-neutral-500 mt-1">Videos watched</p>
        </div>
      </div>

      {missionProgress.length > 0 && (
        <div className="card p-5 mb-6 bg-gradient-to-br from-neutral-900 to-neutral-950 border-neutral-800">
          <h3 className="font-bold mb-3 flex items-center gap-2"><Target size={16} className="text-amber-400" /> Missions</h3>
          <div className="space-y-4">
            {missionProgress.map((mp, i) => {
              const colors = ["from-red-600 to-amber-500", "from-purple-600 to-blue-500", "from-emerald-600 to-teal-400", "from-pink-600 to-red-500"];
              const color = colors[i % colors.length];
              return (
                <div key={mp.mission.id}>
                  <div className="flex justify-between text-xs mb-1.5">
                    <span className="font-semibold">{mp.mission.title}</span>
                    <span className={mp.completedEver ? "text-green-400 font-semibold" : "text-neutral-400"}>
                      {mp.completedEver ? "✓ Completed" : `${mp.current}/${mp.mission.threshold}`}
                    </span>
                  </div>
                  <div className="h-2.5 bg-neutral-900 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full bg-gradient-to-r ${mp.completedEver ? "from-green-600 to-emerald-400" : color} transition-all`}
                      style={{ width: `${Math.min(100, (mp.current / mp.mission.threshold) * 100)}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <ProfilePostsClient posts={postsForDisplay} authorName={user.name} profileUserId={user.id} />
    </div>
  );
}
