// 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;

function useHumanTasks() {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      // Get tickets tagged with 'human' or 'human-required'
      const data = await get("/dashboard/tickets");
      const allTickets = data?.tickets || [];
      // Filter human-related tickets
      const humanTasks = allTickets.filter(t =>
        t.tags?.some(tag =>
          tag.includes("human") || tag.includes("autofix") || tag.includes("manual")
        ) || t.type === "human" || t.assigned_tool?.tool === "human"
      );
      setTasks(humanTasks);
    } catch (e) {
      console.error("Failed to load human tasks:", e);
      setTasks([]);
    } 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: "human",
        tags: ["human", "manual", ...(taskData.tags || [])],
        project_id: taskData.project_id,
      });
      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, loading, creating, refresh, createTask, completeTask, addComment };
}

function HumanTaskPanel() {
  const { tasks, loading, creating, refresh, createTask, completeTask, addComment } = useHumanTasks();
  const [showCreate, setShowCreate] = useState(false);
  const [form, setForm] = useState({ task: "", description: "", priority: "medium" });
  const [expandedTask, setExpandedTask] = useState(null);

  const handleCreate = async (e) => {
    e.preventDefault();
    if (!form.task.trim()) return;
    try {
      await createTask(form);
      setForm({ task: "", description: "", priority: "medium" });
      setShowCreate(false);
    } catch (err) {
      alert("Failed to create task: " + (err?.message || "Unknown error"));
    }
  };

  const handleComplete = async (task) => {
    const resolution = prompt(`Complete task "${task.task}"?\nEnter resolution (optional):`);
    if (resolution === null) return; // cancelled
    try {
      await completeTask(task.id, resolution || "Completed");
    } catch (err) {
      alert("Failed to complete: " + (err?.message || "Unknown error"));
    }
  };

  const priorityColor = {
    critical: "bg-red-100 text-red-700",
    high: "bg-orange-100 text-orange-700",
    medium: "bg-blue-100 text-blue-700",
    low: "bg-gray-100 text-gray-600",
  };

  const statusColor = {
    backlog: "bg-gray-100 text-gray-600",
    todo: "bg-blue-100 text-blue-700",
    in_progress: "bg-amber-100 text-amber-700",
    in_review: "bg-purple-100 text-purple-700",
    done: "bg-emerald-100 text-emerald-700",
    cancelled: "bg-gray-100 text-gray-400",
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <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>
          <button
            onClick={() => setShowCreate(!showCreate)}
            className="px-3 py-1.5 bg-purple-600 text-white text-sm rounded hover:bg-purple-700"
          >
            {showCreate ? "Cancel" : "+ New Task"}
          </button>
        </div>
      </div>

      {/* Stats */}
      <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">{tasks.length}</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">
            {tasks.filter(t => t.status === "in_progress").length}
          </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">
            {tasks.filter(t => t.status === "todo" || t.status === "backlog").length}
          </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">
            {tasks.filter(t => t.status === "done").length}
          </div>
          <div className="text-xs text-gray-500">Done</div>
        </div>
      </div>

      {/* Create form */}
      {showCreate && (
        <form onSubmit={handleCreate} className="bg-purple-50 rounded-lg border border-purple-200 p-4 space-y-3">
          <h4 className="font-medium text-purple-900">Create Human Task</h4>
          <input
            className="w-full px-3 py-2 border rounded text-sm"
            placeholder="Task title *"
            value={form.task}
            onChange={e => setForm(prev => ({ ...prev, task: e.target.value }))}
            required
          />
          <textarea
            className="w-full px-3 py-2 border rounded text-sm"
            placeholder="Description (optional)"
            rows={3}
            value={form.description}
            onChange={e => setForm(prev => ({ ...prev, description: e.target.value }))}
          />
          <select
            className="w-full px-3 py-2 border rounded text-sm"
            value={form.priority}
            onChange={e => setForm(prev => ({ ...prev, priority: e.target.value }))}
          >
            <option value="critical">Critical</option>
            <option value="high">High</option>
            <option value="medium">Medium</option>
            <option value="low">Low</option>
          </select>
          <div className="flex gap-2">
            <button
              type="submit"
              disabled={creating}
              className="px-4 py-2 bg-purple-600 text-white text-sm rounded hover:bg-purple-700 disabled:opacity-50"
            >
              {creating ? "Creating..." : "Create Task"}
            </button>
            <button
              type="button"
              onClick={() => setShowCreate(false)}
              className="px-4 py-2 bg-gray-100 text-gray-700 text-sm rounded hover:bg-gray-200"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      {/* Task list */}
      {tasks.length === 0 ? (
        <div className="text-center py-8 bg-gray-50 rounded-lg border border-gray-200">
          <p className="text-gray-500 text-sm mb-2">No human tasks found.</p>
          <p className="text-gray-400 text-xs">Create a task manually or wait for auto-diagnostic to create one.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {tasks.map(task => (
            <div
              key={task.id}
              className={`bg-white rounded-lg border p-3 hover:shadow-sm transition-shadow ${
                task.status === "done" ? "border-gray-200 opacity-75" : "border-gray-200"
              }`}
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-medium text-sm text-gray-900 truncate">{task.task}</span>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${priorityColor[task.priority] || priorityColor.medium}`}>
                      {task.priority}
                    </span>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${statusColor[task.status] || statusColor.backlog}`}>
                      {task.status}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 mt-1">ID: {task.id}</div>
                  {task.description && (
                    <div className="text-xs text-gray-600 mt-2 line-clamp-2">{task.description}</div>
                  )}
                  {task.tags?.length > 0 && (
                    <div className="flex items-center gap-1 mt-2 flex-wrap">
                      {task.tags.map(tag => (
                        <span key={tag} className="text-[10px] px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded">
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-1 ml-2">
                  {task.status !== "done" && task.status !== "cancelled" && (
                    <button
                      onClick={() => handleComplete(task)}
                      className="px-2 py-1 bg-emerald-600 text-white text-xs rounded hover:bg-emerald-700"
                      title="Mark as complete"
                    >
                      ✓
                    </button>
                  )}
                  <button
                    onClick={() => setExpandedTask(expandedTask === task.id ? null : task.id)}
                    className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded hover:bg-gray-200"
                  >
                    {expandedTask === task.id ? "−" : "+"}
                  </button>
                </div>
              </div>

              {/* Expanded details */}
              {expandedTask === task.id && (
                <div className="mt-3 pt-3 border-t border-gray-100 space-y-2">
                  {task.comments?.length > 0 && (
                    <div className="space-y-1">
                      <div className="text-xs font-medium text-gray-700">Comments:</div>
                      {task.comments.map((comment, i) => (
                        <div key={i} className="text-xs bg-gray-50 rounded px-2 py-1">
                          <span className="text-gray-500">{comment.author}:</span>{" "}
                          <span className="text-gray-700">{comment.content}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        const content = prompt("Add comment:");
                        if (content) addComment(task.id, content);
                      }}
                      className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200"
                    >
                      Add Comment
                    </button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
