// JobDetailsPanel — expanded view for a selected job with logs, repair results, metadata.

function JobDetailsPanel({ job, loading, error, onClose, onRetry, onRepair, repairResult }) {
  if (!job) return null;

  const result = job.result || null;
  const stdout = result?.stdout || "";
  const stderr = result?.stderr || "";
  const filesChanged = result?.files_changed || [];
  const isFailed = job.status === "failed";
  const ticketTitle = job.ticket?.title || job.ticket?.task || job.ticket_id || "—";
  const ticketStatus = job.ticket?.status || "—";
  const repairActionClass = {
    install: "bg-emerald-100 text-emerald-700",
    retry: "bg-amber-100 text-amber-700",
    start_container: "bg-blue-100 text-blue-700",
  };
  const execution = result?.execution || result?.execution_metadata || {};
  const promptExcerpt = job.prompt_excerpt || "";
  const projectDir = job.project_dir || "";
  const resultSuccess = result?.success;
  const isActiveJob = job.status === "queued" || job.status === "running";
  let resultLabel = "unknown";
  if (typeof resultSuccess === "boolean") {
    if (resultSuccess) {
      resultLabel = "success";
    } else if (isActiveJob) {
      resultLabel = "pending";
    } else {
      resultLabel = "failed";
    }
  } else if (isActiveJob) {
    resultLabel = "pending";
  }
  let resultLabelClass = "text-gray-500";
  if (resultLabel === "success") {
    resultLabelClass = "text-emerald-600";
  } else if (resultLabel === "failed") {
    resultLabelClass = "text-red-600";
  }
  const stdoutLines = result?.stdout_lines ?? 0;
  const stderrLines = result?.stderr_lines ?? 0;

  return (
    <div className="mt-4 rounded-xl border border-gray-200 bg-gray-50 p-4 space-y-4">
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="text-sm font-semibold text-gray-800">Job details</div>
          <div className="text-xs text-gray-500 font-mono mt-1">{job.id} · {job.tool} · {job.status}</div>
        </div>
        <div className="flex items-center gap-2">
          {isFailed && (
            <button
              type="button"
              onClick={() => onRetry?.(job)}
              className="text-xs px-3 py-1 rounded bg-amber-100 text-amber-700 hover:bg-amber-200 font-medium"
            >
              Retry Job
            </button>
          )}
          {isFailed && (
            <button
              type="button"
              onClick={() => onRepair?.(job)}
              className="text-xs px-3 py-1 rounded bg-purple-100 text-purple-700 hover:bg-purple-200 font-medium"
            >
              Auto-Repair
            </button>
          )}
          <button
            type="button"
            onClick={onClose}
            className="text-xs px-2 py-1 rounded bg-white border border-gray-200 text-gray-600 hover:bg-gray-100"
          >
            Close
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 text-xs">
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Ticket</div>
          <div className="font-medium text-gray-800 mt-1">{ticketTitle}</div>
          <div className="text-gray-500 mt-1 font-mono">{job.ticket_id}</div>
          <div className="text-gray-400 mt-1">{ticketStatus}</div>
        </div>
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Execution context</div>
          <div className="font-medium text-gray-800 mt-1 truncate" title={projectDir || ""}>
            {projectDir || "—"}
          </div>
          <div className="text-gray-400 mt-1">
            {job.mode || "—"}{job.model ? ` · ${job.model}` : ""}
          </div>
          {job.environment && (
            <div className="mt-2 space-y-1">
              <div className="text-gray-500">Environment: <span className="font-medium text-gray-800">{job.environment.name}</span></div>
              <div className="text-gray-400 truncate" title={job.environment.target || ""}>
                {job.environment.target || job.environment.kind || ""}
              </div>
              {(job.environment?.tool_instance_name || job.environment?.tool_instance?.name) && (
                <div className="mt-2 space-y-1">
                  <div className="text-gray-500">
                    Instance: <span className="font-medium text-gray-800">{job.environment.tool_instance_name || job.environment.tool_instance?.name}</span>
                  </div>
                  {job.environment.tool_instance?.kind && (
                    <div className="text-gray-400 truncate" title={job.environment.tool_instance.description || ""}>
                      {job.environment.tool_instance.kind}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
          <div className="text-gray-400 mt-1">Prompt: {job.prompt_length || 0} chars</div>
        </div>
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Execution result</div>
          <div className={`font-medium mt-1 ${resultLabelClass}`}>
            {resultLabel}
          </div>
          <div className="text-gray-400 mt-1">Exit code: {result?.exit_code ?? "—"}</div>
          <div className="text-gray-400 mt-1">stdout {stdoutLines} / stderr {stderrLines}</div>
        </div>
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Files changed</div>
          <div className="font-medium text-gray-800 mt-1">{filesChanged.length || 0}</div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 text-xs">
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Prompt excerpt</div>
          <p className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap font-mono text-[11px] leading-snug text-gray-700">
            {promptExcerpt || "—"}
          </p>
        </div>
        <div className="rounded-lg bg-white border border-gray-200 p-3">
          <div className="text-gray-400 uppercase">Execution metadata</div>
          {Object.keys(execution).length > 0 ? (
            <pre className="mt-2 max-h-40 overflow-auto rounded bg-gray-50 p-2 text-[11px] leading-snug text-gray-700 whitespace-pre-wrap">
              {JSON.stringify(execution, null, 2)}
            </pre>
          ) : (
            <div className="mt-2 text-gray-400">No execution metadata captured.</div>
          )}
        </div>
      </div>

      {loading && <p className="text-xs text-gray-500">Loading job logs...</p>}
      {error && <p className="text-xs text-red-600">{error}</p>}

      {/* Repair results panel */}
      {repairResult && (
        <div className="rounded-lg border border-purple-200 bg-purple-50 p-4 space-y-3">
          <div className="text-sm font-semibold text-purple-800 flex items-center gap-2">
            Auto-Repair Results
            {repairResult.error && <span className="text-xs text-red-500 font-normal">(error)</span>}
          </div>

          {repairResult.error && (
            <p className="text-xs text-red-600">{repairResult.error}</p>
          )}

          {repairResult.diagnosis && (
            <div>
              <div className="text-xs font-medium text-purple-700 mb-1">Diagnosis</div>
              <p className="text-xs text-gray-700 bg-white rounded p-2 border border-purple-100">
                {repairResult.diagnosis}
              </p>
            </div>
          )}

          {repairResult.suggestion && (
            <div>
              <div className="text-xs font-medium text-purple-700 mb-1">Suggestion</div>
              <p className="text-xs text-gray-700 bg-white rounded p-2 border border-purple-100">
                {repairResult.suggestion}
              </p>
            </div>
          )}

          {repairResult.quick_fixes && repairResult.quick_fixes.length > 0 && (
            <div>
              <div className="text-xs font-medium text-purple-700 mb-1">Quick Fixes</div>
              <div className="space-y-2">
                {repairResult.quick_fixes.map((fix) => (
                  <div key={fix.label} className="flex items-start gap-2 bg-white rounded p-2 border border-purple-100">
                    <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${repairActionClass[fix.action] || "bg-gray-100 text-gray-600"}`}>
                      {fix.action}
                    </span>
                    <div className="flex-1">
                      <div className="text-xs font-medium text-gray-800">{fix.label}</div>
                      <div className="text-xs text-gray-500">{fix.description}</div>
                      {fix.command && (
                        <pre className="mt-1 text-[11px] bg-gray-900 text-green-300 rounded px-2 py-1 font-mono overflow-x-auto">
                          {fix.command}
                        </pre>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      <div className="space-y-3">
        <div>
          <div className="text-xs font-medium text-gray-600 mb-1">stdout</div>
          <pre className="max-h-72 overflow-auto rounded-lg bg-gray-900 p-3 text-[11px] leading-tight text-green-300 whitespace-pre-wrap">
            {stdout || "No stdout captured for this job."}
          </pre>
        </div>
        <div>
          <div className="text-xs font-medium text-gray-600 mb-1">stderr</div>
          <pre className="max-h-48 overflow-auto rounded-lg bg-gray-900 p-3 text-[11px] leading-tight text-red-300 whitespace-pre-wrap">
            {stderr || "No stderr captured for this job."}
          </pre>
        </div>
      </div>
    </div>
  );
}
