// components/tasks.jsx — TasksPanel: unified Tickets + Tools view.
// Board with inline job logs, queue controls, QuickDo at top.
// Depends on: React (useState, useCallback, useEffect, useMemo),
//             Card, StatusBadge, get, post, put from api.js,
//             QuickDo from home.jsx,
//             TICKET_STATUSES, STATUS_COLORS, PRIORITY_COLORS, TYPE_ICONS, TOOLS from tickets.jsx,
//             JOB_STATUS_COLORS from tools.jsx

// ── Hook: useTasksData — tickets + queue + tools in one ─────

function useTasksData() {
  const [tickets, setTickets] = useState([]);
  const [sprints, setSprints] = useState([]);
  const [queue, setQueue] = useState(null);
  const [jobs, setJobs] = useState([]);
  const [tools, setTools] = useState([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    const [tData, sData, qData, toolData] = await Promise.all([
      get("/dashboard/tickets"),
      get("/dashboard/sprints"),
      get("/dashboard/tools/queue"),
      get("/dashboard/tools/"),
    ]);
    setTickets(tData?.tickets || []);
    setSprints(sData?.sprints || []);
    setQueue(qData);
    setJobs(qData?.recent_jobs || []);
    setTools(toolData?.tools || []);
    setLoading(false);
  }, []);

  useEffect(() => {
    refresh();
    const timer = setInterval(refresh, 12000);
    return () => clearInterval(timer);
  }, [refresh]);

  return { tickets, sprints, queue, jobs, tools, loading, refresh };
}

// ── TaskCardHeader — title + priority + status badges ────────

function TaskCardHeader({ ticket }) {
  const statusColor = STATUS_COLORS[ticket.status] || "bg-gray-100 text-gray-600";
  const priorityColor = PRIORITY_COLORS[ticket.priority] || "bg-gray-100 text-gray-600";
  const typeIcon = TYPE_ICONS[ticket.type] || "📋";
  return (
    <div className="flex items-start justify-between gap-2">
      <div className="flex items-center gap-1.5 min-w-0">
        <span title={ticket.type}>{typeIcon}</span>
        <span className="font-medium text-gray-900 truncate">{ticket.task || ticket.title}</span>
      </div>
      <div className="flex items-center gap-1 shrink-0">
        <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${priorityColor}`}>{ticket.priority}</span>
        <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${statusColor}`}>{ticket.status?.replace("_", " ")}</span>
      </div>
    </div>
  );
}

// ── TaskCardMeta — ticket id + tool + job badge ──────────────

function TaskCardMeta({ ticket, ticketJob }) {
  return (
    <div className="flex items-center gap-2 mt-1.5 text-xs text-gray-400">
      <span className="font-mono">{ticket.id?.slice(0, 12)}</span>
      {ticket.assigned_tool && (
        <span className="px-1.5 py-0.5 bg-indigo-50 text-indigo-600 rounded">{ticket.assigned_tool.tool}</span>
      )}
      {ticketJob && (
        <span className={`px-1.5 py-0.5 rounded ${JOB_STATUS_COLORS[ticketJob.status] || "bg-gray-100 text-gray-500"}`}>
          job: {ticketJob.status}
        </span>
      )}
    </div>
  );
}

// ── TaskInlineLogs — poll + display stdout for running jobs ──

function TaskInlineLogs({ jobId, onDone }) {
  const [logs, setLogs] = useState("");

  useEffect(() => {
    if (!jobId) return;
    const timer = setInterval(async () => {
      const j = await get(`/dashboard/tools/queue/jobs/${jobId}`);
      if (j?.result?.stdout) setLogs(j.result.stdout.slice(-500));
      if (j?.status === "done" || j?.status === "failed") {
        clearInterval(timer);
        if (onDone) onDone();
      }
    }, 3000);
    return () => clearInterval(timer);
  }, [jobId]);

  return (
    <pre className="mt-2 p-2 bg-gray-900 text-green-300 text-[11px] rounded overflow-auto max-h-[120px] font-mono leading-tight">
      {logs || "Waiting for output..."}
    </pre>
  );
}

// ── TaskJobError — show error for failed jobs ────────────────

function TaskJobError({ error }) {
  if (!error) return null;
  return (
    <div className="mt-2 p-2 bg-red-50 border border-red-200 rounded text-xs text-red-700 truncate">
      {error}
    </div>
  );
}

// ── TaskStatusActions — expandable status change buttons ─────

function TaskStatusActions({ ticket, onRefresh }) {
  const [expanded, setExpanded] = useState(false);

  const handleStatusChange = async (newStatus) => {
    await put(`/dashboard/tickets/${ticket.id}`, { status: newStatus });
    if (onRefresh) onRefresh();
  };

  return (
    <div>
      <button onClick={() => setExpanded(!expanded)}
        className="mt-1.5 text-xs text-gray-400 hover:text-gray-600">
        {expanded ? "▴ Less" : "▸ Actions"}
      </button>
      {expanded && (
        <div className="mt-2 pt-2 border-t border-gray-100 flex flex-wrap gap-1">
          {TICKET_STATUSES.filter(s => s !== ticket.status).map(s => (
            <button key={s} onClick={() => handleStatusChange(s)}
              className="text-[11px] px-2 py-0.5 rounded border border-gray-200 hover:bg-gray-50">
              {s.replace("_", " ")}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ── TaskTicketCard — thin shell composing sub-components ─────

function TaskTicketCard({ ticket, jobs, onRefresh }) {
  const ticketJob = jobs.find(j => j.ticket_id === ticket.id);
  const isActive = ticketJob && (ticketJob.status === "running" || ticketJob.status === "queued");

  return (
    <div className={`bg-white rounded-lg border p-3 text-sm transition-shadow hover:shadow-sm ${
      isActive ? "border-amber-300 ring-1 ring-amber-100" : "border-gray-200"
    }`}>
      <TaskCardHeader ticket={ticket} />
      <TaskCardMeta ticket={ticket} ticketJob={ticketJob} />
      {isActive && <TaskInlineLogs jobId={ticketJob.id} onDone={onRefresh} />}
      {ticketJob?.status === "failed" && <TaskJobError error={ticketJob.error} />}
      <TaskStatusActions ticket={ticket} onRefresh={onRefresh} />
    </div>
  );
}

// ── QueueBar — compact queue controls ────────────────────────

function QueueBar({ queue, onStartStop }) {
  if (!queue) return null;
  const byStatus = queue.by_status || {};
  return (
    <div className="flex items-center gap-4 px-4 py-2 bg-gray-50 rounded-lg border text-sm">
      <span className="font-medium text-gray-700">Queue</span>
      <span className="text-gray-500"><strong>{queue.queue_size || 0}</strong> pending</span>
      {byStatus.running > 0 && <span className="text-amber-600"><strong>{byStatus.running}</strong> running</span>}
      {byStatus.done > 0 && <span className="text-emerald-600"><strong>{byStatus.done}</strong> done</span>}
      {byStatus.failed > 0 && <span className="text-red-500"><strong>{byStatus.failed}</strong> failed</span>}
      <div className="ml-auto flex items-center gap-2">
        <span className={`text-xs font-medium ${queue.running ? "text-emerald-600" : "text-gray-400"}`}>
          {queue.running ? "● Running" : "○ Stopped"}
        </span>
        <button onClick={() => onStartStop(!queue.running)}
          className={`text-xs px-2.5 py-1 rounded font-medium ${
            queue.running
              ? "bg-red-100 text-red-600 hover:bg-red-200"
              : "bg-emerald-100 text-emerald-600 hover:bg-emerald-200"
          }`}>
          {queue.running ? "⏸ Pause" : "▶ Start"}
        </button>
      </div>
    </div>
  );
}

// ── TasksPanel (main) ────────────────────────────────────────

function TasksPanel() {
  const { tickets, queue, jobs, loading, refresh } = useTasksData();
  const [view, setView] = useState("board"); // board | list
  const [filterStatus, setFilterStatus] = useState("");

  const filtered = React.useMemo(() => {
    if (!filterStatus) return tickets;
    return tickets.filter(t => t.status === filterStatus);
  }, [tickets, filterStatus]);

  const boardColumns = React.useMemo(() => {
    const cols = {};
    // Simplified board columns: Backlog, To Do, In Progress, Done, Failed
    const boardStatuses = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"];
    boardStatuses.forEach(s => { cols[s] = []; });
    filtered.forEach(t => {
      if (cols[t.status]) cols[t.status].push(t);
    });
    return cols;
  }, [filtered]);

  const handleStartStop = async (start) => {
    await post(`/dashboard/tools/queue/${start ? "start" : "stop"}`, {});
    refresh();
  };

  if (loading) {
    return <Card title="Tasks"><p className="text-gray-400 text-sm">Loading…</p></Card>;
  }

  return (
    <div className="space-y-4">
      {/* Quick Action */}
      <QuickDo compact onCreated={refresh} />

      {/* Queue controls */}
      <QueueBar queue={queue} onStartStop={handleStartStop} />

      {/* Toolbar */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="flex border rounded overflow-hidden">
            <button onClick={() => setView("board")}
              className={`px-3 py-1 text-xs font-medium ${view === "board" ? "bg-blue-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50"}`}>
              Board
            </button>
            <button onClick={() => setView("list")}
              className={`px-3 py-1 text-xs font-medium ${view === "list" ? "bg-blue-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50"}`}>
              List
            </button>
          </div>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
            className="text-xs px-2 py-1 border rounded text-gray-600">
            <option value="">All statuses</option>
            {TICKET_STATUSES.map(s => <option key={s} value={s}>{s.replace("_", " ")}</option>)}
          </select>
          <span className="text-xs text-gray-400">{filtered.length} task{filtered.length !== 1 ? "s" : ""}</span>
        </div>
        <button onClick={refresh} className="text-xs px-3 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200">
          ↻ Refresh
        </button>
      </div>

      {/* Board view */}
      {view === "board" && (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          {TICKET_STATUSES.map(status => (
            <div key={status} className="bg-gray-50 rounded-lg p-2 min-h-[200px]">
              <h5 className={`text-xs font-medium px-2 py-1 rounded mb-2 ${STATUS_COLORS[status] || "bg-gray-100 text-gray-600"}`}>
                {status.replace("_", " ")} ({boardColumns[status]?.length || 0})
              </h5>
              <div className="space-y-2">
                {(boardColumns[status] || []).map(t => (
                  <TaskTicketCard key={t.id} ticket={t} jobs={jobs} onRefresh={refresh} />
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* List view */}
      {view === "list" && (
        <div className="space-y-2">
          {filtered.length === 0 ? (
            <Card title="No tasks"><p className="text-gray-400 text-sm">Use Quick Action above to create your first task.</p></Card>
          ) : (
            filtered.map(t => (
              <TaskTicketCard key={t.id} ticket={t} jobs={jobs} onRefresh={refresh} />
            ))
          )}
        </div>
      )}

      {/* Recent jobs table (collapsed) */}
      {jobs.length > 0 && (
        <Card title={`Recent Jobs (${jobs.length})`}>
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead>
                <tr className="border-b border-gray-200 text-xs text-gray-500 uppercase">
                  <th className="py-2 px-3">ID</th>
                  <th className="py-2 px-3">Ticket</th>
                  <th className="py-2 px-3">Tool</th>
                  <th className="py-2 px-3">Status</th>
                  <th className="py-2 px-3">Duration</th>
                  <th className="py-2 px-3">Error</th>
                </tr>
              </thead>
              <tbody>
                {jobs.map(j => (
                  <tr key={j.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-1.5 px-3 text-xs font-mono text-gray-400">{j.id?.slice(0, 10)}</td>
                    <td className="py-1.5 px-3 text-xs font-mono text-gray-500">{j.ticket_id?.slice(0, 12)}</td>
                    <td className="py-1.5 px-3 text-xs font-medium">{j.tool}</td>
                    <td className="py-1.5 px-3">
                      <span className={`text-[11px] px-1.5 py-0.5 rounded-full ${JOB_STATUS_COLORS[j.status] || "bg-gray-100"}`}>{j.status}</span>
                    </td>
                    <td className="py-1.5 px-3 text-xs text-gray-400">{j.duration_s > 0 ? `${j.duration_s}s` : "—"}</td>
                    <td className="py-1.5 px-3 text-xs text-red-400 truncate max-w-[200px]">{j.error || ""}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  );
}
