import { DashboardShell } from '../../../components/dashboard-shell';
import { RolesPermissionsBoard } from '../../../components/roles-permissions-board';
import { requireAuthToken } from '../../../lib/auth';
import { fetchAuditTrail, fetchRoles } from '../../../lib/api';

function formatRelativeTime(value: string) {
  const diff = Date.now() - new Date(value).getTime();
  const minutes = Math.max(1, Math.floor(diff / 60000));

  if (minutes < 60) {
    return `${minutes} min ago`;
  }

  const hours = Math.floor(minutes / 60);
  if (hours < 24) {
    return `${hours} hour${hours === 1 ? '' : 's'} ago`;
  }

  const days = Math.floor(hours / 24);
  return `${days} day${days === 1 ? '' : 's'} ago`;
}

function iconForAction(actionType: string) {
  if (actionType.includes('Created')) return 'add_circle';
  if (actionType.includes('Updated')) return 'person_edit';
  if (actionType.includes('Deleted')) return 'delete';
  return 'history';
}

export default async function RolesPage() {
  const token = await requireAuthToken();
  const [roles, auditTrail] = await Promise.all([
    fetchRoles(token),
    fetchAuditTrail(token, { limit: 3, module: 'Access Control' }),
  ]);

  return (
    <DashboardShell currentPath="/dashboard/roles">
      <section className="page-header">
        <div>
          <p className="page-eyebrow">Access Control</p>
          <h1 className="page-heading">Roles &amp; Permissions</h1>
          <p className="page-copy">Configure access levels and granular permissions for campaigns, analytics, settings, and audit visibility.</p>
        </div>
      </section>

      <RolesPermissionsBoard
        initialRoles={roles.map((role) => ({
          id: role.id,
          name: role.name,
          badge: role.badge,
          tone: role.tone,
          summary: role.summary,
          usersAssigned: role.usersAssigned,
          icon: role.icon,
          permissionRows: role.permissions,
        }))}
        initialAuditHighlights={auditTrail.items.map((item) => ({
          id: item.id,
          icon: iconForAction(item.actionType),
          title: item.actionType,
          description: item.details,
          time: formatRelativeTime(item.createdAt),
        }))}
      />
    </DashboardShell>
  );
}
