import prisma from "@/lib/prisma";

export const metadata = {
  title: "AI Moderation | 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 AdminAIModerationPage() {
  // Total photos moderated
  const [totalModerated] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM photos WHERE moderation_status IS NOT NULL`,
    [{ count: 0 }]
  );

  // Approved
  const [approvedCount] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM photos WHERE moderation_status = 'approved'`,
    [{ count: 0 }]
  );

  // Rejected
  const [rejectedCount] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM photos WHERE moderation_status = 'rejected'`,
    [{ count: 0 }]
  );

  // Pending
  const [pendingCount] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(*)::int as count FROM photos WHERE moderation_status = 'pending'`,
    [{ count: 0 }]
  );

  // Recent moderation decisions
  const recentDecisions = await safeQuery<{
    id: number;
    user_id: number;
    username: string | null;
    moderation_status: string;
    moderation_reason: string | null;
    moderated_at: string | null;
  }[]>(
    `SELECT p.id, p.user_id, u.username,
            p.moderation_status,
            p.moderation_reason,
            p.updated_at::text as moderated_at
     FROM photos p
     LEFT JOIN users u ON u.id = p.user_id
     WHERE p.moderation_status IS NOT NULL
     ORDER BY p.updated_at DESC
     LIMIT 25`,
    []
  );

  // Moderation volume last 7 days
  const dailyVolume = await safeQuery<{ day: string; count: number }[]>(
    `SELECT DATE(updated_at)::text as day, COUNT(*)::int as count
     FROM photos
     WHERE moderation_status IS NOT NULL AND updated_at >= CURRENT_DATE - interval '7 days'
     GROUP BY DATE(updated_at)
     ORDER BY day ASC`,
    []
  );

  const total = totalModerated?.count ?? 0;
  const approved = approvedCount?.count ?? 0;
  const rejected = rejectedCount?.count ?? 0;
  const pending = pendingCount?.count ?? 0;
  const approvedPct = total > 0 ? ((approved / total) * 100).toFixed(1) : "0";
  const rejectedPct = total > 0 ? ((rejected / total) * 100).toFixed(1) : "0";

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">AI Content Moderation</h1>
        <p className="text-text-muted mt-1">Photo moderation statistics and recent decisions.</p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <span className="text-text-muted text-sm">Total Moderated</span>
          <p className="text-3xl font-bold text-white mt-2">{total.toLocaleString()}</p>
        </div>
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <span className="text-text-muted text-sm">Approved</span>
          <p className="text-3xl font-bold text-green-400 mt-2">{approvedPct}%</p>
          <p className="text-text-muted text-xs">{approved.toLocaleString()} photos</p>
        </div>
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <span className="text-text-muted text-sm">Rejected</span>
          <p className="text-3xl font-bold text-red-400 mt-2">{rejectedPct}%</p>
          <p className="text-text-muted text-xs">{rejected.toLocaleString()} photos</p>
        </div>
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <span className="text-text-muted text-sm">Pending Review</span>
          <p className="text-3xl font-bold text-gold mt-2">{pending.toLocaleString()}</p>
        </div>
      </div>

      {/* Daily volume chart (simple bar chart) */}
      {dailyVolume.length > 0 && (
        <div className="bg-surface rounded-xl border border-surface-light p-5">
          <h2 className="text-lg font-semibold text-white mb-4">Moderation Volume (Last 7 Days)</h2>
          <div className="flex items-end gap-2 h-32">
            {dailyVolume.map((d) => {
              const maxCount = Math.max(...dailyVolume.map((v) => v.count), 1);
              const heightPct = (d.count / maxCount) * 100;
              return (
                <div key={d.day} className="flex-1 flex flex-col items-center gap-1">
                  <span className="text-xs text-text-muted">{d.count}</span>
                  <div
                    className="w-full bg-gold/80 rounded-t-md transition-all"
                    style={{ height: `${heightPct}%`, minHeight: "4px" }}
                  />
                  <span className="text-xs text-text-muted">
                    {new Date(d.day).toLocaleDateString(undefined, { weekday: "short" })}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Recent decisions */}
      <div className="bg-surface rounded-xl border border-surface-light overflow-hidden">
        <div className="p-5 border-b border-surface-light">
          <h2 className="text-lg font-semibold text-white">Recent Moderation Decisions</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-surface-light">
                <th className="text-left text-text-muted text-xs font-medium uppercase px-4 py-3">Photo ID</th>
                <th className="text-left text-text-muted text-xs font-medium uppercase px-4 py-3">User</th>
                <th className="text-left text-text-muted text-xs font-medium uppercase px-4 py-3">Status</th>
                <th className="text-left text-text-muted text-xs font-medium uppercase px-4 py-3">Reason</th>
                <th className="text-left text-text-muted text-xs font-medium uppercase px-4 py-3">Date</th>
              </tr>
            </thead>
            <tbody>
              {recentDecisions.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-4 py-8 text-center text-text-muted">
                    No moderation decisions found.
                  </td>
                </tr>
              )}
              {recentDecisions.map((d) => (
                <tr key={d.id} className="border-b border-surface-light last:border-0 hover:bg-surface-light/50">
                  <td className="px-4 py-3 text-white text-sm">#{d.id}</td>
                  <td className="px-4 py-3">
                    <a
                      href={`/admin/users?search=${d.user_id}`}
                      className="text-white hover:text-gold text-sm transition-colors"
                    >
                      {d.username ?? `User #${d.user_id}`}
                    </a>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        d.moderation_status === "approved"
                          ? "bg-green-500/20 text-green-400"
                          : d.moderation_status === "rejected"
                          ? "bg-red-500/20 text-red-400"
                          : "bg-amber-500/20 text-amber-400"
                      }`}
                    >
                      {d.moderation_status}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-text-muted text-sm max-w-xs truncate">
                    {d.moderation_reason ?? "-"}
                  </td>
                  <td className="px-4 py-3 text-text-muted text-sm">
                    {d.moderated_at
                      ? new Date(d.moderated_at).toLocaleDateString()
                      : "-"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
