import Link from "next/link";
import {
  archiveProjectAction,
  deleteProjectAction,
  publishProjectAction,
} 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 { listCategories } from "@/services/category-service";
import { listDashboardProjects } from "@/services/project-service";

function statusClass(status: string) {
  if (status === "published") return "archi-status archi-status-published";
  if (status === "archived") return "archi-status archi-status-archived";
  return "archi-status archi-status-draft";
}

export default async function DashboardProjectsPage({
  searchParams,
}: {
  searchParams: Promise<{ category?: string }>;
}) {
  const { category: categoryFilter } = await searchParams;
  const ctx = await requireDashboardContext("projects:view");
  const [projects, categories] = await Promise.all([
    listDashboardProjects(ctx.tenant),
    listCategories(ctx.tenant),
  ]);
  const storage = getStorage();

  const filtered = categoryFilter
    ? projects.filter((p) => p.categoryId === categoryFilter)
    : projects;

  const withThumbs = await Promise.all(
    filtered.map(async (project) => ({
      project,
      imageSrc: project.heroStorageKey
        ? await storage.getSignedUrl(
            project.heroStorageKey,
            ctx.tenant.tenantId,
          )
        : null,
      categoryName: categories.find((c) => c.id === project.categoryId)?.name,
    })),
  );

  return (
    <DashboardShell width="wide">
      <DashboardPageHeader
        eyebrow="Projects"
        title="Portfolio"
        description="Draft, publish, and organize studio work."
        actions={
          <>
            <Link
              href="/dashboard/categories"
              className="border border-[var(--archi-line)] bg-white px-4 py-2 text-sm"
            >
              Categories
            </Link>
            <Link href="/dashboard/projects/new" className="archi-btn-primary">
              New project
            </Link>
          </>
        }
      />

      {categories.length > 0 ? (
        <div className="mt-8 flex flex-wrap gap-2">
          <Link
            href="/dashboard/projects"
            className={`px-3 py-1.5 text-xs tracking-wide uppercase ${
              !categoryFilter
                ? "bg-[var(--archi-ink)] text-[var(--archi-bg)]"
                : "border border-[var(--archi-line)] bg-white text-[var(--archi-ink-muted)]"
            }`}
          >
            All
          </Link>
          {categories.map((category) => (
            <Link
              key={category.id}
              href={`/dashboard/projects?category=${category.id}`}
              className={`px-3 py-1.5 text-xs tracking-wide uppercase ${
                categoryFilter === category.id
                  ? "bg-[var(--archi-ink)] text-[var(--archi-bg)]"
                  : "border border-[var(--archi-line)] bg-white text-[var(--archi-ink-muted)]"
              }`}
            >
              {category.name}
            </Link>
          ))}
        </div>
      ) : null}

      {withThumbs.length === 0 ? (
        <div className="mt-10">
          <EmptyState
            title="No projects yet"
            description="Create your first portfolio piece, then publish it to the live studio site."
            action={
              <PrimaryButton href="/dashboard/projects/new">
                New project
              </PrimaryButton>
            }
          />
        </div>
      ) : (
      <div className="archi-panel mt-10 overflow-x-auto">
        <table className="w-full min-w-[720px] text-left text-sm">
          <thead className="border-b border-[var(--archi-line)] text-xs uppercase tracking-wider text-[var(--archi-ink-muted)]">
            <tr>
              <th className="px-4 py-3 pr-4 font-medium">Project</th>
              <th className="py-3 pr-4 font-medium">Status</th>
              <th className="py-3 pr-4 font-medium">Category</th>
              <th className="py-3 pr-4 font-medium">Location</th>
              <th className="py-3 pr-4 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
              {withThumbs.map(({ project, imageSrc, categoryName }) => (
                <tr
                  key={project.id}
                  className="border-b border-[var(--archi-line)] last:border-0"
                >
                  <td className="px-4 py-4 pr-4">
                    <div className="flex items-center gap-3">
                      <div className="h-12 w-16 shrink-0 overflow-hidden bg-[var(--archi-bg-deep)]">
                        {imageSrc ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={imageSrc}
                            alt=""
                            className="h-full w-full object-cover"
                          />
                        ) : null}
                      </div>
                      <div>
                        <Link
                          href={`/dashboard/projects/${project.id}`}
                          className="font-medium"
                        >
                          {project.title}
                        </Link>
                        <p className="text-xs text-[var(--archi-ink-muted)]">
                          /{project.slug}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="py-4 pr-4">
                    <span className={statusClass(project.status)}>
                      {project.status}
                    </span>
                  </td>
                  <td className="py-4 pr-4 text-[var(--archi-ink-muted)]">
                    {categoryName ?? "—"}
                  </td>
                  <td className="py-4 pr-4 text-[var(--archi-ink-muted)]">
                    {project.location ?? "—"}
                  </td>
                  <td className="py-4">
                    <div className="flex flex-wrap gap-2">
                      {project.status !== "published" ? (
                        <form
                          action={publishProjectAction.bind(null, project.id)}
                        >
                          <button type="submit" className="text-xs underline">
                            Publish
                          </button>
                        </form>
                      ) : (
                        <form
                          action={archiveProjectAction.bind(null, project.id)}
                        >
                          <button type="submit" className="text-xs underline">
                            Archive
                          </button>
                        </form>
                      )}
                      <form action={deleteProjectAction.bind(null, project.id)}>
                        <button
                          type="submit"
                          className="text-xs text-red-800 underline"
                        >
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
          </tbody>
        </table>
      </div>
      )}
    </DashboardShell>
  );
}
