// TasksPanelRefactored - Refactored tasks panel with separated concerns
import React, { useState, useMemo } from 'react';
import { post } from '../../api.js';
import Card from '../Card';
import TasksViewControls from './TasksViewControls';
import TasksBoard from './TasksBoard';
import TasksList from './TasksList';
import TasksTable from './TasksTable';
import TasksRecentJobs from './TasksRecentJobs';
import QuickTaskCreator from '../QuickTaskCreator';
import QueueBar from '../QueueBar';

function TasksPanelRefactored() {
  // Custom hook for data
  const { tickets, sprints, projects, queue, jobs, tools, loading, refresh } = useTasksData();
  
  // State management
  const [view, setView] = useState("board"); // board | list | table
  const [filterStatus, setFilterStatus] = useState("");

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

  const boardColumns = useMemo(() => {
    const cols = {};
    // Simplified board columns: Backlog, To Do, In Progress, Done, Failed
    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]);

  // 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);
  };

  // Loading state
  if (loading) {
    return <Card title="Tasks"><p className="text-gray-400 text-sm">Loading…</p></Card>;
  }

  return (
    <div className="space-y-4">
      {/* Quick Create - unified task creation for tools and human */}
      <QuickTaskCreator projects={projects} sprints={sprints} tools={tools} onCreated={refresh} />

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

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

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

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

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

      {/* Recent jobs table (collapsed) */}
      <TasksRecentJobs jobs={jobs} />
    </div>
  );
}

export default TasksPanelRefactored;
