// components/human.jsx — HumanTaskPanel: human-in-the-loop task management.
// Depends on: React (useState, useCallback, useEffect), Card, get, post from api.js

const useState = React.useState;
const useCallback = React.useCallback;
const useEffect = React.useEffect;
const useMemo = React.useMemo;

function _isHumanTicket(ticket) {
  return ticket?.assigned_tool?.tool === "human";
}

function useHumanTasks() {
  const [tasks, setTasks] = useState([]);
  const [projects, setProjects] = useState([]);
  const [sprints, setSprints] = useState([]);
  const [queue, setQueue] = useState(null);
  const [jobs, setJobs] = useState([]);
  const [tools, setTools] = useState([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const [tData, sData, pData, qData, toolData] = await Promise.all([
        get("/dashboard/tickets"),
        get("/dashboard/sprints"),
        get("/dashboard/projects"),
        get("/dashboard/tools/queue"),
        get("/dashboard/tools/"),
      ]);
      const allTickets = tData?.tickets || [];
      setTasks(allTickets.filter(_isHumanTicket));
      setSprints(sData?.sprints || []);
      setProjects(Array.isArray(pData) ? pData : []);
      setQueue(qData || null);
      setJobs(qData?.recent_jobs || []);
      setTools(toolData?.tools || []);
    } catch (e) {
      console.error("Failed to load human tasks:", e);
      setTasks([]);
      setSprints([]);
      setProjects([]);
      setQueue(null);
      setJobs([]);
      setTools([]);
    } finally {
      setLoading(false);
    }
  }, []);

  const createTask = useCallback(async (taskData) => {
    setCreating(true);
    try {
      const result = await post("/dashboard/tickets", {
        task: taskData.task,
        description: taskData.description,
        priority: taskData.priority || "medium",
        type: "task",
        tags: ["human", "manual", ...(taskData.tags || [])],
        project_id: taskData.project_id,
        tool: "human",
      });
      await refresh();
      return result;
    } catch (e) {
      console.error("Failed to create human task:", e);
      throw e;
    } finally {
      setCreating(false);
    }
  }, [refresh]);

  const completeTask = useCallback(async (ticketId, resolution) => {
    try {
      await post(`/dashboard/tickets/${ticketId}/transition`, {
        status: "done",
        resolution: resolution || "Completed by human",
      });
      await refresh();
    } catch (e) {
      console.error("Failed to complete task:", e);
      throw e;
    }
  }, [refresh]);

  const addComment = useCallback(async (ticketId, content) => {
    try {
      await post(`/dashboard/tickets/${ticketId}/comments`, {
        content,
        author: "human",
      });
      await refresh();
    } catch (e) {
      console.error("Failed to add comment:", e);
      throw e;
    }
  }, [refresh]);

  useEffect(() => { refresh(); }, [refresh]);

  return { tasks, projects, sprints, queue, jobs, tools, loading, creating, refresh, createTask, completeTask, addComment };
}

function HumanTaskPanel() {
  const { tasks, projects, sprints, queue, jobs, tools, loading, refresh } = useHumanTasks();
  const [view, setView] = useState("board");
  const [filterStatus, setFilterStatus] = useState("");

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

  const boardColumns = useMemo(() => {
    const cols = {};
    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 humanJobs = useMemo(() => jobs.filter(job => _isHumanTicket(job.ticket) || job.tool === "human"), [jobs]);

  const stats = useMemo(() => ({
    total: tasks.length,
    inProgress: tasks.filter(t => t.status === "in_progress").length,
    pending: tasks.filter(t => t.status === "todo" || t.status === "backlog").length,
    done: tasks.filter(t => t.status === "done").length,
  }), [tasks]);

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

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="font-semibold text-gray-900">Human-in-the-Loop Tasks</h3>
          <p className="text-xs text-gray-500">Tasks requiring manual intervention or human decision</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={refresh}
            disabled={loading}
            className="px-3 py-1.5 bg-gray-100 text-gray-600 text-sm rounded hover:bg-gray-200 disabled:opacity-50"
          >
            {loading ? "↻" : "↻ Refresh"}
          </button>
        </div>
      </div>

      <QuickTaskCreator projects={projects} sprints={sprints} tools={tools} onCreated={refresh} defaultTool="human" />

      <div className="grid grid-cols-4 gap-2">
        <div className="bg-white rounded border p-2 text-center">
          <div className="text-lg font-bold text-gray-900">{stats.total}</div>
          <div className="text-xs text-gray-500">Total</div>
        </div>
        <div className="bg-white rounded border p-2 text-center">
          <div className="text-lg font-bold text-amber-600">
            {stats.inProgress}
          </div>
          <div className="text-xs text-gray-500">In Progress</div>
        </div>
        <div className="bg-white rounded border p-2 text-center">
          <div className="text-lg font-bold text-blue-600">
            {stats.pending}
          </div>
          <div className="text-xs text-gray-500">Pending</div>
        </div>
        <div className="bg-white rounded border p-2 text-center">
          <div className="text-lg font-bold text-emerald-600">
            {stats.done}
          </div>
          <div className="text-xs text-gray-500">Done</div>
        </div>
      </div>

      <QueueBar queue={queue} onStartStop={handleStartStop} />

      <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>
            <button onClick={() => setView("table")}
              className={`px-3 py-1 text-xs font-medium ${view === "table" ? "bg-blue-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50"}`}>
              Table
            </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>

      {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>
      )}

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

      {view === "table" && (
        <Card title={`Human Tasks Table (${filtered.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">Type</th>
                  <th className="py-2 px-3">Title</th>
                  <th className="py-2 px-3">Status</th>
                  <th className="py-2 px-3">Priority</th>
                  <th className="py-2 px-3">Tool</th>
                  <th className="py-2 px-3">Project</th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0 ? (
                  <tr>
                    <td colSpan="7" className="py-4 px-3 text-center text-gray-400">No human tasks found</td>
                  </tr>
                ) : (
                  filtered.map(t => (
                    <tr key={t.id} className="border-b border-gray-100 hover:bg-gray-50">
                      <td className="py-2 px-3 text-xs font-mono text-gray-400">{t.id?.slice(0, 10)}</td>
                      <td className="py-2 px-3">
                        <span className="text-sm">{TYPE_ICONS[t.type] || "📋"}</span>
                      </td>
                      <td className="py-2 px-3">
                        <div className="font-medium text-gray-900">{t.task || t.title}</div>
                        {t.description && (
                          <div className="text-xs text-gray-500 truncate max-w-[300px]">{t.description}</div>
                        )}
                      </td>
                      <td className="py-2 px-3">
                        <span className={`text-[11px] px-1.5 py-0.5 rounded-full ${STATUS_COLORS[t.status] || "bg-gray-100"}`}>
                          {t.status?.replace("_", " ")}
                        </span>
                      </td>
                      <td className="py-2 px-3">
                        <span className={`text-[11px] px-1.5 py-0.5 rounded-full ${PRIORITY_COLORS[t.priority] || "bg-gray-100"}`}>
                          {t.priority}
                        </span>
                      </td>
                      <td className="py-2 px-3 text-xs">
                        {t.assigned_tool ? (
                          <span className="px-1.5 py-0.5 bg-indigo-50 text-indigo-700 rounded">{t.assigned_tool.tool}</span>
                        ) : (
                          <span className="text-gray-400">—</span>
                        )}
                      </td>
                      <td className="py-2 px-3 text-xs text-gray-500">{t.project_id || "—"}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {humanJobs.length > 0 && (
        <Card title={`Recent Human Jobs (${humanJobs.length})`}>
          <div className="flex justify-between items-center mb-2">
            <span className="text-xs text-gray-500">Recent human-linked jobs ({humanJobs.length})</span>
            <TableExport
              data={humanJobs.map(job => ({
                id: job.id,
                ticket: job.ticket_id,
                ticket_title: job.ticket?.title || job.ticket?.task || '',
                ticket_status: job.ticket?.status || '',
                ticket_priority: job.ticket?.priority || '',
                ticket_type: job.ticket?.type || '',
                ticket_project_id: job.ticket?.project_id || '',
                ticket_assigned_tool: job.ticket?.assigned_tool?.tool || '',
                tool: job.tool,
                mode: job.mode || '',
                status: job.status,
                duration: job.duration_s > 0 ? `${job.duration_s}s` : '—',
                exit_code: job.result?.exit_code ?? '',
                stdout_lines: job.result?.stdout_lines ?? 0,
                stderr_lines: job.result?.stderr_lines ?? 0,
                stdout: job.result?.stdout || '',
                stderr: job.result?.stderr || '',
                files_changed: Array.isArray(job.result?.files_changed) ? job.result.files_changed.join(', ') : '',
                error: job.error || ''
              }))}
              filename="human_jobs"
              title="Human Jobs"
            />
          </div>
          <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>
                {humanJobs.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>
  );
}
