import Link from "next/link";
import { prisma } from "@/lib/db";
import { listRecentBotJobLogs } from "@/lib/admin/bot-queries";
import { getSiteSettings } from "@/lib/settings/site-settings";

const TASK_LABELS: Record<string, string> = {
  CONFESSION: "İtiraf",
  QUOTE: "Güzel Söz",
  ROOM_ARTICLE: "Oda Makalesi",
  QUOTE_DAILY_ROTATION: "Günlük Söz Aktivasyonu",
};

export default async function AdminDashboardPage() {
  const [
    totalUsers,
    verifiedUsers,
    suspendedUsers,
    adminCount,
    confessionCount,
    quoteCount,
    roomCount,
    messageCount,
    pendingPhotoCount,
    unreadContactCount,
    recentBotJobs,
    settings,
  ] = await Promise.all([
    prisma.user.count(),
    prisma.user.count({ where: { emailVerifiedAt: { not: null } } }),
    prisma.user.count({ where: { status: "SUSPENDED" } }),
    prisma.user.count({ where: { role: "ADMIN" } }),
    prisma.confession.count(),
    prisma.quote.count(),
    prisma.room.count(),
    prisma.message.count(),
    prisma.photo.count({ where: { status: "PENDING" } }),
    prisma.contactMessage.count({ where: { isRead: false } }),
    listRecentBotJobLogs(5),
    getSiteSettings(),
  ]);

  const memberStats = [
    { label: "Toplam Üye", value: totalUsers },
    { label: "E-postası Doğrulanmış", value: verifiedUsers },
    { label: "Askıya Alınmış", value: suspendedUsers },
    { label: "Yönetici", value: adminCount },
  ];

  const contentStats = [
    { label: "İtiraf", value: confessionCount },
    { label: "Güzel Söz", value: quoteCount },
    { label: "Oda", value: roomCount },
    { label: "Mesaj", value: messageCount },
  ];

  const quickLinks = [
    {
      href: "/admin/fotograf-onay",
      label: "Bekleyen Fotoğraf Onayları",
      count: pendingPhotoCount,
      accent: pendingPhotoCount > 0,
    },
    {
      href: "/admin/iletisim",
      label: "Okunmamış İletişim Mesajları",
      count: unreadContactCount,
      accent: unreadContactCount > 0,
    },
    {
      href: "/admin/bot",
      label: "İçerik Botu Zamanlamaları",
      count: null,
      accent: false,
    },
  ];

  return (
    <div className="p-8">
      <div className="mb-7 flex items-center justify-between border-b border-border pb-6">
        <div>
          <h1 className="text-[22px]">Dashboard</h1>
          <p className="mt-0.5 text-[12.5px] text-text-muted">
            {new Date().toLocaleDateString("tr-TR", { day: "numeric", month: "long", year: "numeric", weekday: "long" })}
          </p>
        </div>
      </div>

      <h2 className="mb-3 text-[13px] font-bold text-text-muted">Üyelik</h2>
      <div className="mb-8 grid grid-cols-2 gap-4 lg:grid-cols-4">
        {memberStats.map((stat) => (
          <div key={stat.label} className="rounded-2xl border border-border bg-surface p-5">
            <div className="font-heading text-[26px]">{stat.value}</div>
            <div className="mt-1 text-[12.5px] text-text-muted">{stat.label}</div>
          </div>
        ))}
      </div>

      <h2 className="mb-3 text-[13px] font-bold text-text-muted">İçerik</h2>
      <div className="mb-8 grid grid-cols-2 gap-4 lg:grid-cols-4">
        {contentStats.map((stat) => (
          <div key={stat.label} className="rounded-2xl border border-border bg-surface p-5">
            <div className="font-heading text-[26px]">{stat.value}</div>
            <div className="mt-1 text-[12.5px] text-text-muted">{stat.label}</div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
        <div>
          <h2 className="mb-3 text-[13px] font-bold text-text-muted">Hızlı Erişim</h2>
          <div className="flex flex-col gap-2.5">
            {quickLinks.map((link) => (
              <Link
                key={link.href}
                href={link.href}
                className={`flex items-center justify-between rounded-2xl border p-4 transition-colors ${
                  link.accent ? "border-accent/40 bg-accent/5 hover:bg-accent/10" : "border-border bg-surface hover:border-accent"
                }`}
              >
                <span className="text-[13.5px] font-semibold">{link.label}</span>
                {link.count !== null && (
                  <span
                    className={`rounded-full px-2.5 py-0.5 text-[11.5px] font-bold ${
                      link.accent ? "bg-accent text-white" : "bg-bg-alt text-text-muted"
                    }`}
                  >
                    {link.count}
                  </span>
                )}
              </Link>
            ))}
          </div>
        </div>

        <div>
          <h2 className="mb-3 text-[13px] font-bold text-text-muted">Son Bot Çalışmaları</h2>
          {recentBotJobs.length === 0 ? (
            <p className="rounded-2xl border border-dashed border-border p-5 text-[13px] text-text-muted">
              Henüz bir bot çalışması yok. Zamanlama eklemek için{" "}
              <Link href="/admin/bot" className="font-semibold text-accent">
                İçerik Botu
              </Link>{" "}
              sayfasına git.
            </p>
          ) : (
            <div className="flex flex-col gap-1.5">
              {recentBotJobs.map((log) => (
                <div key={log.id} className="flex items-center justify-between rounded-xl border border-border bg-surface px-3 py-2.5">
                  <div className="flex items-center gap-2">
                    <span className="text-[13px] font-semibold">{TASK_LABELS[log.schedule.taskType]}</span>
                    <span
                      className={`rounded-full px-2 py-0.5 text-[10.5px] font-semibold ${
                        log.status === "SUCCESS" ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
                      }`}
                    >
                      {log.status === "SUCCESS" ? "Başarılı" : "Başarısız"}
                    </span>
                  </div>
                  <span className="text-[11.5px] text-text-muted">{log.runAt.toLocaleString("tr-TR")}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="mt-8 rounded-2xl border border-dashed border-border p-6 text-[13.5px] text-text-muted">
        {settings.gaMeasurementId ? (
          <>
            ✅ Google Analytics bağlı (<span className="font-mono">{settings.gaMeasurementId}</span>) — ziyaretçi
            verisi <span className="font-mono">analytics.google.com</span>&apos;a akıyor.
          </>
        ) : (
          <>
            Google Analytics henüz bağlı değil —{" "}
            <Link href="/admin/seo" className="font-semibold text-accent">
              SEO sayfasından
            </Link>{" "}
            ölçüm kimliğini girerek etkinleştirebilirsiniz.
          </>
        )}{" "}
        Bu verileri (ziyaretçi grafiği, arama motoru anahtar kelimeleri) doğrudan bu panelin içinde göstermek için
        ayrıca bir Google Cloud servis hesabı bağlantısı gerekiyor — canlıya alındıktan ve gerçek trafik oluştuktan
        sonra isterseniz bunu birlikte kuralım.
      </div>
    </div>
  );
}
