import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import { HelpArticleDeleteButton } from "./HelpArticleDeleteButton";
import { HelpArticlePublishToggle } from "./HelpArticlePublishToggle";

export default async function AdminHelpArticlesPage() {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const articles = await prisma.helpArticle.findMany({
    orderBy: [{ category: "asc" }, { sort_order: "asc" }],
  });

  function categoryLabel(value: string) {
    return value.replace(/-/g, " ").replace(/\b\w/g, (c: string) => c.toUpperCase());
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Help Articles</h1>
        <Link
          href="/admin/help/create"
          className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors text-sm"
        >
          New Article
        </Link>
      </div>

      <p className="text-text-muted text-sm">
        {articles.length} help articles
      </p>

      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-surface-light text-text-muted text-sm">
                <th className="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">Title</th>
                <th className="p-4 font-medium">Category</th>
                <th className="p-4 font-medium">Views</th>
                <th className="p-4 font-medium">Helpful</th>
                <th className="p-4 font-medium">Published</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {articles.map((article) => {
                const totalFeedback = article.helpful_yes + article.helpful_no;
                const helpfulRatio =
                  totalFeedback > 0
                    ? Math.round((article.helpful_yes / totalFeedback) * 100)
                    : null;

                return (
                  <tr
                    key={article.id}
                    className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                  >
                    <td className="p-4 text-text-muted font-mono text-sm">
                      {article.id}
                    </td>
                    <td className="p-4 font-medium max-w-[300px] truncate">
                      {article.title}
                    </td>
                    <td className="p-4">
                      <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-surface-light text-text-muted">
                        {categoryLabel(article.category)}
                      </span>
                    </td>
                    <td className="p-4 text-text-muted">
                      {article.views.toLocaleString()}
                    </td>
                    <td className="p-4">
                      {helpfulRatio !== null ? (
                        <span
                          className={`text-sm ${
                            helpfulRatio >= 70
                              ? "text-green-400"
                              : helpfulRatio >= 40
                              ? "text-yellow-400"
                              : "text-red-400"
                          }`}
                        >
                          {helpfulRatio}%
                          <span className="text-text-muted text-xs ml-1">
                            ({totalFeedback})
                          </span>
                        </span>
                      ) : (
                        <span className="text-text-muted text-sm">-</span>
                      )}
                    </td>
                    <td className="p-4">
                      <HelpArticlePublishToggle
                        articleId={article.id}
                        published={article.published}
                      />
                    </td>
                    <td className="p-4">
                      <div className="flex gap-3">
                        <Link
                          href={`/help/${article.slug}`}
                          className="text-text-muted hover:text-white text-sm transition-colors"
                          target="_blank"
                        >
                          View
                        </Link>
                        <Link
                          href={`/admin/help/edit/${article.id}`}
                          className="text-primary hover:text-primary-dark text-sm transition-colors"
                        >
                          Edit
                        </Link>
                        <HelpArticleDeleteButton articleId={article.id} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
