// TicketsPanelRefactored - Split version with reduced complexity
import React, { useState, useCallback, useEffect } from 'react';
import { get } from '../../api.js';
import TicketFilters from './TicketFilters';
import TicketStats from './TicketStats';
import TicketList from './TicketList';
import BulkOperations from './BulkOperations';

// Extracted filtering logic
function useTicketFilters(tickets, selectedMilestone, selectedSprint, filterStatus, filterTool, filterPriority, searchQuery, sortBy, sortOrder) {
  return React.useMemo(() => {
    let result = tickets;
    
    // Apply filters
    if (selectedMilestone) result = result.filter(t => t.milestone_id === selectedMilestone);
    if (selectedSprint) result = result.filter(t => t.sprint_id === selectedSprint);
    if (filterStatus) result = result.filter(t => t.status === filterStatus);
    if (filterTool) result = result.filter(t => t.assigned_tool?.tool === filterTool);
    if (filterPriority) result = result.filter(t => t.priority === filterPriority);
    
    // Search filter
    if (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.tags || []).some(tag => tag.toLowerCase().includes(q)) ||
        (t.id || "").toLowerCase().includes(q)
      );
    }
    
    // Sorting
    const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
    const statusOrder = { in_progress: 0, todo: 1, in_review: 2, backlog: 3, done: 4, cancelled: 5 };
    
    result = [...result].sort((a, b) => {
      let comparison = 0;
      switch (sortBy) {
        case "priority":
          comparison = (priorityOrder[a.priority] || 99) - (priorityOrder[b.priority] || 99);
          break;
        case "status":
          comparison = (statusOrder[a.status] || 99) - (statusOrder[b.status] || 99);
          break;
        case "updated":
          comparison = (b.updated_at || 0) - (a.updated_at || 0);
          break;
        case "created":
        default:
          comparison = (b.created_at || 0) - (a.created_at || 0);
          break;
      }
      return sortOrder === "asc" ? -comparison : comparison;
    });
    
    return result;
  }, [tickets, selectedMilestone, selectedSprint, filterStatus, filterTool, filterPriority, searchQuery, sortBy, sortOrder]);
}

// Extracted statistics calculation
function useTicketStats(filtered) {
  const TOOLS = ["vscode", "aider", "claude-code", "windsurf", "cursor", "roo-code", "continue", "copilot", "human"];
  
  return React.useMemo(() => ({
    total: filtered.length,
    todo: filtered.filter(t => t.status === "todo").length,
    in_progress: filtered.filter(t => t.status === "in_progress").length,
    done: filtered.filter(t => t.status === "done").length,
    by_tool: TOOLS.reduce((acc, tool) => {
      const count = filtered.filter(t => t.assigned_tool?.tool === tool).length;
      if (count > 0) acc[tool] = count;
      return acc;
    }, {}),
  }), [filtered]);
}

// Extracted data hook
function useTicketsData() {
  const [tickets, setTickets] = useState([]);
  const [sprints, setSprints] = useState([]);
  const [milestones, setMilestones] = useState([]);
  const [loading, setLoading] = useState(true);

  const refreshTickets = useCallback(async () => {
    const data = await get("/dashboard/tickets");
    setTickets(data?.tickets || []);
  }, []);

  const refreshSprints = useCallback(async () => {
    const data = await get("/dashboard/sprints");
    setSprints(data?.sprints || []);
  }, []);

  const refreshMilestones = useCallback(async () => {
    const data = await get("/dashboard/milestones");
    setMilestones(data?.milestones || []);
  }, []);

  const refresh = useCallback(async () => {
    setLoading(true);
    await Promise.all([refreshTickets(), refreshSprints(), refreshMilestones()]);
    setLoading(false);
  }, [refreshTickets, refreshSprints, refreshMilestones]);

  useEffect(() => { refresh(); }, [refresh]);

  return { tickets, sprints, milestones, loading, refresh, refreshTickets, refreshSprints, refreshMilestones };
}

// Main component - reduced complexity
function TicketsPanelRefactored({ selectedTicket, setSelectedTicket }) {
  // Data fetching
  const { tickets, sprints, milestones, loading, refresh } = useTicketsData();
  
  // Filter state
  const [selectedMilestone, setSelectedMilestone] = useState(null);
  const [selectedSprint, setSelectedSprint] = useState(null);
  const [filterStatus, setFilterStatus] = useState("");
  const [filterTool, setFilterTool] = useState("");
  const [filterPriority, setFilterPriority] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("created");
  const [sortOrder, setSortOrder] = useState("desc");
  
  // Bulk operations state
  const [selectedTickets, setSelectedTickets] = useState(new Set());
  
  // Computed values
  const filtered = useTicketFilters(tickets, selectedMilestone, selectedSprint, filterStatus, filterTool, filterPriority, searchQuery, sortBy, sortOrder);
  const stats = useTicketStats(filtered);
  
  // Handlers
  const handleRefresh = useCallback(async () => {
    await refresh();
    if (selectedTicket) {
      // Reload selected ticket details if needed
    }
  }, [refresh, selectedTicket]);

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

  const visibleSprints = React.useMemo(() => {
    return sprints.filter(s => !selectedMilestone || s.milestone_id === selectedMilestone);
  }, [sprints, selectedMilestone]);

  if (loading) {
    return <div className="bg-white rounded-lg border p-8 text-center"><p className="text-gray-500">Loading...</p></div>;
  }

  return (
    <div className="space-y-6">
      {/* Statistics */}
      <TicketStats stats={stats} />
      
      {/* Filters */}
      <TicketFilters
        selectedMilestone={selectedMilestone}
        setSelectedMilestone={setSelectedMilestone}
        selectedSprint={selectedSprint}
        setSelectedSprint={setSelectedSprint}
        filterStatus={filterStatus}
        setFilterStatus={setFilterStatus}
        filterTool={filterTool}
        setFilterTool={setFilterTool}
        filterPriority={filterPriority}
        setFilterPriority={setFilterPriority}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        sortBy={sortBy}
        setSortBy={setSortBy}
        sortOrder={sortOrder}
        setSortOrder={setSortOrder}
        milestones={milestones}
        sprints={sprints}
      />
      
      {/* Bulk Operations */}
      <BulkOperations
        selectedTickets={selectedTickets}
        setSelectedTickets={setSelectedTickets}
        onRefresh={handleRefresh}
        tickets={filtered}
      />
      
      {/* Ticket List */}
      <TicketList
        filtered={filtered}
        selectedTicket={selectedTicket}
        setSelectedTicket={setSelectedTicket}
        selectedTickets={selectedTickets}
        toggleTicketSelection={toggleTicketSelection}
        handleRefresh={handleRefresh}
        visibleSprints={visibleSprints}
      />
    </div>
  );
}

export default TicketsPanelRefactored;
