/**
 * System Tasks Admin Page
 * View and manage automated system tasks
 */

import { Metadata } from 'next';
import { prisma } from '@/lib/db';
import { TaskManagementPanel } from '@/components/admin/task-management-panel';
import { BRAND } from '@/lib/white-label/constants';

export const metadata: Metadata = {
  title: `System Tasks | ${BRAND.primaryName} Admin`,
  description: 'Manage automated system tasks',
};

export const dynamic = 'force-dynamic';

export default async function SystemTasksPage() {
  const tasks = await prisma.systemTask.findMany({
    orderBy: [{ category: 'asc' }, { name: 'asc' }],
    include: {
      _count: {
        select: { runs: true, subscriptions: true },
      },
    },
  });

  // Group by category
  const tasksByCategory = tasks.reduce((acc: Record<string, any[]>, task: any) => {
    if (!acc[task.category]) {
      acc[task.category] = [];
    }
    acc[task.category].push(task);
    return acc;
  }, {} as Record<string, any[]>);

  return (
    <div className="min-h-screen bg-brand-bg text-white p-8">
      <div className="max-w-6xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold gradient-text">System Tasks</h1>
          <p className="text-gray-400 mt-2">
            Manage automated tasks that power Foundry Familiars. Enable or disable tasks,
            view run history, and configure task-specific settings.
          </p>
        </div>

        <div className="grid gap-4 mb-8">
          <div className="glass-card p-4 flex items-center justify-between">
            <div>
              <span className="text-gray-400">Total Tasks</span>
              <span className="ml-2 text-2xl font-bold text-brand">{tasks.length}</span>
            </div>
            <div>
              <span className="text-gray-400">Enabled</span>
              <span className="ml-2 text-2xl font-bold text-green-400">
                {tasks.filter((t: any) => t.isEnabled).length}
              </span>
            </div>
            <div>
              <span className="text-gray-400">Critical</span>
              <span className="ml-2 text-2xl font-bold text-brand-secondary-light">
                {tasks.filter((t: any) => t.isCritical).length}
              </span>
            </div>
          </div>
        </div>

        <TaskManagementPanel tasksByCategory={tasksByCategory} />
      </div>
    </div>
  );
}
