/* eslint-disable @next/next/no-img-element */
import { format } from "date-fns";
import Link from "next/link";
import { fetchAllTopics } from "@/data/topics";
import { buildMediaAssets } from "@/lib/media";
export const revalidate = 30;

function getMonthlyStats(topicsCountByMonth: Record<string, { total: number; published: number }>) {
  return Object.entries(topicsCountByMonth)
    .sort(([a], [b]) => (a > b ? 1 : -1))
    .slice(-6);
}

export default async function DashboardPage() {
  const topics = await fetchAllTopics();

  const total = topics.length;
  const published = topics.filter((topic) => topic.is_published).length;
  const pending = total - published;
  const imageCount = topics.filter((topic) => buildMediaAssets(topic.photo_name).some((asset) => !asset.isVideo))
    .length;
  const videoCount = topics.filter((topic) => buildMediaAssets(topic.photo_name).some((asset) => asset.isVideo))
    .length;

  const monthlyStatsMap: Record<string, { total: number; published: number }> = {};
  topics.forEach((topic) => {
    const key = format(new Date(topic.created_at), "yyyy-MM");
    if (!monthlyStatsMap[key]) {
      monthlyStatsMap[key] = { total: 0, published: 0 };
    }
    monthlyStatsMap[key].total += 1;
    if (topic.is_published) {
      monthlyStatsMap[key].published += 1;
    }
  });

  const monthlyStats = getMonthlyStats(monthlyStatsMap);
  const recentPosts = [...topics]
    .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
    .slice(0, 5);

  return (
    <div className="space-y-8">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <p className="text-sm uppercase tracking-[0.3em] text-orange-600 dark:text-orange-300">Control Center</p>
          <h1 className="mt-2 text-3xl font-semibold text-slate-900 dark:text-white lg:text-4xl">Dashboard</h1>
          <p className="mt-2 text-sm text-slate-600 dark:text-slate-400">
            Keep track of webhook runs, publishing status, and media distribution from a single view.
          </p>
        </div>
        <div className="flex gap-4">
          <Link
            href="/posts"
            className="rounded-2xl bg-slate-100 px-5 py-3 text-sm font-semibold text-slate-900 transition hover:bg-slate-200 dark:bg-white/10 dark:text-white dark:hover:bg-white/20"
          >
            View posts
          </Link>
          <a
            href="mailto:info@gainrhino.com"
            className="rounded-2xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-900 transition hover:border-slate-300 dark:border-white/10 dark:text-white dark:hover:border-white/30"
          >
            Support
          </a>
        </div>
      </div>

      <section className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {[
          { label: "Total posts", value: total.toString() },
          { label: "Published", value: published.toString() },
          { label: "Drafts", value: pending.toString() },
          { label: "Media split", value: `${imageCount} img / ${videoCount} vid` },
        ].map((card) => (
          <article key={card.label} className="rounded-3xl border border-white/10 bg-white p-6 shadow-lg shadow-orange-500/10 dark:border-white/5 dark:bg-white/5">
            <p className="text-sm text-slate-600 dark:text-slate-400">{card.label}</p>
            <p className="mt-3 text-3xl font-semibold text-slate-900 dark:text-white">{card.value}</p>
          </article>
        ))}
      </section>

      <section className="grid gap-6 lg:grid-cols-3">
        <div className="rounded-3xl border border-white/10 bg-white p-6 shadow-lg shadow-orange-500/10 dark:border-white/5 dark:bg-white/5 lg:col-span-2">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Monthly output</h2>
            <span className="text-xs uppercase tracking-[0.3em] text-slate-500 dark:text-slate-400">Last 6 months</span>
          </div>
          <div className="mt-8 space-y-4">
            {monthlyStats.length === 0 ? (
              <p className="text-sm text-slate-600 dark:text-slate-400">No data yet.</p>
            ) : (
              monthlyStats.map(([month, values]) => (
                <div key={month}>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-slate-700 dark:text-slate-300">{month}</span>
                    <span className="text-slate-900 dark:text-white">
                      {values.published} / {values.total}
                    </span>
                  </div>
                  <div className="mt-2 h-2 overflow-hidden rounded-full bg-orange-100 dark:bg-white/5">
                    <div
                      className="h-full rounded-full bg-gradient-to-r from-orange-500 to-amber-400"
                      style={{
                        width: `${(values.published / values.total) * 100}%`,
                      }}
                    />
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="rounded-3xl border border-white/10 bg-white p-6 shadow-lg shadow-orange-500/10 dark:border-white/5 dark:bg-white/5">
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Latest 5 posts</h2>
          <div className="mt-6 space-y-4">
            {recentPosts.map((topic) => {
              const assets = buildMediaAssets(topic.photo_name);
              const firstAsset = assets[0];

              return (
                <div key={topic.id} className="flex gap-4 rounded-2xl border border-white/10 bg-white p-3 dark:border-white/10 dark:bg-white/5">
                  <div className="h-16 w-16 overflow-hidden rounded-2xl bg-slate-100 dark:bg-white/5">
                    {firstAsset ? (
                      firstAsset.isVideo ? (
                        <video src={firstAsset.url} className="h-full w-full object-cover" muted playsInline />
                      ) : (
                        <img src={firstAsset.url} alt={firstAsset.name} className="h-full w-full object-cover" />
                      )
                    ) : (
                      <div className="flex h-full w-full items-center justify-center text-xs text-slate-500">
                        N/A
                      </div>
                    )}
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-semibold text-slate-900 dark:text-white">
                      #{topic.id} • {topic.is_published ? "Published" : "Draft"}
                    </p>
                    <p className="text-xs text-slate-600 dark:text-slate-400">
                      {format(new Date(topic.created_at), "dd MMM yyyy, HH:mm")}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}
