﻿import Link from "next/link";
import { prisma } from "@/lib/db";

export const dynamic = "force-dynamic";

export default async function AdminDashboard() {
  const [projects, posts, experiences, messages, audit, products] = await Promise.all([
    prisma.project.count({ where: { deletedAt: null } }),
    prisma.blogPost.count({ where: { deletedAt: null } }),
    prisma.experience.count(),
    prisma.contactMessage.count(),
    prisma.auditLog.findMany({ orderBy: { createdAt: "desc" }, take: 6 }),
    prisma.product.count(),
  ]);

  const publishedProjects = await prisma.project.count({ where: { status: "PUBLISHED", deletedAt: null } });
  const publishedPosts = await prisma.blogPost.count({ where: { status: "PUBLISHED", deletedAt: null } });
  const draftPosts = await prisma.blogPost.count({ where: { status: "DRAFT", deletedAt: null } });
  const unread = await prisma.contactMessage.count({ where: { status: "UNREAD" } });

  // Real status checks â€” if no monitoring configured, show NOT CONNECTED (per spec 24)
  const hasMonitoring = !!process.env.STATUS_API_URL;
  const hasAnalytics = !!process.env.ANALYTICS_TOKEN;
  const hasGithub = !!process.env.GITHUB_TOKEN;

  const hour = new Date().getHours();
  const greeting = hour < 12 ? "GOOD MORNING" : hour < 18 ? "GOOD AFTERNOON" : "GOOD EVENING";

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap justify-between gap-4 items-end">
        <div>
          <h1 className="text-[22px] sm:text-[28px] font-[800] tracking-[-0.04em] text-white">{greeting}, RAVNEET.</h1>
          <p className="text-sm text-white/50">Here&apos;s what&apos;s happening across your website.</p>
        </div>
        <div className="flex gap-2">
          <Link href="/admin/blog/new" className="px-4 py-2 rounded-full bg-white text-black font-semibold text-sm">+ New Blog Post</Link>
          <Link href="/admin/content/work/new" className="px-4 py-2 rounded-full border border-white/15 text-white font-semibold text-sm">+ New Project</Link>
        </div>
      </div>

      <div className="grid sm:grid-cols-3 lg:grid-cols-6 gap-3">
        {[
          { label:"+ New Blog Post", href:"/admin/blog/new" },
          { label:"+ New Project", href:"/admin/content/work/new" },
          { label:"+ Experience", href:"/admin/content/experience" },
          { label:"+ Skill", href:"/admin/content/skills" },
          { label:"View Messages", href:"/admin/messages" },
          { label:"Preview Website", href:"/", external:true },
        ].map(a=>(
          <Link key={a.label} href={a.href} target={(a as any).external ? "_blank" : undefined} className="rounded-2xl border border-white/10 bg-white/[0.04] p-4 text-center hover:bg-white hover:text-black text-white text-sm font-medium">
            {a.label}
          </Link>
        ))}
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
          <p className="text-xs tracking-widest text-white/30">ARTICLES</p>
          <p className="text-2xl font-bold text-white mt-1">{posts} <span className="text-sm font-normal text-white/40">Published: {publishedPosts}</span></p>
          <p className="text-xs text-white/30 mt-1">Drafts: {draftPosts} â€¢ Total: {posts}</p>
          {posts===0 && <p className="text-xs text-white/20 mt-1">No blog posts yet â€” create your first article.</p>}
        </div>
        <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
          <p className="text-xs tracking-widest text-white/30">PROJECTS</p>
          <p className="text-2xl font-bold text-white mt-1">{projects} <span className="text-sm font-normal text-white/40">Published: {publishedProjects}</span></p>
          {projects===0 ? <p className="text-xs text-white/20 mt-1">No projects yet â€” create your first project.</p> : <p className="text-xs text-white/30">Total: {projects}</p>}
        </div>
        <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
          <p className="text-xs tracking-widest text-white/30">EXPERIENCE</p>
          <p className="text-2xl font-bold text-white mt-1">{experiences} entries</p>
          {experiences===0 && <p className="text-xs text-white/20">No experience entries.</p>}
        </div>
        <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
          <p className="text-xs tracking-widest text-white/30">CONTACTS</p>
          <p className="text-2xl font-bold text-white mt-1">{unread} unread</p>
          <p className="text-xs text-white/40">{messages} total</p>
          {messages===0 && <p className="text-xs text-white/20">No messages yet.</p>}
        </div>
        <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
          <p className="text-xs tracking-widest text-white/30">PRODUCTS</p>
          <p className="text-2xl font-bold text-white mt-1">{products}</p>
          <p className="text-xs text-white/40">Zyphron + FreeDash</p>
        </div>
        <div className={`rounded-2xl border p-5 ${hasMonitoring ? "border-emerald-500/20 bg-emerald-500/10" : "border-white/10 bg-white/[0.04]"}`}>
          <p className="text-xs tracking-widest text-white/30">STATUS</p>
          {hasMonitoring ? (
            <>
              <p className="text-sm font-bold text-emerald-300 mt-1 flex items-center gap-2"><span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" /> ONLINE</p>
              <p className="text-xs text-white/40">Monitoring connected</p>
            </>
          ) : (
            <>
              <p className="text-sm font-bold text-white/40 mt-1">STATUS MONITORING NOT CONFIGURED</p>
              <p className="text-xs text-white/30">Set STATUS_API_URL to enable</p>
            </>
          )}
        </div>
      </div>

      <div className="rounded-2xl border border-white/10 bg-gradient-to-br from-white/[0.06] to-transparent p-6">
        <p className="text-xs tracking-widest text-white/30 uppercase">Ravneet Control Center</p>
        <div className="mt-3 grid sm:grid-cols-4 gap-3 text-sm">
          <div className={`rounded-xl p-4 text-center border ${hasMonitoring ? "bg-white text-black border-white" : "bg-white/[0.04] border-white/10 text-white/40"}`}>
            <p className="font-bold">{hasMonitoring ? "WEBSITE â— ONLINE" : "WEBSITE â€” NOT CONNECTED"}</p><p className="text-xs opacity-60">ravneetbrar.in</p>
          </div>
          <div className="rounded-xl border border-white/10 bg-white/[0.04] p-4 text-center text-white">
            <p className="font-bold">ZYPHRON</p><p className="text-xs opacity-60">zyphron.cloud â€” {hasMonitoring ? "â— ONLINE" : "NOT CONNECTED"}</p>
          </div>
          <div className="rounded-xl border border-white/10 bg-white/[0.04] p-4 text-center text-white">
            <p className="font-bold">FREEDASH</p><p className="text-xs opacity-60">freedash.zyphron.cloud â€” {hasMonitoring ? "â— ONLINE" : "NOT CONNECTED"}</p>
          </div>
          <div className="rounded-xl border border-white/10 bg-white/[0.04] p-4 text-center text-white">
            <p className="font-bold">{publishedPosts} ARTICLES â€¢ {publishedProjects} PROJECTS</p><p className="text-xs opacity-60">{unread} UNREAD â€¢ {hasAnalytics ? "Analytics connected" : "ANALYTICS NOT CONNECTED"}</p>
          </div>
        </div>
        {hasGithub ? <p className="text-xs text-white/20 mt-3">GitHub connected</p> : <p className="text-xs text-white/20 mt-3">GITHUB NOT CONNECTED â€” set GITHUB_TOKEN to see repos</p>}
      </div>

      <div className="rounded-2xl border border-white/10 bg-white/[0.04] p-5">
        <h2 className="font-semibold text-white">RECENT ACTIVITY</h2>
        {audit.length===0 ? (
          <p className="text-sm text-white/30 mt-3">No activity yet.</p>
        ) : (
          <div className="mt-3 space-y-2">
            {audit.map(a=>(
              <div key={a.id} className="flex justify-between gap-4 rounded-xl bg-black/20 border border-white/5 px-4 py-2.5">
                <span className="text-sm text-white/70"><b className="text-white">{a.user}</b> {a.action}{a.detail ? ` â€” ${a.detail}` : ""}</span>
                <span className="text-xs text-white/30 shrink-0">{new Date(a.createdAt).toLocaleString()}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      <p className="text-xs text-white/20">Real data only â€” counts from database. Empty states when 0. No fabricated numbers.</p>
    </div>
  );
}
