// 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({
  viewMode, setViewMode,
  filterStatus: filterStatusProp, setFilterStatus: setFilterStatusProp,
  filterAgent: filterAgentProp, setFilterAgent: setFilterAgentProp,
  searchQuery: searchQueryProp, setSearchQuery: setSearchQueryProp,
}) {
  // Custom hook for data
  const { tickets, sprints, projects, queue, jobs, tools, loading, refresh } = useTasksData();
  
  // Use URL-backed props when available, fall back to local state
  const [localView, setLocalView] = useState("table");
  const [localFilterStatus, setLocalFilterStatus] = useState("");
  const [localFilterAgent, setLocalFilterAgent] = useState("");
  const [localSearchQuery, setLocalSearchQuery] = useState("");

  const view = viewMode || localView;
  const setView = setViewMode || setLocalView;
  const filterStatus = filterStatusProp !== undefined ? filterStatusProp : localFilterStatus;
  const setFilterStatus = setFilterStatusProp || setLocalFilterStatus;
  const filterAgent = filterAgentProp !== undefined ? filterAgentProp : localFilterAgent;
  const setFilterAgent = setFilterAgentProp || setLocalFilterAgent;
  const searchQuery = searchQueryProp !== undefined ? searchQueryProp : localSearchQuery;
  const setSearchQuery = setSearchQueryProp || setLocalSearchQuery;

  // Computed values
  const filtered = useMemo(() => {
    let result = tickets;
    if (filterAgent === "human") result = result.filter(t => t?.assigned_tool?.tool === "human");
    else if (filterAgent === "auto") result = result.filter(t => t?.assigned_tool?.tool !== "human");
    if (filterStatus) result = result.filter(t => t.status === filterStatus);
    if (searchQuery && searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter(t => (
        (t.task || "").toLowerCase().includes(q)
        || (t.title || "").toLowerCase().includes(q)
        || (t.description || "").toLowerCase().includes(q)
        || (t.id || "").toLowerCase().includes(q)
        || (t.sprint_name || "").toLowerCase().includes(q)
        || (t.milestone_name || "").toLowerCase().includes(q)
        || (t.tags || []).some(tag => String(tag).toLowerCase().includes(q))
      ));
    }
    return result;
  }, [tickets, filterStatus, filterAgent, searchQuery]);

  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]);

  // 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}
        filterAgent={filterAgent}
        searchQuery={searchQuery}
        filteredCount={filtered.length}
        onViewChange={handleViewChange}
        onFilterChange={handleFilterChange}
        onFilterAgentChange={setFilterAgent}
        onSearchChange={setSearchQuery}
        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} tools={tools} projects={projects} onRefresh={refresh} />
      )}

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

export default TasksPanelRefactored;
