// ToolsJobQueue - Component for managing job queue and displaying jobs
import React, { useState, useCallback } from 'react';
import { post, get } from '../../api.js';
import Card from '../Card';
import QueueSummary from '../QueueSummary';
import TableExport from './TableExport';
import JobRow from './JobRow';
import JobDetailsPanel from './JobDetailsPanel';

function ToolsJobQueue({ queue, jobs, onRefresh }) {
  // State management
  const [selectedJobId, setSelectedJobId] = useState(null);
  const [selectedJob, setSelectedJob] = useState(null);
  const [selectedJobLoading, setSelectedJobLoading] = useState(false);
  const [selectedJobError, setSelectedJobError] = useState("");
  const [repairResult, setRepairResult] = useState(null);

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

  const handleRetryJob = useCallback(async (job) => {
    try {
      await post(`/dashboard/tools/queue/jobs/${job.id}/retry`, {});
      setRepairResult(null);
      setTimeout(() => onRefresh(), 500);
    } catch (e) {
      console.error("Retry failed:", e);
    }
  }, [onRefresh]);

  const handleRepairJob = useCallback(async (job) => {
    setRepairResult(null);
    try {
      const data = await post(`/dashboard/tools/queue/jobs/${job.id}/repair`, {});
      setRepairResult(data);
      // Auto-select this job to show repair results
      if (selectedJobId !== job.id) {
        setSelectedJobId(job.id);
        setSelectedJob(job);
        try {
          const details = await get(`/dashboard/tools/queue/jobs/${job.id}`);
          setSelectedJob(details);
        } catch (_) { /* keep current job data */ }
      }
    } catch (e) {
      setRepairResult({ error: `Repair request failed: ${e.message || e}` });
    }
  }, [selectedJobId]);

  const handleSelectJob = useCallback(async (job) => {
    if (!job) return;
    if (selectedJobId === job.id) {
      setSelectedJobId(null);
      setSelectedJob(null);
      setSelectedJobError("");
      setRepairResult(null);
      return;
    }

    setSelectedJobId(job.id);
    setSelectedJob(job);
    setSelectedJobLoading(true);
    setSelectedJobError("");
    setRepairResult(null);

    try {
      const data = await get(`/dashboard/tools/queue/jobs/${job.id}`);
      setSelectedJob(data);
    } catch (e) {
      console.error("Failed to load job details:", e);
      setSelectedJobError("Nie udało się pobrać logów joba.");
    } finally {
      setSelectedJobLoading(false);
    }
  }, [selectedJobId]);

  const handleCloseJobDetails = () => {
    setSelectedJobId(null);
    setSelectedJob(null);
    setSelectedJobError("");
    setRepairResult(null);
  };

  return (
    <Card title="Job Queue">
      <QueueSummary queue={queue} onStartStop={handleStartStop} />
      {jobs.length > 0 ? (
        <div className="mt-3">
          <div className="flex justify-between items-center mb-2">
            <span className="text-xs text-gray-500">Recent jobs ({jobs.length})</span>
            <TableExport 
              data={jobs.map(job => ({
                ...job,
                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 || '',
                ticket_assigned_mode: job.ticket?.assigned_tool?.agent_mode || '',
                ticket_assigned_model: job.ticket?.assigned_tool?.model || '',
                result_success: job.result?.success ?? null,
                result_exit_code: job.result?.exit_code ?? null,
                result_duration_s: job.result?.duration_s ?? null,
                result_stdout_lines: job.result?.stdout_lines ?? 0,
                result_stderr_lines: job.result?.stderr_lines ?? 0,
                result_stdout: job.result?.stdout || '',
                result_stderr: job.result?.stderr || '',
                result_files_changed: Array.isArray(job.result?.files_changed) ? job.result.files_changed.join(', ') : '',
              }))}
              filename="job_queue"
              title="Job Queue"
            />
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <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">Mode</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>
                  <th className="py-2 px-3">Logs</th>
                  <th className="py-2 px-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                {jobs.map(j => (
                  <JobRow
                    key={j.id}
                    job={j}
                    onClick={handleSelectJob}
                    isSelected={selectedJobId === j.id}
                    onRetry={handleRetryJob}
                    onRepair={handleRepairJob}
                  />
                ))}
              </tbody>
            </table>
          </div>
          <JobDetailsPanel
            job={selectedJob}
            loading={selectedJobLoading}
            error={selectedJobError}
            onClose={handleCloseJobDetails}
            onRetry={handleRetryJob}
            onRepair={handleRepairJob}
            repairResult={repairResult}
          />
        </div>
      ) : (
        <p className="mt-3 text-sm text-gray-400">No jobs yet. Dispatch a tool to a ticket to start.</p>
      )}
    </Card>
  );
}

export default ToolsJobQueue;
