import Link from 'next/link';
import { AdminShell, EmptyState } from '../../components/admin/admin-page.jsx';
import { getProject, getProjectWorkspaceSummary } from '../../../lib/projects.js';
import { getRootFolder } from '../../../lib/disk.js';
import ProjectAlbum from './album-view.jsx';
import ProjectDropZone from './project-drop-zone.jsx';
import ProjectHeaderActions from './header-actions.jsx';
import { ProjectAlbumProvider } from './project-album-context.jsx';
import { isProjectsLiveDeltasEnabled } from '../../../lib/feature-flags.js';

export const dynamic = 'force-dynamic';

export default async function ProjectPage({ params, searchParams }) {
  const { slug } = await params;
  const sp = (await searchParams) || {};
  const project = getProject(slug);

  if (!project) {
    return (
      <AdminShell kicker="Project" title="Not found" description="That project slug does not exist." hideProjectSwitcher>
        <EmptyState title="Project not found">
          <Link className="admin-link" href="/projects">
            Back to projects
          </Link>
        </EmptyState>
      </AdminShell>
    );
  }

  const summary = getProjectWorkspaceSummary(project.id, { limit: 100, changelogLimit: 50 });
  const lockedCount = summary.libraryItems.filter((it) => it.is_protected).length;
  const root = getRootFolder(project.id);
  const folderParam = typeof sp.folder === 'string' ? sp.folder : '';
  const currentFolderId = folderParam || root?.id || null;

  return (
    <ProjectAlbumProvider
      initialItems={summary.libraryItems}
      initialFolders={summary.folders}
      projectId={project.id}
      projectSlug={project.slug}
      rootFolderId={root?.id || null}
      currentFolderId={currentFolderId}
      liveDeltasEnabled={isProjectsLiveDeltasEnabled()}
    >
      <AdminShell
        kicker="Project"
        title={project.name}
        description={project.description || `Library for ${project.slug}.`}
        hideProjectSwitcher
        actions={
          <ProjectHeaderActions
            projectId={project.id}
            projectName={project.name}
            slug={project.slug}
            lockedCount={lockedCount}
            currentFolderId={currentFolderId}
            rootFolderId={root?.id || null}
          />
        }
      >
        <ProjectDropZone projectId={project.id}>
          <div className="mkt-page" data-page="project-detail">
            <ProjectAlbum
              items={summary.libraryItems}
              folders={summary.folders}
              projectId={project.id}
              projectSlug={project.slug}
              rootFolderId={root?.id || null}
              currentFolderId={currentFolderId}
            />
          </div>
        </ProjectDropZone>
      </AdminShell>
    </ProjectAlbumProvider>
  );
}
