import os from 'node:os';
import path from 'node:path';
import Link from 'next/link';
import { AdminShell, EmptyState, StatusPill } from '../../../components/admin/admin-page.jsx';
import { getProject, listProjectChangelog } from '../../../../lib/projects.js';
import { listSecrets } from '../../../../lib/secrets.js';
import LogMarkdown from './log-markdown.jsx';

export const dynamic = 'force-dynamic';

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

function when(value) {
  if (!value) return 'Never';
  try {
    return new Intl.DateTimeFormat('en', {
      month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
    }).format(new Date(value));
  } catch { return value; }
}

function buildLogMarkdown(project, entries) {
  const progress = entries.filter((e) => e.details?.update_kind === 'progress');
  const lines = [];

  lines.push('## Project update');
  lines.push('');
  if (!progress.length) {
    lines.push('_No project updates yet. Agents will post highlights here as work happens._');
  } else {
    progress.slice(0, 50).forEach((e) => {
      const title = e.details?.title || e.action;
      const summary = e.details?.summary || '';
      lines.push(`- **${title}**${summary ? ` — ${summary}` : ''}  `);
      lines.push(`  _${when(e.created_at)}_`);
    });
  }
  lines.push('');
  lines.push('---');
  lines.push('');
  lines.push('## Full changelog');
  lines.push('');
  if (!entries.length) {
    lines.push('_No changelog entries yet._');
  } else {
    entries.forEach((e) => {
      const title = e.details?.title || e.action;
      const summary = e.details?.summary || '';
      lines.push(`- \`${when(e.created_at)}\` **${title}**${summary ? ` — ${summary}` : ''} _(${e.action})_`);
    });
  }
  return lines.join('\n');
}

export default async function ProjectLogPage({ params }) {
  const { slug } = await params;
  const project = getProject(slug);

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

  const entries = listProjectChangelog(project.id, { limit: 500 });
  const md = buildLogMarkdown(project, entries);
  const secrets = listSecrets().filter((s) => s.project_id === project.id);
  const googleConnected = secrets.some((s) => s.name === 'GOOGLE_REFRESH_TOKEN');
  const folderRoot = project.folder_path || path.join('workspace', 'projects', project.slug);

  return (
    <AdminShell
      kicker="Project log"
      title={`${project.name} · Activity`}
      description="Status, project update, and full changelog. Agents append entries here automatically."
      actions={
        <Link className="project-activity-link" href={`/projects/${project.slug}`} aria-label="Back to project">
          <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M10 4l-4 4 4 4" />
          </svg>
          <span>Back to project</span>
        </Link>
      }
    >
      <div className="mkt-page" data-page="project-log">
        <section className="project-log-status">
          <div className="project-log-status-row">
            <StatusPill tone={project.status === 'active' ? 'ready' : 'neutral'}>{project.status}</StatusPill>
            <code>{project.slug}</code>
            <small title={folderRoot}>{prettyPath(folderRoot)}</small>
          </div>
          {project.description ? <p>{project.description}</p> : null}
        </section>

        <article className="project-log-md">
          <LogMarkdown markdown={md} />
        </article>

        <section className="project-log-settings">
          <h3>Integrations</h3>
          <div className="project-log-integration-row">
            <div>
              <b>Gmail &amp; Calendar</b>
              <small>Send mail and read events scoped to this project.</small>
            </div>
            <div className="project-log-integration-actions">
              <StatusPill tone={googleConnected ? 'ready' : 'neutral'}>
                {googleConnected ? 'Connected' : 'Disconnected'}
              </StatusPill>
              <Link className="admin-link" href={`/api/integrations/google/oauth?project_id=${project.id}`}>
                {googleConnected ? 'Reconnect' : 'Connect'}
              </Link>
            </div>
          </div>
        </section>
      </div>
    </AdminShell>
  );
}
