import Link from 'next/link';
import { AdminShell, EmptyState, StatusPill } from '../components/admin/admin-page.jsx';
import { listDefinitions } from '../../lib/process/definitions.js';
import { listCases } from '../../lib/process/engine.js';
import { listProjects } from '../../lib/projects.js';
import { getBrandProfile } from '../../lib/brand.js';
import { pickBrandAccent } from '../../lib/process/util.js';
import { STATUS_TONES, STATUS_LABELS } from '../../lib/process/status-tokens.js';
import DefinitionCard from './definition-card.jsx';

export const dynamic = 'force-dynamic';

const ACTIVE_STATES = new Set(['intake', 'running', 'awaiting_approval']);

function formatRelative(iso) {
  if (!iso) return '';
  const ts = new Date(iso).getTime();
  if (Number.isNaN(ts)) return iso;
  const diffMs = Date.now() - ts;
  if (diffMs < 60_000) return 'just now';
  if (diffMs < 3_600_000) return `${Math.floor(diffMs / 60_000)}m ago`;
  if (diffMs < 86_400_000) return `${Math.floor(diffMs / 3_600_000)}h ago`;
  return `${Math.floor(diffMs / 86_400_000)}d ago`;
}

export default function WorkflowsPage() {
  const definitions = listDefinitions();
  const cases = listCases({ limit: 100 });
  const projects = listProjects({ status: 'active' });
  const brand = getBrandProfile();
  const accent = pickBrandAccent(brand);
  const defaultProjectId = projects[0]?.id || 'personal';

  const activeCases = cases.filter((c) => ACTIVE_STATES.has(c.status));
  const completedCases = cases.filter((c) => c.status === 'complete');
  const recentCases = cases.slice(0, 6);

  // Featured + rest split. Featured is the most-used definition (by case
  // count); the rest tile beneath in a tighter grid. If only one
  // definition exists, skip the split.
  const usage = new Map();
  for (const c of cases) {
    usage.set(c.definition_slug, (usage.get(c.definition_slug) || 0) + 1);
  }
  const ordered = [...definitions].sort((a, b) => (usage.get(b.slug) || 0) - (usage.get(a.slug) || 0));

  return (
    <AdminShell
      kicker="Workflows"
      title="Workflows"
      description="Stage-gated business processes. Configure once, then run cases through verifiers, gates, and approvals — each case produces a branded artifact trail."
    >
      <div className="mkt-page wf-page" data-page="workflows" style={{ '--wf-accent': accent }}>
        <section className="mkt-stats wf-stats">
          <div className="mkt-stat">
            <b>{definitions.length}</b>
            <span>Definitions</span>
          </div>
          <div className="mkt-stat">
            <b>{cases.length}</b>
            <span>Total cases</span>
          </div>
          <div className="mkt-stat">
            <b>{activeCases.length}</b>
            <span>In flight</span>
          </div>
          <div className="mkt-stat">
            <b>{completedCases.length}</b>
            <span>Complete</span>
          </div>
        </section>

        <section className="wf-section">
          <header className="wf-section-head">
            <div>
              <h2>Process definitions</h2>
              <p>Pick a process, configure it for your project, and start a case.</p>
            </div>
            <Link href="/workflows/new/definition" className="wf-section-newbtn">+ New workflow</Link>
          </header>

          {definitions.length === 0 ? (
            <EmptyState title="No process definitions">
              <p>The ADGM entity setup process seeds automatically. Restart the dev server if you don't see it.</p>
            </EmptyState>
          ) : (
            <ul className="mkt-grid wf-defgrid">
              {ordered.map((def) => (
                <DefinitionCard
                  key={def.id}
                  definition={def}
                  projects={projects}
                  defaultProjectId={defaultProjectId}
                  usage={usage.get(def.slug) || 0}
                />
              ))}
            </ul>
          )}
        </section>

        {/* Cases — visual cards instead of dense table */}
        <section className="wf-section">
          <header className="wf-section-head">
            <div>
              <h2>Recent cases</h2>
              <p>{cases.length === 0 ? 'No cases yet — start one above.' : `${activeCases.length} active · ${completedCases.length} complete`}</p>
            </div>
            {cases.length > recentCases.length ? (
              <Link href="/workflows?view=all" className="wf-section-link">View all {cases.length} ↗</Link>
            ) : null}
          </header>

          {cases.length === 0 ? (
            <EmptyState title="No cases yet">
              <p>Start your first case from a definition above. ADGM Entity Setup is a good place to begin.</p>
            </EmptyState>
          ) : (
            <ul className="wf-caselist">
              {recentCases.map((c) => (
                <li key={c.id} className={`wf-casecard wf-casecard--${c.status}`}>
                  <Link href={`/workflows/${c.id}`} className="wf-casecard-link">
                    <div className="wf-casecard-status">
                      <StatusPill tone={STATUS_TONES[c.status] || 'neutral'}>
                        {STATUS_LABELS[c.status] || c.status}
                      </StatusPill>
                    </div>
                    <div className="wf-casecard-body">
                      <h3>{c.title}</h3>
                      <p>
                        <span>{c.definition_slug}</span>
                        <span aria-hidden>·</span>
                        <span>{c.current_stage_slug || '—'}</span>
                      </p>
                    </div>
                    <div className="wf-casecard-meta">
                      <time>{formatRelative(c.updated_at)}</time>
                      <small>{c.id.slice(-8)}</small>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </section>
      </div>
    </AdminShell>
  );
}
