import { revalidatePath } from 'next/cache';
import { AdminShell, EmptyState, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { addTaskComment, getTask, getTaskActiveRun, getTaskChildren, getTaskOperatorSnapshot, listAgentRunEvents, listAgentRuns, listTaskAttachments, listTaskChecklist, listTaskComments, listTaskEvents, releaseTask, updateTask } from '@/lib/delegation.js';
import { listAgents } from '@/lib/runtime.js';
import { notFound } from 'next/navigation';
import TaskChecklistEditor from './checklist-editor.jsx';

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

const TASK_STATUSES = ['backlog', 'todo', 'in_progress', 'in_review', 'blocked', 'done', 'cancelled'];
const TASK_PRIORITIES = ['low', 'medium', 'high', 'urgent'];

function statusTone(status) {
  if (status === 'done') return 'ready';
  if (status === 'blocked' || status === 'cancelled') return 'danger';
  if (status === 'in_progress' || status === 'in_review') return 'warn';
  return 'neutral';
}

function priorityTone(priority) {
  if (priority === 'urgent') return 'danger';
  if (priority === 'high') return 'warn';
  return 'neutral';
}

function runTone(status) {
  if (status === 'running') return 'warn';
  if (status === 'waiting_approval') return 'danger';
  if (status === 'failed' || status === 'timed_out' || status === 'cancelled') return 'danger';
  if (status === 'succeeded' || status === 'completed') return 'ready';
  return 'neutral';
}

function shortDate(iso) {
  if (!iso) return null;
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso.slice(0, 16);
  return iso.slice(0, 16).replace('T', ' ');
}

async function updateTaskAction(formData) {
  'use server';
  const id = String(formData.get('task_id') || '');
  const assignee = String(formData.get('assignee_agent_id') || '').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 = String(formData.get('tags') || '').trim();
  const watchers = formData.getAll('watchers').map((v) => String(v).trim()).filter(Boolean);
  updateTask(id, {
    title: String(formData.get('title') || '').trim(),
    description: String(formData.get('description') || '').trim() || null,
    status: String(formData.get('status') || ''),
    priority: String(formData.get('priority') || ''),
    assignee_agent_id: assignee || null,
    blocked_reason: String(formData.get('blocked_reason') || '').trim() || null,
    due_at: dueAt || null,
    estimate_minutes: estimateRaw === '' ? null : Number(estimateRaw),
    recurrence: recurrence || null,
    acceptance_criteria: acceptance || null,
    tags: tags ? tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
    watchers,
  });
  revalidatePath(`/tasks/${id}`);
  revalidatePath('/tasks');
  revalidatePath('/activity');
}

async function addCommentAction(formData) {
  'use server';
  const id = String(formData.get('task_id') || '');
  const body = String(formData.get('body') || '').trim();
  if (body) addTaskComment(id, { body, author_user_id: 'ak@madarx.io' });
  revalidatePath(`/tasks/${id}`);
}

async function releaseTaskAction(formData) {
  'use server';
  const id = String(formData.get('task_id') || '');
  releaseTask(id);
  revalidatePath(`/tasks/${id}`);
  revalidatePath('/tasks');
}

export default async function TaskDetailPage({ params }) {
  const { id } = await params;
  const task = getTask(id);
  if (!task) notFound();
  const agents = listAgents();
  const agentsById = new Map(agents.map(a => [a.id, a]));
  const children = getTaskChildren(id);
  const comments = listTaskComments(id);
  const events = listTaskEvents(id);
  const runs = listAgentRuns({ task_id: id, limit: 100 });
  const activeRun = getTaskActiveRun(id);
  const activeRunEvents = activeRun ? listAgentRunEvents(activeRun.id) : [];
  const operator = getTaskOperatorSnapshot(id);
  const checklist = listTaskChecklist(id);
  const attachments = listTaskAttachments(id);
  const assigneeName = task.assignee_agent_id
    ? (agentsById.get(task.assignee_agent_id)?.name || task.assignee_agent_id)
    : 'unassigned';
  const tags = Array.isArray(task.tags) ? task.tags : [];
  const watchers = Array.isArray(task.watchers) ? task.watchers : [];
  const dueAtDate = task.due_at ? task.due_at.slice(0, 10) : '';
  const isOverdue = task.due_at && new Date(task.due_at).getTime() < Date.now() && task.status !== 'done' && task.status !== 'cancelled';
  const estimateLabel = task.estimate_minutes
    ? (task.estimate_minutes < 60 ? `${task.estimate_minutes}m` : `${Math.floor(task.estimate_minutes / 60)}h${task.estimate_minutes % 60 ? (task.estimate_minutes % 60) + 'm' : ''}`)
    : null;

  return (
    <AdminShell
      title={task.title}
      description={task.description || 'No description recorded.'}
      actions={<a className="admin-button secondary" href="/tasks">Back to tasks</a>}
    >
      <section className="task-hero-meta">
        <StatusPill tone={statusTone(task.status)}>{task.status}</StatusPill>
        <StatusPill tone={priorityTone(task.priority)}>{task.priority}</StatusPill>
        <span>{assigneeName}</span>
        {task.due_at ? (
          <>
            <span>·</span>
            <span className={`task-meta-due tone-${isOverdue ? 'overdue' : 'future'}`}>
              {isOverdue ? '⚠ ' : ''}Due {task.due_at.slice(0, 10)}
            </span>
          </>
        ) : null}
        {estimateLabel ? <><span>·</span><span>⏱ {estimateLabel}</span></> : null}
        {task.recurrence ? <><span>·</span><span title={`Recurs ${task.recurrence}`}>↻ {task.recurrence}</span></> : null}
        {watchers.length ? <><span>·</span><span>👁 {watchers.length} watcher{watchers.length === 1 ? '' : 's'}</span></> : null}
        <span>·</span>
        <span>updated {shortDate(task.updated_at)}</span>
        <span>·</span>
        <span className="task-hero-id">{task.id}</span>
      </section>

      {tags.length ? (
        <section className="task-hero-tags">
          {tags.map((t) => <span key={t} className="task-meta-tag">#{t}</span>)}
        </section>
      ) : null}

      {operator?.needs_action ? (
        <section className="admin-panel admin-operator-alert">
          <div className="admin-panel-head">
            <span>Operator attention needed</span>
            <small>Failure, approval, or blocker requiring action.</small>
          </div>
          <p>{operator.needs_action_reason}</p>
          <div className="admin-tool-meta">
            {operator.active_run_id ? <span>active: {operator.active_run_id}</span> : null}
            {operator.last_failure_run_id ? <span>failure: {operator.last_failure_run_id}</span> : null}
            {operator.checkout_run_id ? <span>checkout: {operator.checkout_run_id}</span> : null}
          </div>
        </section>
      ) : null}

      <div className="task-detail-layout">
        <main className="task-detail-main">
          {task.acceptance_criteria ? (
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Acceptance criteria</span>
                <small>Definition of done.</small>
              </div>
              <pre className="task-acceptance">{task.acceptance_criteria}</pre>
            </section>
          ) : null}

          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>Checklist</span>
              <small>{checklist.filter((c) => c.done).length} / {checklist.length} done</small>
            </div>
            <TaskChecklistEditor taskId={task.id} initial={checklist} />
          </section>

          {attachments.length ? (
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Attachments</span>
                <small>{attachments.length} artifact{attachments.length === 1 ? '' : 's'}</small>
              </div>
              <ul className="task-attachments">
                {attachments.map((a) => (
                  <li key={a.id}>
                    <a className="admin-link" href={a.path} target="_blank" rel="noreferrer">
                      {a.title || a.path}
                    </a>
                    <small>{a.kind || 'file'} · {shortDate(a.created_at)}</small>
                  </li>
                ))}
              </ul>
            </section>
          ) : null}

          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>Comments</span>
              <small>{comments.length} {comments.length === 1 ? 'note' : 'notes'} · progress, blockers, handoff.</small>
            </div>
            {comments.length ? (
              <ul className="task-thread">
                {comments.map(comment => (
                  <li key={comment.id} className="task-thread-item">
                    <div className="task-thread-meta">
                      <b>{comment.author_agent_id ? (agentsById.get(comment.author_agent_id)?.name || comment.author_agent_id) : comment.author_user_id || 'system'}</b>
                      <small>{shortDate(comment.created_at)}</small>
                    </div>
                    <p>{comment.body}</p>
                  </li>
                ))}
              </ul>
            ) : <EmptyState title="No comments yet">Add the first note below.</EmptyState>}
            <form className="task-comment-form" action={addCommentAction}>
              <input type="hidden" name="task_id" value={task.id} />
              <textarea name="body" rows={3} required placeholder="Progress note, blocker, or handoff." />
              <button className="admin-button" type="submit">Post comment</button>
            </form>
          </section>

          {activeRun ? (
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Active run</span>
                <small>{activeRun.id} · {activeRun.trigger_source || 'task execution'}</small>
              </div>
              <div className="task-active-run-head">
                <StatusPill tone={runTone(activeRun.status)}>{activeRun.status}</StatusPill>
                <span>{shortDate(activeRun.created_at)}</span>
              </div>
              {activeRunEvents.length ? (
                <ul className="task-run-events">
                  {activeRunEvents.map(event => (
                    <li key={event.id} className="task-run-event">
                      <div className="task-run-event-head">
                        <b>{event.event_type}</b>
                        <small>#{event.seq}</small>
                      </div>
                      {event.message ? <p>{event.message}</p> : null}
                    </li>
                  ))}
                </ul>
              ) : <p className="task-mute">No events recorded for this run yet.</p>}
            </section>
          ) : null}

          <details className="admin-panel task-timeline">
            <summary className="admin-panel-head">
              <span>Event timeline</span>
              <small>{events.length} {events.length === 1 ? 'event' : 'events'} · immutable history</small>
            </summary>
            {events.length ? (
              <ul className="task-timeline-list">
                {events.map(event => (
                  <li key={event.id}>
                    <div><b>{event.event_type}</b><small>{shortDate(event.created_at)}</small></div>
                    {event.payload && Object.keys(event.payload).length ? (
                      <pre>{JSON.stringify(event.payload, null, 2)}</pre>
                    ) : null}
                  </li>
                ))}
              </ul>
            ) : <p className="task-mute">No events recorded.</p>}
          </details>
        </main>

        <aside className="task-detail-side">
          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>At a glance</span>
              <small>Lineage and lifecycle.</small>
            </div>
            <div className="agent-detail-kv-grid">
              <div className="agent-detail-kv"><b>Parent</b><span>{task.parent_task_id ? <a className="admin-link" href={`/tasks/${task.parent_task_id}`} style={{ marginTop: 0 }}>{task.parent_task_id}</a> : 'root task'}</span></div>
              <div className="agent-detail-kv"><b>Created</b><span>{shortDate(task.created_at)}</span></div>
              <div className="agent-detail-kv"><b>Started</b><span>{task.started_at ? shortDate(task.started_at) : '—'}</span></div>
              <div className="agent-detail-kv"><b>Updated</b><span>{shortDate(task.updated_at)}</span></div>
              {task.checkout_run_id ? <div className="agent-detail-kv"><b>Checkout</b><span>{task.checkout_run_id}</span></div> : null}
              {task.execution_run_id ? <div className="agent-detail-kv"><b>Execution</b><span>{task.execution_run_id}</span></div> : null}
              {operator?.last_failure_error ? <div className="agent-detail-kv danger"><b>Last failure</b><span>{operator.last_failure_error}</span></div> : null}
            </div>
            {task.checkout_run_id ? (
              <form action={releaseTaskAction} style={{ marginTop: 12 }}>
                <input type="hidden" name="task_id" value={task.id} />
                <button className="admin-button danger" type="submit">Release checkout</button>
              </form>
            ) : null}
          </section>

          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>Edit task</span>
              <small>Reassign, change status, unblock.</small>
            </div>
            <form className="task-edit-form" action={updateTaskAction}>
              <input type="hidden" name="task_id" value={task.id} />
              <label>Title<input name="title" defaultValue={task.title} required /></label>
              <label>Description<textarea name="description" rows={3} defaultValue={task.description || ''} /></label>
              <div className="task-edit-row">
                <label>Status
                  <select name="status" defaultValue={task.status}>
                    {TASK_STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </label>
                <label>Priority
                  <select name="priority" defaultValue={task.priority}>
                    {TASK_PRIORITIES.map(p => <option key={p} value={p}>{p}</option>)}
                  </select>
                </label>
              </div>
              <label>Assignee
                <select name="assignee_agent_id" defaultValue={task.assignee_agent_id || ''}>
                  <option value="">Unassigned</option>
                  {agents.map(agent => <option key={agent.id} value={agent.id}>{agent.name}</option>)}
                </select>
              </label>
              <div className="task-edit-row">
                <label>Due date<input type="date" name="due_at" defaultValue={dueAtDate} /></label>
                <label>Estimate (min)<input type="number" name="estimate_minutes" min="0" step="15" defaultValue={task.estimate_minutes ?? ''} /></label>
              </div>
              <label>Recurrence
                <select name="recurrence" defaultValue={task.recurrence || ''}>
                  <option value="">None</option>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                  <option value="every 1d">Every 1 day</option>
                  <option value="every 3d">Every 3 days</option>
                  <option value="every 1w">Every 1 week</option>
                </select>
              </label>
              <label>Tags (comma-separated)
                <input name="tags" defaultValue={tags.join(', ')} placeholder="ux, infra, q3" />
              </label>
              <label>Watchers
                <select name="watchers" multiple size={Math.min(6, Math.max(3, agents.length))} defaultValue={watchers}>
                  {agents.map((agent) => <option key={agent.id} value={agent.id}>{agent.name}</option>)}
                </select>
                <small className="task-modal-hint">Cmd/Ctrl-click to select multiple.</small>
              </label>
              <label>Acceptance criteria<textarea name="acceptance_criteria" rows={4} defaultValue={task.acceptance_criteria || ''} placeholder="- [ ] step 1&#10;- [ ] step 2" /></label>
              <label>Blocked reason<input name="blocked_reason" defaultValue={task.blocked_reason || ''} placeholder="Used when status = blocked" /></label>
              <button className="admin-button" type="submit">Save task</button>
            </form>
          </section>

          {children.length ? (
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Child tasks</span>
                <small>{children.length} {children.length === 1 ? 'subtask' : 'subtasks'}</small>
              </div>
              <ul className="task-child-list">
                {children.map(child => (
                  <li key={child.id}>
                    <a className="admin-link" href={`/tasks/${child.id}`} style={{ marginTop: 0 }}>{child.title}</a>
                    <StatusPill tone={statusTone(child.status)}>{child.status}</StatusPill>
                  </li>
                ))}
              </ul>
            </section>
          ) : null}

          {runs.length ? (
            <section className="admin-panel">
              <div className="admin-panel-head">
                <span>Run history</span>
                <small>{runs.length} {runs.length === 1 ? 'attempt' : 'attempts'} · showing 6</small>
              </div>
              <ul className="task-run-list">
                {runs.slice(0, 6).map(run => (
                  <li key={run.id}>
                    <div className="task-run-list-head">
                      <b>{run.trigger_source || 'task execution'}</b>
                      <StatusPill tone={runTone(run.status)}>{run.status}</StatusPill>
                    </div>
                    <small>{run.id} · {shortDate(run.created_at)}</small>
                  </li>
                ))}
              </ul>
            </section>
          ) : null}
        </aside>
      </div>
    </AdminShell>
  );
}
