import prisma from "@/lib/prisma";

interface ProfileBadgesProps {
  userId: number;
  lastonlineAt: Date | null;
  hits: number;
  createdAt: Date;
}

interface Badge {
  label: string;
  color: string;
  bgColor: string;
}

export default async function ProfileBadges({
  userId,
  lastonlineAt,
  hits,
  createdAt,
}: ProfileBadgesProps) {
  // Fetch custom badges from user_badges table
  let customBadges: { name: string; color: string }[] = [];
  try {
    customBadges = await prisma.$queryRawUnsafe(
      `SELECT name, color FROM user_badges WHERE user_id = $1`,
      userId
    );
  } catch {
    // user_badges table may not exist yet
  }

  const badges: Badge[] = [];

  // Auto-calculate badges
  const now = new Date();

  // Active 7 Days
  if (lastonlineAt) {
    const diffDays = (now.getTime() - new Date(lastonlineAt).getTime()) / (1000 * 60 * 60 * 24);
    if (diffDays <= 7) {
      badges.push({
        label: "Active 7 Days",
        color: "text-green-400",
        bgColor: "bg-green-500/15 border-green-500/30",
      });
    }
  }

  // Popular
  if (hits > 1000) {
    badges.push({
      label: "Popular",
      color: "text-gold",
      bgColor: "bg-gold/15 border-gold/30",
    });
  }

  // New Member
  const daysSinceCreated = (now.getTime() - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24);
  if (daysSinceCreated < 30) {
    badges.push({
      label: "New Member",
      color: "text-blue-400",
      bgColor: "bg-blue-500/15 border-blue-500/30",
    });
  }

  // Add custom badges from DB
  for (const cb of customBadges) {
    badges.push({
      label: cb.name,
      color: `text-${cb.color || "gold"}`,
      bgColor: "bg-surface-light border-white/10",
    });
  }

  if (badges.length === 0) return null;

  return (
    <div className="flex flex-wrap gap-2">
      {badges.map((badge) => (
        <span
          key={badge.label}
          className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold border ${badge.bgColor} ${badge.color}`}
        >
          {badge.label === "Active 7 Days" && (
            <span className="w-2 h-2 rounded-full bg-green-400 animate-pulse" />
          )}
          {badge.label === "Popular" && (
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 15l-5.878 3.09 1.123-6.545L.489 6.91l6.572-.955L10 0l2.939 5.955 6.572.955-4.756 4.635 1.123 6.545z" />
            </svg>
          )}
          {badge.label === "New Member" && (
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path d="M10 2a8 8 0 100 16 8 8 0 000-16zm1 11H9v-2h2v2zm0-4H9V5h2v4z" />
            </svg>
          )}
          {badge.label}
        </span>
      ))}
    </div>
  );
}
