import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { FileText, Briefcase, ShoppingBag, Mail, Clock, Wrench } from "lucide-react";
import { formatDate } from "@/lib/types";

export const dynamic = "force-dynamic";

export default async function AdminDashboard() {
  const session = await getSession();
  if (!session.isLoggedIn) redirect("/admin/login");

  const [postCount, projectCount, productCount, timelineCount, usesCount, unreadMessages, recentMessages, recentPosts] =
    await Promise.all([
      prisma.post.count(),
      prisma.project.count(),
      prisma.product.count(),
      prisma.timelineEvent.count(),
      prisma.usesItem.count(),
      prisma.contactMessage.count({ where: { isRead: false } }),
      prisma.contactMessage.findMany({ orderBy: { createdAt: "desc" }, take: 5 }),
      prisma.post.findMany({ orderBy: { publishedAt: "desc" }, take: 5 }),
    ]);

  const stats = [
    { label: "نوشته‌ها", value: postCount, icon: FileText, href: "/admin/posts", color: "text-blue-400" },
    { label: "پروژه‌ها", value: projectCount, icon: Briefcase, href: "/admin/projects", color: "text-purple-400" },
    { label: "محصولات", value: productCount, icon: ShoppingBag, href: "/admin/products", color: "text-green-400" },
    { label: "رویدادهای تایم‌لاین", value: timelineCount, icon: Clock, href: "/admin/timeline", color: "text-orange-400" },
    { label: "ابزارها", value: usesCount, icon: Wrench, href: "/admin/uses", color: "text-yellow-400" },
    {
      label: "پیام‌های خوانده‌نشده",
      value: unreadMessages,
      icon: Mail,
      href: "/admin/messages",
      color: unreadMessages > 0 ? "text-accent" : "text-text-secondary",
    },
  ];

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-text-primary">داشبورد</h1>
        <p className="text-text-secondary mt-1">خوش آمدی، {session.username} 👋</p>
      </div>

      {/* Stats grid */}
      <div className="grid gap-4 grid-cols-2 lg:grid-cols-3 mb-10">
        {stats.map((stat) => (
          <a
            key={stat.href}
            href={stat.href}
            className="group rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/30 hover:bg-surface-hover"
          >
            <div className="flex items-start justify-between">
              <div>
                <div className="text-3xl font-bold text-text-primary">{stat.value}</div>
                <div className="mt-1 text-sm text-text-secondary">{stat.label}</div>
              </div>
              <div className={`mt-1 ${stat.color}`}>
                <stat.icon size={22} />
              </div>
            </div>
          </a>
        ))}
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Recent posts */}
        <div className="rounded-xl border border-border bg-surface p-5">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-semibold text-text-primary">آخرین نوشته‌ها</h2>
            <a href="/admin/posts/new" className="text-xs text-accent hover:text-accent-hover">+ جدید</a>
          </div>
          {recentPosts.length === 0 ? (
            <p className="text-sm text-text-secondary py-4 text-center">هنوز نوشته‌ای ندارید</p>
          ) : (
            <div className="space-y-3">
              {recentPosts.map((post) => (
                <a
                  key={post.id}
                  href={`/admin/posts/${post.id}`}
                  className="flex items-start justify-between gap-3 rounded-lg p-2 hover:bg-surface-hover transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-text-primary line-clamp-1">{post.title}</div>
                    <div className="mt-0.5 font-mono text-xs text-text-secondary">
                      {formatDate(post.publishedAt, "fa")} · {post.locale}
                    </div>
                  </div>
                  {post.featured && (
                    <span className="shrink-0 text-xs text-accent">★</span>
                  )}
                </a>
              ))}
            </div>
          )}
        </div>

        {/* Recent messages */}
        <div className="rounded-xl border border-border bg-surface p-5">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-semibold text-text-primary">پیام‌های اخیر</h2>
            <a href="/admin/messages" className="text-xs text-accent hover:text-accent-hover">مشاهده همه</a>
          </div>
          {recentMessages.length === 0 ? (
            <p className="text-sm text-text-secondary py-4 text-center">هنوز پیامی دریافت نشده</p>
          ) : (
            <div className="space-y-3">
              {recentMessages.map((msg) => (
                <a
                  key={msg.id}
                  href="/admin/messages"
                  className="flex items-start gap-3 rounded-lg p-2 hover:bg-surface-hover transition-colors"
                >
                  <div className={`mt-1 h-2 w-2 shrink-0 rounded-full ${!msg.isRead ? "bg-accent" : "bg-border"}`} />
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-text-primary">{msg.name}</div>
                    <div className="text-xs text-text-secondary line-clamp-1">{msg.subject ?? msg.message}</div>
                  </div>
                  <div className="shrink-0 font-mono text-xs text-text-secondary">
                    {formatDate(msg.createdAt, "fa")}
                  </div>
                </a>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
