import Link from "next/link";
import {
  deleteMediaAction,
  updateMediaAltAction,
} from "@/app/dashboard/actions";
import {
  EmptyState,
  PrimaryButton,
} from "@/components/dashboard/empty-state";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import { getStorage } from "@/core/storage/storage";
import { listTenantMedia } from "@/services/media-service";
import { listDashboardProjects } from "@/services/project-service";

export default async function DashboardMediaPage() {
  const ctx = await requireDashboardContext("media:manage");
  const [media, projects] = await Promise.all([
    listTenantMedia(ctx.tenant),
    listDashboardProjects(ctx.tenant),
  ]);
  const storage = getStorage();
  const projectById = new Map(projects.map((p) => [p.id, p]));
  const heroByProject = new Map(
    projects
      .filter((p) => p.heroStorageKey)
      .map((p) => [p.heroStorageKey!, p.id]),
  );

  const withThumbs = await Promise.all(
    media.map(async (item) => ({
      item,
      imageSrc:
        item.fileType === "image"
          ? await storage.getSignedUrl(item.storageKey, ctx.tenant.tenantId)
          : null,
      project: projectById.get(item.projectId),
      isHero: heroByProject.has(item.storageKey),
    })),
  );

  const imageCount = media.filter((m) => m.fileType === "image").length;

  return (
    <DashboardShell width="wide">
      <DashboardPageHeader
        eyebrow="Content"
        title="Library"
        description={`${media.length} assets · ${imageCount} images. Upload from a project page, then manage here.`}
        actions={
          <Link href="/dashboard/projects" className="archi-btn-primary">
            Go to projects
          </Link>
        }
      />

      {withThumbs.length === 0 ? (
        <div className="mt-10">
          <EmptyState
            title="No media yet"
            description="Upload images from a project detail page, then manage alt text and heroes here."
            action={
              <PrimaryButton href="/dashboard/projects">
                Go to projects
              </PrimaryButton>
            }
          />
        </div>
      ) : (
        <ul className="mt-10 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {withThumbs.map(({ item, imageSrc, project, isHero }) => (
            <li
              key={item.id}
              className="overflow-hidden border border-[var(--archi-line)] bg-white/70"
            >
              <div className="relative aspect-[16/10] bg-[var(--archi-bg-deep)]">
                {imageSrc ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={imageSrc}
                    alt={item.altText ?? ""}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <div className="flex h-full items-center justify-center text-xs text-[var(--archi-ink-muted)]">
                    {item.fileType}
                  </div>
                )}
                {isHero ? (
                  <span className="absolute top-2 left-2 bg-[var(--archi-gold)] px-2 py-0.5 text-[10px] font-bold text-[var(--archi-dark)] uppercase">
                    Hero
                  </span>
                ) : null}
              </div>
              <div className="space-y-2 p-3 text-sm">
                <p className="truncate font-medium">
                  {item.storageKey.split("/").pop()}
                </p>
                <p className="text-xs text-[var(--archi-ink-muted)]">
                  {item.mimeType} · {(item.fileSize / 1024).toFixed(0)} KB
                </p>
                {project ? (
                  <Link
                    href={`/dashboard/projects/${project.id}`}
                    className="inline-block text-xs underline underline-offset-2"
                  >
                    {project.title}
                  </Link>
                ) : null}
                  <form
                    action={async (formData) => {
                      "use server";
                      await updateMediaAltAction(item.id, formData);
                    }}
                    className="flex gap-2"
                  >
                  <input
                    name="altText"
                    defaultValue={item.altText ?? ""}
                    placeholder="Alt text"
                    className="archi-input min-w-0 flex-1 px-2 py-1 text-xs"
                  />
                  <button type="submit" className="text-xs underline">
                    Save
                  </button>
                </form>
                <form action={deleteMediaAction.bind(null, item.id)}>
                  <button
                    type="submit"
                    className="text-xs text-red-800 underline"
                  >
                    Delete
                  </button>
                </form>
              </div>
            </li>
          ))}
        </ul>
      )}
    </DashboardShell>
  );
}
