import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { formatDate } from "@/lib/types";
import { Plus, Pencil, Trash2, Star } from "lucide-react";

export const dynamic = "force-dynamic";

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

  const posts = await prisma.post.findMany({
    orderBy: { publishedAt: "desc" },
    include: { tags: { include: { tag: true } } },
  });

  const categoryColors: Record<string, string> = {
    "founder-notes": "text-blue-400 bg-blue-400/10 border-blue-400/20",
    "marketing-branding": "text-purple-400 bg-purple-400/10 border-purple-400/20",
    "product-thinking": "text-green-400 bg-green-400/10 border-green-400/20",
    "tech-builds": "text-orange-400 bg-orange-400/10 border-orange-400/20",
    "business-experiments": "text-pink-400 bg-pink-400/10 border-pink-400/20",
    "systems-productivity": "text-yellow-400 bg-yellow-400/10 border-yellow-400/20",
  };

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">نوشته‌ها</h1>
          <p className="text-sm text-text-secondary mt-1">{posts.length} نوشته</p>
        </div>
        <a
          href="/admin/posts/new"
          className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover transition-colors"
        >
          <Plus size={16} />
          نوشته جدید
        </a>
      </div>

      {posts.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
          <p className="text-text-secondary">هنوز نوشته‌ای ندارید</p>
          <a href="/admin/posts/new" className="mt-4 text-sm text-accent hover:text-accent-hover">
            اولین نوشته را بنویسید →
          </a>
        </div>
      ) : (
        <div className="rounded-xl border border-border bg-surface overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-surface-hover text-right">
                <th className="px-4 py-3 font-medium text-text-secondary">عنوان</th>
                <th className="hidden px-4 py-3 font-medium text-text-secondary md:table-cell">دسته‌بندی</th>
                <th className="hidden px-4 py-3 font-medium text-text-secondary lg:table-cell">زبان</th>
                <th className="hidden px-4 py-3 font-medium text-text-secondary lg:table-cell">تاریخ</th>
                <th className="px-4 py-3 font-medium text-text-secondary">عملیات</th>
              </tr>
            </thead>
            <tbody>
              {posts.map((post) => (
                <tr key={post.id} className="border-b border-border/50 hover:bg-surface-hover transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      {post.featured && <Star size={12} className="text-accent shrink-0" />}
                      <span className="font-medium text-text-primary line-clamp-1">{post.title}</span>
                    </div>
                    <div className="mt-0.5 text-xs text-text-secondary font-mono">/{post.slug}</div>
                  </td>
                  <td className="hidden px-4 py-3 md:table-cell">
                    <span className={`rounded-full border px-2 py-0.5 text-xs ${categoryColors[post.category] ?? "text-text-secondary bg-surface-hover border-border"}`}>
                      {post.category}
                    </span>
                  </td>
                  <td className="hidden px-4 py-3 lg:table-cell">
                    <span className="font-mono text-xs text-text-secondary">{post.locale}</span>
                  </td>
                  <td className="hidden px-4 py-3 lg:table-cell">
                    <span className="font-mono text-xs text-text-secondary">
                      {formatDate(post.publishedAt, "fa")}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <a
                        href={`/admin/posts/${post.id}`}
                        className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors"
                        title="ویرایش"
                      >
                        <Pencil size={14} />
                      </a>
                      <DeletePostButton id={post.id} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function DeletePostButton({ id }: { id: string }) {
  return (
    <form
      action={async () => {
        "use server";
        await fetch(`/api/admin/posts/${id}`, { method: "DELETE" });
      }}
    >
      <button
        type="button"
        onClick={async () => {
          if (!confirm("آیا مطمئن هستید؟")) return;
          const res = await fetch(`/api/admin/posts/${id}`, { method: "DELETE" });
          if (res.ok) window.location.reload();
        }}
        className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-danger/40 hover:text-danger transition-colors"
        title="حذف"
      >
        <Trash2 size={14} />
      </button>
    </form>
  );
}
