import type { Metadata } from "next";
import Link from "next/link";
import {
  getAllPosts,
  getAllProjects,
  getAllTestimonials,
  getServices,
} from "@/lib/cms";
import { getSession } from "@/lib/auth";

export const metadata: Metadata = {
  title: "Dashboard",
  robots: { index: false, follow: false },
};

function seoIssues(posts: Awaited<ReturnType<typeof getAllPosts>>) {
  const issues: { slug: string; title: string; issue: string }[] = [];
  for (const post of posts) {
    if (!post.seo.metaDescription && post.excerpt.length < 70) {
      issues.push({
        slug: post.slug,
        title: post.title,
        issue: "No meta description and a thin excerpt",
      });
    } else if (!post.seo.metaDescription) {
      issues.push({
        slug: post.slug,
        title: post.title,
        issue: "Missing meta description (excerpt is used as fallback)",
      });
    }
    if (!post.seo.ogImage && !post.coverImage) {
      issues.push({
        slug: post.slug,
        title: post.title,
        issue: "No social share image",
      });
    }
  }
  return issues;
}

export default async function AdminDashboardPage() {
  const [posts, projects, services, testimonials, session] = await Promise.all([
    getAllPosts(),
    getAllProjects(),
    getServices(),
    getAllTestimonials(),
    getSession(),
  ]);
  const publishedPosts = posts.filter((p) => p.published).length;
  const drafts = posts.length - publishedPosts;
  const hiddenProjects = projects.filter((p) => !p.published).length;
  const hiddenServices = services.filter((s) => !s.published).length;
  const hiddenTestimonials = testimonials.filter((t) => !t.published).length;
  const issues = seoIssues(posts);

  const stats = [
    { label: "Journal posts", value: posts.length, note: `${publishedPosts} live · ${drafts} drafts` },
    { label: "Portfolio projects", value: projects.length, note: hiddenProjects ? `${hiddenProjects} hidden` : "all live" },
    { label: "Services", value: services.length, note: hiddenServices ? `${hiddenServices} hidden` : "all live" },
    { label: "Testimonials", value: testimonials.length, note: hiddenTestimonials ? `${hiddenTestimonials} hidden` : "all live" },
    { label: "SEO issues", value: issues.length, note: issues.length ? "worth a look" : "all clear" },
  ];

  return (
    <div className="space-y-8">
      <header>
        <p className="text-sm font-semibold uppercase tracking-[0.14em] text-coral">
          Dashboard
        </p>
        <h1 className="display-2 mt-2">
          Welcome back{session ? `, ${session.email.split("@")[0]}` : ""}
        </h1>
        <p className="mt-2 text-ink-soft">
          Manage your content and keep the site&apos;s search presence sharp.
        </p>
      </header>

      {/* Stats */}
      <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-5">
        {stats.map((stat) => (
          <div key={stat.label} className="card-soft p-6">
            <p className="text-[0.72rem] font-bold uppercase tracking-[0.16em] text-ink-mute">
              {stat.label}
            </p>
            <p className="mt-2 font-display text-4xl font-bold text-ink">
              {stat.value}
            </p>
            <p className="mt-1 text-xs text-ink-mute">{stat.note}</p>
          </div>
        ))}
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.4fr_1fr]">
        {/* Recent posts */}
        <section className="card-soft p-7">
          <div className="flex items-center justify-between gap-4">
            <h2 className="display-3">Recent posts</h2>
            <Link href="/admin/posts" className="text-sm font-semibold text-teal link-sweep">
              View all
            </Link>
          </div>
          <ul className="mt-6 divide-y divide-linen">
            {posts.slice(0, 5).map((post) => (
              <li key={post.slug} className="flex items-center gap-4 py-4">
                <div className="min-w-0 flex-1">
                  <Link
                    href={`/admin/posts/${post.slug}/edit`}
                    className="block truncate font-medium text-ink transition-colors hover:text-teal"
                  >
                    {post.title}
                  </Link>
                  <p className="mt-0.5 text-xs text-ink-mute">
                    {post.category} · {post.date}
                  </p>
                </div>
                <span
                  className={`shrink-0 rounded-full px-2.5 py-1 text-[0.68rem] font-bold uppercase tracking-wide ${
                    post.published
                      ? "bg-teal-soft text-teal-dark"
                      : "bg-amber-soft text-amber-dark"
                  }`}
                >
                  {post.published ? "Live" : "Draft"}
                </span>
              </li>
            ))}
            {posts.length === 0 ? (
              <li className="py-6 text-sm text-ink-mute">
                No posts yet — create your first journal entry.
              </li>
            ) : null}
          </ul>
        </section>

        {/* SEO health */}
        <section className="card-soft p-7">
          <h2 className="display-3">SEO health</h2>
          <p className="mt-2 text-sm text-ink-mute">
            Quick checks across your journal content.
          </p>
          <ul className="mt-5 space-y-3">
            {issues.slice(0, 5).map((issue, i) => (
              <li key={`${issue.slug}-${i}`} className="flex gap-3 text-sm">
                <span className="mt-2 h-2 w-2 shrink-0 rounded-full bg-amber" />
                <span className="text-ink-soft">
                  <Link
                    href={`/admin/posts/${issue.slug}/edit`}
                    className="font-medium text-ink hover:text-teal"
                  >
                    {issue.title}
                  </Link>{" "}
                  — {issue.issue}
                </span>
              </li>
            ))}
            {issues.length === 0 ? (
              <li className="flex gap-3 text-sm text-ink-soft">
                <span className="mt-2 h-2 w-2 shrink-0 rounded-full bg-teal" />
                All posts pass the basic checks. Nicely done.
              </li>
            ) : null}
          </ul>
        </section>
      </div>

      {/* Quick actions */}
      <section className="card-soft flex flex-wrap items-center gap-4 p-7">
        <h2 className="display-3 mr-auto">Quick actions</h2>
        <Link href="/admin/pages" className="btn btn-teal">
          Edit page content
        </Link>
        <Link href="/admin/projects/new" className="btn btn-outline">
          New project
        </Link>
        <Link href="/admin/services/new" className="btn btn-outline">
          New service
        </Link>
        <Link href="/admin/posts/new" className="btn btn-outline">
          New journal post
        </Link>
        <Link href="/admin/testimonials" className="btn btn-outline">
          Testimonials
        </Link>
        <Link href="/" className="btn btn-outline">
          View website
        </Link>
      </section>
    </div>
  );
}
