// TicketDispatchTableRefactored - Refactored dispatch table with separated concerns
import React, { useState, useEffect } from 'react';
import { get, post } from '../../api.js';
import DispatchTableHeader from './DispatchTableHeader';
import TicketStatusBadges from './TicketStatusBadges';
import ProjectInfoResolver from './ProjectInfoResolver';
import DispatchTableRow from './DispatchTableRow';
import ToolAvailabilityAlert from './ToolAvailabilityAlert';
import TableExport from './TableExport';

function TicketDispatchTableRefactored({ tools, onDispatch }) {
  // State management
  const [tickets, setTickets] = useState([]);
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [dispatching, setDispatching] = useState(null);

  // Computed values
  const availableTools = tools.filter(t => t.available);
  const unavailableTools = tools.filter(t => !t.available);
  const dispatchableTickets = tickets.filter(ticket => ticket.status !== "cancelled");

  // Helper instances
  const projectResolver = ProjectInfoResolver({ projects });

  // Load data
  useEffect(() => {
    const loadTickets = async () => {
      try {
        const data = await get("/dashboard/tickets");
        setTickets(data?.tickets || []);
      } catch (e) {
        console.error("Failed to load tickets:", e);
      } finally {
        setLoading(false);
      }
    };

    const loadProjects = async () => {
      try {
        const data = await get("/dashboard/projects");
        setProjects(Array.isArray(data) ? data : []);
      } catch (e) {
        console.error("Failed to load projects:", e);
      }
    };

    loadTickets();
    loadProjects();
  }, []);

  // Handle tool dispatch
  const handleToolSelect = async (ticketId, toolName, mode = "", projectDir = "") => {
    setDispatching(ticketId);
    try {
      await post("/dashboard/tools/dispatch", {
        ticket_id: ticketId,
        tool: toolName,
        mode: mode,
        project_dir: projectDir,
      });
      if (onDispatch) onDispatch();
    } catch (e) {
      console.error("Dispatch failed:", e);
    } finally {
      setDispatching(null);
    }
  };

  // Loading state
  if (loading) {
    return (
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <h3 className="text-sm font-semibold text-gray-700 mb-3">Dispatch Tool to Ticket</h3>
        <p className="text-sm text-gray-400">Loading tickets...</p>
      </div>
    );
  }

  // No tickets state
  if (dispatchableTickets.length === 0) {
    return (
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <h3 className="text-sm font-semibold text-gray-700 mb-3">Dispatch Tool to Ticket</h3>
        <p className="text-sm text-gray-400">No dispatchable tickets found. Create a non-cancelled ticket first to dispatch tools.</p>
      </div>
    );
  }

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      {/* Table Header */}
      <DispatchTableHeader
        dispatchableTickets={dispatchableTickets}
        getProjectInfo={projectResolver.getProjectInfo}
      />

      {/* Tool Availability Alert */}
      <ToolAvailabilityAlert
        availableTools={availableTools}
        unavailableTools={unavailableTools}
      />

      {/* Dispatch Table */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200 text-xs text-gray-500 uppercase">
              <th className="text-left py-2 px-3">Ticket</th>
              <th className="text-left py-2 px-3">Title</th>
              <th className="text-left py-2 px-3">Project</th>
              <th className="text-left py-2 px-3">Status</th>
              <th className="text-left py-2 px-3">Priority</th>
              <th className="text-left py-2 px-3">Current Tool</th>
              <th className="text-left py-2 px-3">Assign Tool</th>
            </tr>
          </thead>
          <tbody>
            {dispatchableTickets.map(ticket => (
              <DispatchTableRow
                key={ticket.id}
                ticket={ticket}
                tools={tools}
                projects={projects}
                isDispatching={dispatching}
                onToolSelect={handleToolSelect}
              />
            ))}
          </tbody>
        </table>
      </div>

      {/* Instructions */}
      <p className="text-xs text-gray-400 mt-3">
        Select a tool from the dropdown to dispatch it to the ticket. Unavailable tools are hidden, and tools with multiple modes will show mode options.
      </p>
    </div>
  );
}

export default TicketDispatchTableRefactored;
