import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AdminShell } from '@/app/components/admin/admin-page.jsx';
import { listAgents } from '@/lib/runtime.js';
import { listProjects } from '@/lib/projects.js';
import { createTask, getTaskOperatorSnapshot, listTasks, reportingSnapshot } from '@/lib/delegation.js';
import NewTaskModal from './new-task-modal.jsx';
import TasksWorkspace from './tasks-workspace.jsx';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

async function createTaskAction(formData) {
  'use server';
  const assignee = String(formData.get('assignee_agent_id') || '').trim();
  const parent = String(formData.get('parent_task_id') || '').trim();
  const project = String(formData.get('project_id') || '').trim();
  const goal = String(formData.get('goal_id') || '').trim();
  const status = String(formData.get('status') || '').trim() || undefined;
  const blocked = String(formData.get('blocked_reason') || '').trim();
  const dueAt = String(formData.get('due_at') || '').trim();
  const estimateRaw = String(formData.get('estimate_minutes') || '').trim();
  const recurrence = String(formData.get('recurrence') || '').trim();
  const acceptance = String(formData.get('acceptance_criteria') || '').trim();
  const tags = formData.getAll('tags').map((v) => String(v).trim()).filter(Boolean);
  const watchers = formData.getAll('watchers').map((v) => String(v).trim()).filter(Boolean);
  const checklist = formData.getAll('checklist').map((v) => String(v).trim()).filter(Boolean);
  createTask({
    title: String(formData.get('title') || '').trim() || 'Untitled task',
    description: String(formData.get('description') || '').trim() || null,
    assignee_agent_id: assignee || null,
    priority: String(formData.get('priority') || 'medium'),
    status,
    parent_task_id: parent || null,
    project_id: project || null,
    goal_id: goal || null,
    blocked_reason: blocked || null,
    due_at: dueAt || null,
    estimate_minutes: estimateRaw === '' ? null : Number(estimateRaw),
    recurrence: recurrence || null,
    acceptance_criteria: acceptance || null,
    tags,
    watchers,
    checklist,
    created_by_user_id: 'ak@madarx.io',
  });
  revalidatePath('/tasks');
  revalidatePath('/activity');
  redirect('/tasks');
}

export default function TasksPage() {
  const tasks = listTasks({ limit: 200 });
  const taskRows = tasks.map((task) => ({
    task,
    operator: getTaskOperatorSnapshot(task.id),
  }));
  const agents = listAgents();
  const projects = listProjects({ status: 'all' });
  const reporting = reportingSnapshot();

  const projectSummaries = projects.map((p) => ({
    id: p.id,
    slug: p.slug,
    name: p.name,
    color: p.color,
    status: p.status,
  }));
  const agentSummaries = agents.map((a) => ({ id: a.id, name: a.name }));
  const parentCandidates = tasks
    .filter((t) => t.status !== 'done' && t.status !== 'cancelled')
    .slice(0, 50)
    .map((t) => ({ id: t.id, title: t.title }));

  const headerActions = (
    <NewTaskModal
      agents={agentSummaries}
      projects={projectSummaries}
      parentTasks={parentCandidates}
      createAction={createTaskAction}
    />
  );

  return (
    <AdminShell
      kicker="madarX OS v1.0"
      title="Tasks"
      description="Delegated work across projects, agents, and statuses."
      actions={headerActions}
    >
      <div className="mkt-page" data-page="tasks-stats">
        <section className="mkt-stats">
          <div className="mkt-stat">
            <b>{reporting.totals.active_tasks}</b>
            <span>Active</span>
          </div>
          <div className="mkt-stat">
            <b>{reporting.totals.blocked_tasks}</b>
            <span>Blocked</span>
          </div>
          <div className="mkt-stat">
            <b>{reporting.totals.running_executions}</b>
            <span>Running</span>
          </div>
          <div className="mkt-stat">
            <b>{reporting.totals.recent_completions}</b>
            <span>Recent done</span>
          </div>
        </section>
      </div>

      <TasksWorkspace
        taskRows={taskRows}
        agents={agentSummaries}
        projects={projectSummaries}
      />
    </AdminShell>
  );
}
