import path from 'node:path';
import os from 'node:os';
import Link from 'next/link';
import { AdminShell, EmptyState } from '../components/admin/admin-page.jsx';
import { listProjects } from '../../lib/projects.js';
import { countInstalledAgentsByProject } from '../../lib/agent-templates.js';
import { countFilesByProject } from '../../lib/disk.js';
import { WORKSPACE } from '../../lib/paths.js';
import NewProjectModal from './new-project-modal.jsx';
import DeleteProjectButton from './delete-project-button.jsx';
import EditProjectButton from './edit-project-button.jsx';
import { DEFAULT_PROJECT_ID } from '../../lib/projects.js';

export const dynamic = 'force-dynamic';

function prettyPath(absolute) {
  if (!absolute) return '';
  const home = os.homedir();
  if (home && absolute.startsWith(home)) return absolute.replace(home, '~');
  return absolute;
}

export default function ProjectsPage() {
  const projects = listProjects({ status: 'all' });
  const active = projects.filter((p) => p.status === 'active');
  const archived = projects.filter((p) => p.status !== 'active');

  const agentCounts = countInstalledAgentsByProject();
  const fileCounts = countFilesByProject();
  const enriched = projects.map((p) => ({
    ...p,
    agentCount: agentCounts[p.id] || 0,
    fileCount: fileCounts[p.id] || 0,
  }));

  const workspaceRoot = prettyPath(path.join(WORKSPACE, 'projects'));
  const headerActions = <NewProjectModal workspaceRoot={workspaceRoot} />;

  return (
    <AdminShell
      kicker="Projects"
      title="Projects"
      description="Group agents, Disk, memory, secrets, approvals, and missions into project scopes."
      actions={headerActions}
      hideProjectSwitcher
    >
      <div className="mkt-page" data-page="projects">
        <section className="mkt-stats">
          <div className="mkt-stat">
            <b>{projects.length}</b>
            <span>Total</span>
          </div>
          <div className="mkt-stat">
            <b>{active.length}</b>
            <span>Active</span>
          </div>
          <div className="mkt-stat">
            <b>{archived.length}</b>
            <span>Archived</span>
          </div>
          <div className="mkt-stat">
            <b>{enriched.reduce((sum, p) => sum + p.agentCount, 0)}</b>
            <span>Agents</span>
          </div>
        </section>

        <section className="mkt-section" aria-live="polite">
          {enriched.length ? (
            <ul className="mkt-grid project-grid">
              {enriched.map((p) => (
                <li
                  key={p.id}
                  className={`mkt-card project-card ${p.status === 'active' ? 'on' : ''}`}
                >
                  <div className="mkt-card-head">
                    <span
                      className="mkt-chip-tile project-tile"
                      style={{
                        backgroundColor: p.color || '#111318',
                        borderColor: 'rgba(17,19,24,.08)',
                      }}
                      aria-hidden="true"
                    >
                      <span className="project-tile-glyph">
                        {(p.name || p.slug).slice(0, 1).toUpperCase()}
                      </span>
                    </span>
                    <Link
                      href={`/projects/${p.slug}`}
                      className="project-card-slug"
                    >
                      {p.slug}
                    </Link>
                  </div>

                  <div className="mkt-card-body">
                    <h3 className="mkt-card-title">{p.name}</h3>
                    {p.description ? <p className="mkt-card-desc">{p.description}</p> : null}
                  </div>

                  <div className="mkt-card-meta">
                    <span>
                      Agents <b>{p.agentCount}</b>
                    </span>
                    <span>
                      Disk files <b>{p.fileCount}</b>
                    </span>
                    <span>
                      Status <b>{p.status}</b>
                    </span>
                    {p.folder_path ? (
                      <span className="project-folder-meta" title={p.folder_path}>
                        Folder <code>{prettyPath(p.folder_path)}</code>
                      </span>
                    ) : null}
                  </div>

                  <div className="mkt-card-foot">
                    <span
                      className={`mkt-availability ${p.status === 'active' ? 'installed' : ''}`}
                    >
                      {p.status === 'active' ? 'Active' : 'Archived'}
                    </span>
                    <div className="project-card-actions">
                      <Link
                        href={`/projects/${p.slug}`}
                        className="admin-button secondary project-open"
                        aria-label={`Open ${p.name}`}
                      >
                        Open
                      </Link>
                      <EditProjectButton
                        projectId={p.id}
                        projectName={p.name}
                        projectColor={p.color}
                        projectDescription={p.description}
                        projectFolderPath={p.folder_path}
                      />
                      <DeleteProjectButton
                        projectId={p.id}
                        projectName={p.name}
                        projectSlug={p.slug}
                        isProtected={p.id === DEFAULT_PROJECT_ID}
                      />
                    </div>
                  </div>
                </li>
              ))}
            </ul>
          ) : (
            <EmptyState title="No projects yet">
              Create your first project to scope agents, files, and secrets.
            </EmptyState>
          )}
        </section>
      </div>
    </AdminShell>
  );
}
