import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import Link from 'next/link';
import { AdminShell, EmptyState } from '@/app/components/admin/admin-page.jsx';
import { createAgent, deleteAgent, listAgents, listSchedules, updateAgent } from '@/lib/runtime.js';
import { listAgentEngines } from '@/lib/agent-engines.js';
import { listMarketplaceTools } from '@/lib/tools/registry.js';
import { listProjects, DEFAULT_PROJECT_ID } from '@/lib/projects.js';
import AgentsLiveRefresh from './agents-live-refresh.jsx';
import NewAgentModal from './new-agent-modal';
import { AgentBuilderCard } from '@/app/components/ui/agent-builder-card';

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

async function createAgentAction(formData: FormData) {
  'use server';
  const tools = String(formData.get('tools') || '')
    .split(',')
    .map(t => t.trim())
    .filter(Boolean);
  const reportsToRaw = String(formData.get('reports_to') || '').trim();
  const titleRaw = String(formData.get('title') || '').trim();
  const roleRaw = String(formData.get('role') || '').trim();
  const projectIdRaw = String(formData.get('project_id') || '').trim();
  const created = createAgent({
    name: String(formData.get('name') || 'Custom Agent'),
    type: String(formData.get('type') || 'custom'),
    mission: String(formData.get('mission') || 'Support madarX OS operations.'),
    schedule: String(formData.get('schedule') || 'on demand'),
    engine: String(formData.get('engine') || 'claude-code'),
    model: String(formData.get('model') || ''),
    tools,
    approval: String(formData.get('approval') || 'human-in-loop'),
    reports_to: reportsToRaw || null,
    title: titleRaw || null,
    role: roleRaw || 'individual_contributor',
    project_id: projectIdRaw || DEFAULT_PROJECT_ID,
  });
  if (created.agent.schedule !== 'on demand') revalidatePath('/schedules');
  revalidatePath('/agents');
  revalidatePath('/org');
  redirect('/agents');
}

async function deleteAgentAction(formData: FormData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  if (agentId) deleteAgent(agentId);
  revalidatePath('/agents');
  revalidatePath('/schedules');
  redirect('/agents');
}

async function updateAgentAction(formData: FormData) {
  'use server';
  const agentId = String(formData.get('agent_id') || '');
  const engine = String(formData.get('engine') || '');
  const model = String(formData.get('model') || '').trim();
  if (agentId && engine) updateAgent(agentId, { engine, model: model || undefined });
  revalidatePath('/agents');
  redirect('/agents');
}

const TOOL_CATEGORY_RULES: Array<[RegExp, string]> = [
  [/^gh_|^github/i, 'github'],
  [/^supabase/i, 'supabase'],
  [/^vercel/i, 'vercel'],
  [/^email_|^resend/i, 'email'],
  [/^gmail/i, 'gmail'],
  [/web[-_]?search|web[-_]?fetch|browser/i, 'web'],
  [/files?|cron|terminal|process|local/i, 'local_machine'],
];

function categoriesForTools(tools: string[] | undefined | null): string[] {
  if (!tools || tools.length === 0) return [];
  const seen = new Set<string>();
  for (const raw of tools) {
    const t = String(raw || '').trim();
    if (!t) continue;
    for (const [pattern, category] of TOOL_CATEGORY_RULES) {
      if (pattern.test(t)) {
        seen.add(category);
        break;
      }
    }
  }
  return Array.from(seen);
}

export default async function AgentsPage() {
  const agents = listAgents();
  const schedules = listSchedules();
  const engines = await listAgentEngines();
  const tools = listMarketplaceTools();
  const projects = listProjects({ status: 'active' }).map((p: { id: string; name: string }) => ({ id: p.id, name: p.name }));
  const schedulesByAgent = new Map(schedules.map((s: { agent_id: string }) => [s.agent_id, s]));

  const headerActions = (
    <NewAgentModal
      engines={engines}
      agents={agents.map((a: { id: string; name: string }) => ({ id: a.id, name: a.name }))}
      tools={tools.map((t: any) => ({
        name: t.name,
        title: t.title,
        description: t.description,
        category: t.category,
        risk_level: t.risk_level,
        available: t.available,
        missing_env: t.missing_env,
      }))}
      projects={projects}
      currentProjectId={DEFAULT_PROJECT_ID}
      createAction={createAgentAction}
    />
  );

  return (
    <AdminShell
      kicker="madarX OS"
      title="Agents"
      description="Your workers. Each one has a mission, a schedule, and a Run button. Create an agent or open one to see its activity."
      actions={headerActions}
    >
      <AgentsLiveRefresh />

      <div className="mkt-page" data-page="agents">
        <section className="mkt-section" aria-live="polite">
          {agents.length ? (
            <ul className="mkt-grid agent-grid">
              {agents.map((agent: any) => {
                const schedule = schedulesByAgent.get(agent.id) as { schedule?: string } | undefined;
                const scheduleLabel = schedule?.schedule || agent.schedule || 'on demand';
                const toolCategories = categoriesForTools(agent.tools);
                return (
                  <AgentBuilderCard
                    key={agent.id}
                    agent={agent}
                    scheduleLabel={scheduleLabel}
                    toolCategories={toolCategories}
                    engines={engines}
                    updateAction={updateAgentAction}
                    deleteAction={deleteAgentAction}
                  />
                );
              })}
            </ul>
          ) : (
            <EmptyState title="No agents yet">
              Create an agent to give yourself a worker that runs on a schedule.
              You can also ask the Main Agent to set one up over chat or WhatsApp.
            </EmptyState>
          )}
        </section>

        <p className="agents-runtime-footer">
          Looking for engine status, workers, or technical diagnostics?{' '}
          <Link href="/runtime">View runtime diagnostics →</Link>
        </p>
      </div>
    </AdminShell>
  );
}
