// BulkOperations - Extracted bulk operations from TicketsPanel
import React, { useState, useCallback } from 'react';
import { post, put, delete_ } from '../../api.js';

const TOOLS = ["vscode", "aider", "claude-code", "windsurf", "cursor", "roo-code", "continue", "copilot", "human"];
const TICKET_STATUSES = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"];

function BulkOperations({ 
  selectedTickets, 
  setSelectedTickets, 
  onRefresh,
  tickets 
}) {
  const [bulkAction, setBulkAction] = useState("");
  const [bulkTool, setBulkTool] = useState("");
  const [bulkStatus, setBulkStatus] = useState("");
  const [loading, setLoading] = useState(false);

  const toggleTicketSelection = useCallback((ticketId) => {
    const newSet = new Set(selectedTickets);
    if (newSet.has(ticketId)) {
      newSet.delete(ticketId);
    } else {
      newSet.add(ticketId);
    }
    setSelectedTickets(newSet);
  }, [selectedTickets, setSelectedTickets]);

  const selectAllTickets = useCallback(() => {
    setSelectedTickets(new Set(tickets.map(t => t.id)));
  }, [tickets, setSelectedTickets]);

  const clearSelection = useCallback(() => {
    setSelectedTickets(new Set());
  }, [setSelectedTickets]);

  const executeBulkAction = useCallback(async () => {
    if (!bulkAction || selectedTickets.size === 0) return;
    
    setLoading(true);
    try {
      const ids = Array.from(selectedTickets);
      
      switch (bulkAction) {
        case "status":
          if (!bulkStatus) return;
          await Promise.all(
            ids.map(id => put(`/dashboard/tickets/${id}`, { status: bulkStatus }))
          );
          break;
          
        case "assign":
          if (!bulkTool) return;
          await Promise.all(
            ids.map(id => post(`/dashboard/tickets/${id}/assign`, { tool: bulkTool }))
          );
          break;
          
        case "delete":
          await Promise.all(
            ids.map(id => delete_(`/dashboard/tickets/${id}`))
          );
          break;
      }
      
      clearSelection();
      await onRefresh();
    } catch (error) {
      console.error("Bulk action failed:", error);
    } finally {
      setLoading(false);
    }
  }, [bulkAction, bulkStatus, bulkTool, selectedTickets, onRefresh, clearSelection]);

  if (selectedTickets.size === 0) {
    return null;
  }

  return (
    <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <span className="text-sm font-medium text-amber-800">
            {selectedTickets.size} tickets selected
          </span>
          
          <div className="flex space-x-2">
            <button
              onClick={selectAllTickets}
              className="text-xs text-amber-600 hover:text-amber-800"
            >
              Select All
            </button>
            <button
              onClick={clearSelection}
              className="text-xs text-amber-600 hover:text-amber-800"
            >
              Clear Selection
            </button>
          </div>
        </div>

        <div className="flex items-center space-x-3">
          {/* Action selector */}
          <select
            value={bulkAction}
            onChange={(e) => setBulkAction(e.target.value)}
            className="px-3 py-1 border rounded text-sm"
          >
            <option value="">Choose action...</option>
            <option value="status">Change Status</option>
            <option value="assign">Assign Tool</option>
            <option value="delete">Delete</option>
          </select>

          {/* Conditional inputs */}
          {bulkAction === "status" && (
            <select
              value={bulkStatus}
              onChange={(e) => setBulkStatus(e.target.value)}
              className="px-3 py-1 border rounded text-sm"
            >
              <option value="">Select status...</option>
              {TICKET_STATUSES.map(s => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          )}

          {bulkAction === "assign" && (
            <select
              value={bulkTool}
              onChange={(e) => setBulkTool(e.target.value)}
              className="px-3 py-1 border rounded text-sm"
            >
              <option value="">Select tool...</option>
              {TOOLS.map(t => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>
          )}

          {/* Execute button */}
          <button
            onClick={executeBulkAction}
            disabled={loading || !bulkAction || (bulkAction === "status" && !bulkStatus) || (bulkAction === "assign" && !bulkTool)}
            className="px-4 py-1 bg-amber-600 text-white rounded text-sm hover:bg-amber-700 disabled:opacity-50"
          >
            {loading ? "Executing..." : "Execute"}
          </button>
        </div>
      </div>
    </div>
  );
}

export default BulkOperations;
