// HumanTaskPanelRefactored - Refactored human task panel with separated concerns
import React, { useState, useMemo } from 'react';
import { post } from '../../api.js';
import Card from '../Card';
import HumanTaskStats from './HumanTaskStats';
import HumanTaskBoard from './HumanTaskBoard';
import HumanTaskList from './HumanTaskList';
import HumanTaskTable from './HumanTaskTable';
import HumanJobsList from './HumanJobsList';
import HumanViewControls from './HumanViewControls';
import QuickTaskCreator from '../QuickTaskCreator';
import QueueBar from '../QueueBar';

function HumanTaskPanelRefactored() {
  // Custom hook for data
  const { tasks, projects, sprints, queue, jobs, tools, loading, refresh } = useHumanTasks();
  
  // State management
  const [view, setView] = useState("board");
  const [filterStatus, setFilterStatus] = useState("");

  // Computed values
  const filtered = useMemo(() => {
    if (!filterStatus) return tasks;
    return tasks.filter(t => t.status === filterStatus);
  }, [tasks, filterStatus]);

  const boardColumns = useMemo(() => {
    const cols = {};
    const boardStatuses = ["backlog", "todo", "in_progress", "in_review", "done", "cancelled"];
    boardStatuses.forEach(s => { cols[s] = []; });
    filtered.forEach(t => {
      if (cols[t.status]) cols[t.status].push(t);
    });
    return cols;
  }, [filtered]);

  const humanJobs = useMemo(() => 
    jobs.filter(job => _isHumanTicket(job.ticket) || job.tool === "human"), 
    [jobs]
  );

  const stats = useMemo(() => ({
    total: tasks.length,
    inProgress: tasks.filter(t => t.status === "in_progress").length,
    pending: tasks.filter(t => t.status === "todo" || t.status === "backlog").length,
    done: tasks.filter(t => t.status === "done").length,
  }), [tasks]);

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

  const handleViewChange = (newView) => {
    setView(newView);
  };

  const handleFilterChange = (newStatus) => {
    setFilterStatus(newStatus);
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="font-semibold text-gray-900">Human-in-the-Loop Tasks</h3>
          <p className="text-xs text-gray-500">Tasks requiring manual intervention or human decision</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={refresh}
            disabled={loading}
            className="px-3 py-1.5 bg-gray-100 text-gray-600 text-sm rounded hover:bg-gray-200 disabled:opacity-50"
          >
            {loading ? "↻" : "↻ Refresh"}
          </button>
        </div>
      </div>

      {/* Quick Task Creator */}
      <QuickTaskCreator 
        projects={projects} 
        sprints={sprints} 
        tools={tools} 
        onCreated={refresh} 
        defaultTool="human" 
      />

      {/* Statistics */}
      <HumanTaskStats stats={stats} />

      {/* Queue Bar */}
      <QueueBar queue={queue} onStartStop={handleStartStop} />

      {/* View Controls */}
      <HumanViewControls
        view={view}
        filterStatus={filterStatus}
        filteredCount={filtered.length}
        onViewChange={handleViewChange}
        onFilterChange={handleFilterChange}
        onRefresh={refresh}
      />

      {/* Content Views */}
      {view === "board" && (
        <HumanTaskBoard 
          boardColumns={boardColumns} 
          jobs={jobs} 
          onRefresh={refresh} 
        />
      )}

      {view === "list" && (
        <HumanTaskList 
          filteredTasks={filtered} 
          jobs={jobs} 
          onRefresh={refresh} 
        />
      )}

      {view === "table" && (
        <HumanTaskTable filteredTasks={filtered} />
      )}

      {/* Human Jobs */}
      <HumanJobsList humanJobs={humanJobs} />
    </div>
  );
}

// Helper function (should be moved to utils)
function _isHumanTicket(ticket) {
  return ticket?.assigned_tool?.tool === "human" || ticket?.type === "human";
}

export default HumanTaskPanelRefactored;
