import { AdminShell, EmptyState, StatCard, StatusPill } from '../components/admin/admin-page.jsx';
import { listProjects } from '../../lib/projects.js';
import { listFolders, listFiles } from '../../lib/disk.js';
import UploadFilesModal from './upload-files-modal.jsx';

export const dynamic = 'force-dynamic';

function formatBytes(n) {
  if (!Number.isFinite(n) || n <= 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let v = n;
  while (v >= 1024 && i < units.length - 1) {
    v /= 1024;
    i += 1;
  }
  return `${v.toFixed(v >= 10 || i === 0 ? 0 : 1)} ${units[i]}`;
}

export default function DiskPage() {
  const projects = listProjects({ status: 'active' });
  const project = projects[0];
  const folders = project ? listFolders(project.id) : [];
  const files = project ? listFiles({ project_id: project.id }) : [];

  if (!project) {
    return (
      <AdminShell
        kicker="Disk"
        title="Document Disk"
        description="Project-scoped files with local-only enforcement."
      >
        <EmptyState title="No active project">
          Create a project before uploading files.
        </EmptyState>
      </AdminShell>
    );
  }

  const localOnlyCount = files.filter((f) => f.local_only).length;
  const audioCount = files.filter((f) => f.kind === 'audio').length;
  const totalBytes = files.reduce((sum, f) => sum + (f.size_bytes || 0), 0);

  const headerActions = <UploadFilesModal projectId={project.id} />;

  return (
    <AdminShell
      kicker="Disk"
      title="Document Disk"
      description={`Project-scoped files for ${project.name}. Local-only files never leave this machine.`}
      actions={headerActions}
    >
      <section className="admin-stats">
        <StatCard label="Files" value={files.length} />
        <StatCard label="Local only" value={localOnlyCount} />
        <StatCard label="Audio" value={audioCount} />
        <StatCard label="Total size" value={formatBytes(totalBytes)} tone="mars" />
      </section>

      <section className="disk-shell" data-page="disk">
        <aside className="disk-folders">
          <span className="panel-label">Folders</span>
          {folders.length ? (
            folders.map((f) => (
              <div className="disk-folder" key={f.id}>
                <code>{f.path}</code>
              </div>
            ))
          ) : (
            <p className="disk-folder-empty">No folders.</p>
          )}
        </aside>

        <main className="disk-main">
          {files.length ? (
            <div className="admin-card-list">
              {files.map((f) => (
                <div className="admin-record disk-file" key={f.id}>
                  <div className="admin-record-top">
                    <div>
                      <b>{f.name}</b>
                      <small className="disk-file-meta">
                        <code>{f.kind}</code>
                        <span>·</span>
                        <span>{formatBytes(f.size_bytes)}</span>
                      </small>
                    </div>
                    <div className="admin-pills">
                      {f.local_only ? <StatusPill tone="warn">Local only</StatusPill> : null}
                      {f.kind === 'audio' ? (
                        <form action={`/api/disk/files/${f.id}/transcribe`} method="post">
                          <button type="submit" className="admin-button secondary">
                            Transcribe
                          </button>
                        </form>
                      ) : null}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState title="No files yet">
              Upload your first file to this project from the top right.
            </EmptyState>
          )}
        </main>
      </section>
    </AdminShell>
  );
}
