// EditableTicketTable — reusable ticket/task table with inline-editable
// Status, Priority, Tool, and Project columns via <select> dropdowns.
// Used by: TasksTable, HumanTaskTable, and any future table view.
//
// Props:
//   tickets       — array of ticket objects to render
//   tools         — array of tool objects (for tool select; optional)
//   projects      — array of project objects (for project select; optional)
//   jobs          — array of job objects (optional, for dispatch button)
//   onRefresh     — callback after any inline edit
//   title         — card title (default: "Tasks Table")
//   emptyMessage  — message when no tickets (default: "No tasks found")
//   showSelect    — show selection checkboxes (default: false)
//   selectedIds   — Set of selected ticket IDs
//   onToggleSelect — callback(ticketId) for checkbox toggle

function EditableTicketTable({
  tickets = [],
  tools = [],
  projects = [],
  jobs = [],
  onRefresh,
  title,
  emptyMessage = "No tasks found",
  showSelect = false,
  selectedIds,
  onToggleSelect,
}) {
  const cardTitle = title || `Tasks Table (${tickets.length})`;
  const editable = typeof onRefresh === "function";

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

  const handlePriorityChange = async (ticket, newPriority) => {
    await put(`/dashboard/tickets/${ticket.id}`, { priority: newPriority });
    if (onRefresh) onRefresh();
  };

  const handleToolChange = async (ticket, toolName) => {
    if (toolName) {
      await post(`/dashboard/tickets/${ticket.id}/assign`, { tool: toolName });
    } else {
      await put(`/dashboard/tickets/${ticket.id}`, { assigned_tool: null });
    }
    if (onRefresh) onRefresh();
  };

  const handleProjectChange = async (ticket, projectId) => {
    await put(`/dashboard/tickets/${ticket.id}`, { project_id: projectId || "" });
    if (onRefresh) onRefresh();
  };

  const colCount = 7 + (showSelect ? 1 : 0);

  return (
    <Card title={cardTitle}>
      <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">
              {showSelect && <th className="py-2 px-3 w-12">Select</th>}
              <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>
            {tickets.length === 0 ? (
              <tr>
                <td colSpan={colCount} className="py-4 px-3 text-center text-gray-400">
                  {emptyMessage}
                </td>
              </tr>
            ) : (
              tickets.map(t => {
                const isSelected = selectedIds && selectedIds.has(t.id);
                return (
                  <tr
                    key={t.id}
                    className={`border-b border-gray-100 hover:bg-gray-50 ${isSelected ? "bg-blue-50" : ""}`}
                  >
                    {showSelect && (
                      <td className="py-2 px-3">
                        <input
                          type="checkbox"
                          checked={!!isSelected}
                          onChange={() => onToggleSelect && onToggleSelect(t.id)}
                          className="rounded border-gray-300"
                          aria-label={`Select ticket ${t.id}`}
                        />
                      </td>
                    )}
                    <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>

                    {/* Status — editable select */}
                    <td className="py-2 px-3">
                      {editable ? (
                        <select
                          value={t.status}
                          onChange={(e) => { e.stopPropagation(); handleStatusChange(t, e.target.value); }}
                          onClick={(e) => e.stopPropagation()}
                          className={`text-[11px] px-1.5 py-0.5 rounded-full border-0 cursor-pointer ${STATUS_COLORS[t.status] || "bg-gray-100"}`}
                        >
                          {TICKET_STATUSES.map(s => (
                            <option key={s} value={s}>{s.replace("_", " ")}</option>
                          ))}
                        </select>
                      ) : (
                        <span className={`text-[11px] px-1.5 py-0.5 rounded-full ${STATUS_COLORS[t.status] || "bg-gray-100"}`}>
                          {t.status?.replace("_", " ")}
                        </span>
                      )}
                    </td>

                    {/* Priority — editable select */}
                    <td className="py-2 px-3">
                      {editable ? (
                        <select
                          value={t.priority}
                          onChange={(e) => { e.stopPropagation(); handlePriorityChange(t, e.target.value); }}
                          onClick={(e) => e.stopPropagation()}
                          className={`text-[11px] px-1.5 py-0.5 rounded-full border-0 cursor-pointer ${PRIORITY_COLORS[t.priority] || "bg-gray-100"}`}
                        >
                          {TICKET_PRIORITIES.map(p => (
                            <option key={p} value={p}>{p}</option>
                          ))}
                        </select>
                      ) : (
                        <span className={`text-[11px] px-1.5 py-0.5 rounded-full ${PRIORITY_COLORS[t.priority] || "bg-gray-100"}`}>
                          {t.priority}
                        </span>
                      )}
                    </td>

                    {/* Tool — editable select */}
                    <td className="py-2 px-3 text-xs">
                      {editable ? (
                        <select
                          value={t.assigned_tool?.tool || ""}
                          onChange={(e) => { e.stopPropagation(); handleToolChange(t, e.target.value); }}
                          onClick={(e) => e.stopPropagation()}
                          className="text-[11px] px-1.5 py-0.5 rounded border-0 cursor-pointer bg-indigo-50 text-indigo-700"
                        >
                          <option value="">— none —</option>
                          {tools.map(tool => (
                            <option key={tool.name} value={tool.name}>{tool.name}</option>
                          ))}
                          {!tools.some(tool => tool.name === "human") && (
                            <option value="human">human</option>
                          )}
                        </select>
                      ) : (
                        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>

                    {/* Project — editable select */}
                    <td className="py-2 px-3 text-xs">
                      {editable && projects.length > 0 ? (
                        <select
                          value={t.project_id || ""}
                          onChange={(e) => { e.stopPropagation(); handleProjectChange(t, e.target.value); }}
                          onClick={(e) => e.stopPropagation()}
                          className="text-[11px] px-1.5 py-0.5 rounded border-0 cursor-pointer bg-gray-50 text-gray-600"
                        >
                          <option value="">— no project —</option>
                          {projects.map(p => (
                            <option key={p.id} value={p.id}>{p.name || p.id}</option>
                          ))}
                        </select>
                      ) : (
                        <span className="text-gray-500">{t.project_id || "—"}</span>
                      )}
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </Card>
  );
}
