import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AdminShell, EmptyState, StatCard, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { listAgents, listSchedules, upsertSchedule } from '@/lib/runtime.js';
import { runHeartbeatWorkerOnce } from '@/lib/heartbeat-worker.js';
import NewScheduleModal from './new-schedule-modal.jsx';

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

async function upsertScheduleAction(formData) {
  'use server';
  upsertSchedule({
    agent_id: String(formData.get('agent_id') || formData.get('name') || 'custom-agent'),
    name: String(formData.get('name') || ''),
    schedule: String(formData.get('schedule') || 'daily 07:30'),
    action_kind: String(formData.get('action_kind') || 'agent-tick'),
    delivery: String(formData.get('delivery') || 'dashboard + owner approval'),
    approval: String(formData.get('approval') || 'human-in-loop'),
    enabled: formData.get('enabled') === 'on',
  });
  revalidatePath('/schedules');
  redirect('/schedules');
}

async function toggleScheduleAction(formData) {
  'use server';
  upsertSchedule({
    agent_id: String(formData.get('agent_id')),
    name: String(formData.get('name')),
    schedule: String(formData.get('schedule')),
    action_kind: String(formData.get('action_kind') || 'agent-tick'),
    delivery: String(formData.get('delivery') || 'dashboard + owner approval'),
    approval: String(formData.get('approval') || 'human-in-loop'),
    enabled: String(formData.get('enabled')) === 'true',
  });
  revalidatePath('/schedules');
  redirect('/schedules');
}

async function processHeartbeatOnceAction() {
  'use server';
  await runHeartbeatWorkerOnce({ workerId: 'admin-console' });
  revalidatePath('/schedules');
  revalidatePath('/reports');
  redirect('/schedules');
}

export default function SchedulesPage() {
  const schedules = listSchedules();
  const agents = listAgents();

  const headerActions = (
    <>
      <form action={processHeartbeatOnceAction}>
        <button className="admin-button secondary" type="submit">Process heartbeat once</button>
      </form>
      <NewScheduleModal
        agents={agents.map((a) => ({ id: a.id, name: a.name }))}
        upsertAction={upsertScheduleAction}
      />
    </>
  );

  return (
    <AdminShell
      title="Schedules"
      description="madarX OS v1.0 schedule control: upsert cron-like agent work, enable or pause rows, and process heartbeat once."
      actions={headerActions}
    >
      <section className="admin-stats">
        <StatCard label="Schedules" value={schedules.length} />
        <StatCard label="Enabled" value={schedules.filter(schedule => schedule.enabled).length} />
        <StatCard label="Paused" value={schedules.filter(schedule => !schedule.enabled).length} />
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head"><span>Scheduling rules</span><small>Safe by default.</small></div>
        <div className="admin-copy"><p>Schedules queue durable heartbeat tasks. Agent execution remains local-first and approval-gated for elevated operations.</p><p>Use “Process heartbeat once” after queuing or approving tasks to advance one worker cycle from the admin console.</p></div>
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head"><span>Schedule rows</span><small>Enable/pause controls preserve schedule metadata.</small></div>
        {schedules.length ? (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead><tr><th>Agent</th><th>Status</th><th>Schedule</th><th>Next / last</th><th>Action</th></tr></thead>
              <tbody>
                {schedules.map(schedule => (
                  <tr key={schedule.id}>
                    <td><b>{schedule.agent_name}</b><small>{schedule.agent_id}</small></td>
                    <td><StatusPill tone={schedule.enabled ? 'ready' : 'neutral'}>{schedule.enabled ? 'enabled' : 'paused'}</StatusPill></td>
                    <td>{schedule.schedule}<small>{schedule.action_kind} · {schedule.approval}</small></td>
                    <td>Next: {schedule.next_run_at || 'manual'}<small>Last: {schedule.last_run_at || schedule.last_queued_at || 'not yet'}</small></td>
                    <td>
                      <form action={toggleScheduleAction}>
                        <input type="hidden" name="agent_id" value={schedule.agent_id} />
                        <input type="hidden" name="name" value={schedule.agent_name} />
                        <input type="hidden" name="schedule" value={schedule.schedule} />
                        <input type="hidden" name="action_kind" value={schedule.action_kind} />
                        <input type="hidden" name="delivery" value={schedule.delivery} />
                        <input type="hidden" name="approval" value={schedule.approval} />
                        <input type="hidden" name="enabled" value={String(!schedule.enabled)} />
                        <button className="admin-button secondary" type="submit">{schedule.enabled ? 'Pause' : 'Enable'}</button>
                      </form>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : <EmptyState title="No schedules yet">Create a schedule from the top right, or ensure the Caretaker.</EmptyState>}
      </section>
    </AdminShell>
  );
}
