import prisma from "@/lib/prisma";

export const metadata = {
  title: "Engagement | Admin",
};

async function safeQuery<T>(query: string, fallback: T): Promise<T> {
  try {
    const result = await prisma.$queryRawUnsafe(query);
    return result as T;
  } catch {
    return fallback;
  }
}

export default async function AdminEngagementPage() {
  // Daily Active Users
  const [dauRows] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM users WHERE lastonline_at >= CURRENT_DATE`,
    [{ count: 0 }]
  );

  // Monthly Active Users
  const [mauRows] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM users WHERE lastonline_at >= CURRENT_DATE - interval '30 days'`,
    [{ count: 0 }]
  );

  // New registrations this month
  const [newRegsRows] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM users WHERE created_at >= date_trunc('month', CURRENT_DATE)`,
    [{ count: 0 }]
  );

  // Popular search terms
  const popularSearches = await safeQuery<{ term: string; count: number }[]>(
    `SELECT query as term, COUNT(*)::int as count FROM searches
     WHERE created_at >= CURRENT_DATE - interval '30 days' AND query IS NOT NULL AND query != ''
     GROUP BY query ORDER BY count DESC LIMIT 15`,
    []
  );

  // Top viewed profiles
  const topProfiles = await safeQuery<{ username: string; id_aw: string; views: number }[]>(
    `SELECT u.username, u.id_aw, COUNT(rv.id)::int as views
     FROM recently_viewed rv
     JOIN users u ON u.id = rv.viewed_user_id
     WHERE rv.created_at >= CURRENT_DATE - interval '30 days'
     GROUP BY u.id, u.username, u.id_aw
     ORDER BY views DESC
     LIMIT 15`,
    []
  );

  const dau = dauRows?.count ?? 0;
  const mau = mauRows?.count ?? 0;
  const newRegs = newRegsRows?.count ?? 0;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">User Engagement</h1>
        <p className="text-text-muted mt-1">Activity metrics and user behavior insights.</p>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <div className="flex items-center justify-between mb-3">
            <span className="text-text-muted text-sm">Daily Active Users</span>
            <svg className="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
            </svg>
          </div>
          <p className="text-3xl font-bold text-white">{dau.toLocaleString()}</p>
          <p className="text-text-muted text-xs mt-1">Users online today</p>
        </div>

        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <div className="flex items-center justify-between mb-3">
            <span className="text-text-muted text-sm">Monthly Active Users</span>
            <svg className="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </div>
          <p className="text-3xl font-bold text-white">{mau.toLocaleString()}</p>
          <p className="text-text-muted text-xs mt-1">Active in last 30 days</p>
        </div>

        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <div className="flex items-center justify-between mb-3">
            <span className="text-text-muted text-sm">New Registrations</span>
            <svg className="w-5 h-5 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
            </svg>
          </div>
          <p className="text-3xl font-bold text-white">{newRegs.toLocaleString()}</p>
          <p className="text-text-muted text-xs mt-1">This month</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Popular Search Terms */}
        <div className="bg-surface rounded-xl border border-surface-light">
          <div className="p-5 border-b border-surface-light">
            <h2 className="text-lg font-semibold text-white">Popular Search Terms</h2>
            <p className="text-text-muted text-sm">Last 30 days</p>
          </div>
          <div className="divide-y divide-surface-light">
            {popularSearches.length === 0 && (
              <div className="p-5 text-text-muted text-sm text-center">No search data available.</div>
            )}
            {popularSearches.map((s, i) => (
              <div key={i} className="flex items-center justify-between px-5 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-text-muted text-sm w-6">{i + 1}.</span>
                  <span className="text-white">{s.term}</span>
                </div>
                <span className="text-gold font-medium text-sm">{s.count.toLocaleString()} searches</span>
              </div>
            ))}
          </div>
        </div>

        {/* Top Viewed Profiles */}
        <div className="bg-surface rounded-xl border border-surface-light">
          <div className="p-5 border-b border-surface-light">
            <h2 className="text-lg font-semibold text-white">Top Viewed Profiles</h2>
            <p className="text-text-muted text-sm">Last 30 days</p>
          </div>
          <div className="divide-y divide-surface-light">
            {topProfiles.length === 0 && (
              <div className="p-5 text-text-muted text-sm text-center">No profile view data available.</div>
            )}
            {topProfiles.map((p, i) => (
              <div key={i} className="flex items-center justify-between px-5 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-text-muted text-sm w-6">{i + 1}.</span>
                  <a
                    href={`/view/${p.id_aw}`}
                    className="text-white hover:text-gold transition-colors"
                  >
                    {p.username || p.id_aw}
                  </a>
                </div>
                <span className="text-gold font-medium text-sm">{p.views.toLocaleString()} views</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
