/**
 * Tasks Page - Built with TablePageTemplate
 * Consistent with Keywords page layout, structure and design
 */

import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import TablePageTemplate from '../../templates/TablePageTemplate';
import {
  fetchTasks,
  createTask,
  updateTask,
  deleteTask,
  bulkDeleteTasks,
  bulkUpdateTasksStatus,
  autoGenerateContent,
  autoGenerateImages,
  Task,
  TasksFilters,
  TaskCreateData,
  fetchClusters,
  Cluster,
} from '../../services/api';
import FormModal from '../../components/common/FormModal';
import ProgressModal from '../../components/common/ProgressModal';
import { useProgressModal } from '../../hooks/useProgressModal';
import { useResourceDebug } from '../../hooks/useResourceDebug';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { TaskIcon, PlusIcon, DownloadIcon } from '../../icons';
import { createTasksPageConfig } from '../../config/pages/tasks.config';
import { useSectorStore } from '../../store/sectorStore';
import { usePageSizeStore } from '../../store/pageSizeStore';
import ViewToggle, { ViewType } from '../../components/common/ViewToggle';
import { KanbanBoard, TaskList, Task as KanbanTask } from '../../components/tasks';
import WorkflowPipeline, { WorkflowStep } from '../../components/dashboard/WorkflowPipeline';
import ComponentCard from '../../components/common/ComponentCard';
import { useNavigate } from 'react-router';

export default function Tasks() {
  const navigate = useNavigate();
  const toast = useToast();
  const { activeSector } = useSectorStore();
  const { pageSize } = usePageSizeStore();

  // Data state
  const [tasks, setTasks] = useState<Task[]>([]);
  const [clusters, setClusters] = useState<Cluster[]>([]);
  const [loading, setLoading] = useState(true);
  
  // Filter state
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [clusterFilter, setClusterFilter] = useState('');
  const [structureFilter, setStructureFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  
  // Sorting state
  const [sortBy, setSortBy] = useState<string>('created_at');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [showContent, setShowContent] = useState(false);
  
  // View state
  const [currentView, setCurrentView] = useState<ViewType>('table');
  
  // Modal state
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [formData, setFormData] = useState<TaskCreateData>({
    title: '',
    description: '',
    keywords: '',
    cluster_id: null,
    content_structure: 'blog_post',
    content_type: 'blog_post',
    status: 'queued',
    word_count: 0,
  });

  // Progress modal for AI functions
  const progressModal = useProgressModal();

  // AI Function Logs state
  const [aiLogs, setAiLogs] = useState<Array<{
    timestamp: string;
    type: 'request' | 'success' | 'error' | 'step';
    action: string;
    data: any;
    stepName?: string;
    percentage?: number;
  }>>([]);
  
  // Resource Debug toggle - controls AI Function Logs
  const resourceDebugEnabled = useResourceDebug();

  // Track last logged step to avoid duplicates
  const lastLoggedStepRef = useRef<string | null>(null);
  const lastLoggedPercentageRef = useRef<number>(-1);
  const hasReloadedRef = useRef<boolean>(false);

  // Helper function to add log entry (only if Resource Debug is enabled)
  const addAiLog = useCallback((log: {
    timestamp: string;
    type: 'request' | 'success' | 'error' | 'step';
    action: string;
    data: any;
    stepName?: string;
    percentage?: number;
  }) => {
    if (resourceDebugEnabled) {
      setAiLogs(prev => [...prev, log]);
    }
  }, [resourceDebugEnabled]);

  // Load clusters for filter dropdown
  useEffect(() => {
    const loadClusters = async () => {
      try {
        const data = await fetchClusters({ ordering: 'name' });
        setClusters(data.results || []);
      } catch (error) {
        console.error('Error fetching clusters:', error);
      }
    };
    loadClusters();
  }, []);

  // Load tasks - wrapped in useCallback
  const loadTasks = useCallback(async () => {
    setLoading(true);
    setShowContent(false);
    try {
      const ordering = sortBy ? `${sortDirection === 'desc' ? '-' : ''}${sortBy}` : '-created_at';
      
      const filters: TasksFilters = {
        ...(searchTerm && { search: searchTerm }),
        ...(statusFilter && { status: statusFilter }),
        ...(clusterFilter && { cluster_id: clusterFilter }),
        ...(structureFilter && { content_structure: structureFilter }),
        ...(typeFilter && { content_type: typeFilter }),
        page: currentPage,
        page_size: pageSize,
        ordering,
      };
      
      const data = await fetchTasks(filters);
      setTasks(data.results || []);
      setTotalCount(data.count || 0);
      setTotalPages(Math.ceil((data.count || 0) / pageSize));
      
      setTimeout(() => {
        setShowContent(true);
        setLoading(false);
      }, 100);
    } catch (error: any) {
      console.error('Error loading tasks:', error);
      toast.error(`Failed to load tasks: ${error.message}`);
      setShowContent(true);
      setLoading(false);
    }
  }, [currentPage, statusFilter, clusterFilter, structureFilter, typeFilter, sortBy, sortDirection, searchTerm, activeSector, pageSize]);

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

  // Listen for site and sector changes and refresh data
  useEffect(() => {
    const handleSiteChange = () => {
      loadTasks();
    };
    
    const handleSectorChange = () => {
      loadTasks();
    };
    
    window.addEventListener('siteChanged', handleSiteChange);
    window.addEventListener('sectorChanged', handleSectorChange);
    return () => {
      window.removeEventListener('siteChanged', handleSiteChange);
      window.removeEventListener('sectorChanged', handleSectorChange);
    };
  }, [loadTasks]);

  // Reset to page 1 when pageSize changes
  useEffect(() => {
    setCurrentPage(1);
  }, [pageSize]);

  // Map API Task to KanbanBoard Task
  const mapTaskToKanbanTask = (task: Task): KanbanTask => {
    // Map status from API to Kanban status
    const statusMap: Record<string, "todo" | "in_progress" | "completed"> = {
      'queued': 'todo',
      'in_progress': 'in_progress',
      'generating': 'in_progress',
      'completed': 'completed',
      'published': 'completed',
      'draft': 'todo',
      'review': 'in_progress',
    };
    
    const kanbanStatus = statusMap[task.status] || 'todo';
    
    // Format due date if available (you might need to add this field to Task)
    const dueDate = task.created_at ? new Date(task.created_at).toLocaleDateString('en-US', { 
      month: 'short', 
      day: 'numeric', 
      year: 'numeric' 
    }) : undefined;

    // Parse keywords if available (comma-separated string)
    const keywordNames = task.keywords ? task.keywords.split(',').map(k => k.trim()).filter(k => k) : undefined;

    return {
      id: String(task.id),
      title: task.title || 'Untitled Task',
      status: kanbanStatus,
      dueDate,
      commentsCount: 0, // Add if you have this data
      attachmentsCount: 0, // Add if you have this data
      tags: task.cluster_name ? [{ label: task.cluster_name, color: 'brand' as const }] : undefined,
      description: task.description || undefined,
      assignee: undefined, // Add if you have assignee data
      // Relationship data
      clusterId: task.cluster_id || null,
      clusterName: task.cluster_name || null,
      ideaId: task.idea_id || null,
      ideaTitle: task.idea_title || null,
      keywordIds: undefined, // API doesn't return keyword IDs directly, would need to fetch
      keywordNames: keywordNames,
    };
  };

  const kanbanTasks = useMemo(() => tasks.map(mapTaskToKanbanTask), [tasks]);

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (currentPage === 1) {
        loadTasks();
      } else {
        setCurrentPage(1);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm, currentPage, loadTasks]);

  // Handle sorting
  const handleSort = (field: string, direction: 'asc' | 'desc') => {
    setSortBy(field || 'created_at');
    setSortDirection(direction);
    setCurrentPage(1);
  };

  // Bulk status update handler
  const handleBulkUpdateStatus = useCallback(async (ids: string[], status: string) => {
    try {
      const numIds = ids.map(id => parseInt(id));
      await bulkUpdateTasksStatus(numIds, status);
      await loadTasks();
    } catch (error: any) {
      throw error;
    }
  }, [loadTasks]);

  // Bulk export handler
  const handleBulkExport = useCallback(async (ids: string[]) => {
    try {
      if (!ids || ids.length === 0) {
        throw new Error('No records selected for export');
      }
      toast.info('Export functionality coming soon');
    } catch (error: any) {
      throw error;
    }
  }, []);

  // Row action handler for single task actions
  const handleRowAction = useCallback(async (action: string, row: Task) => {
    if (action === 'generate_content') {
      // Validate task has required data
      if (!row.title) {
        toast.error('Task must have a title to generate content');
        return;
      }
      
      // Optional: Validate task status (can generate for any status)
      // if (row.status !== 'queued') {
      //   toast.error(`Only tasks with status "queued" can generate content. Current status: ${row.status}`);
      //   return;
      // }
      
      const requestData = {
        ids: [row.id],
        task_title: row.title,
        task_id: row.id,
      };
      
      // Log request
      addAiLog({
        timestamp: new Date().toISOString(),
        type: 'request',
        action: 'generate_content (Row Action)',
        data: requestData,
      });

      try {
        const result = await autoGenerateContent([row.id]);
        
        if (result.success) {
          if (result.task_id) {
            // Log success with task_id
            addAiLog({
              timestamp: new Date().toISOString(),
              type: 'success',
              action: 'generate_content (Row Action)',
              data: { task_id: result.task_id, message: result.message },
            });
            // Async task - show progress modal
            progressModal.openModal(result.task_id, 'Generating Content', 'ai-generate-content-03');
            toast.success('Content generation started');
          } else {
            // Log success with results
            addAiLog({
              timestamp: new Date().toISOString(),
              type: 'success',
              action: 'generate_content (Row Action)',
              data: { tasks_updated: result.tasks_updated || 0, message: result.message },
            });
            // Synchronous completion
            toast.success(`Content generated successfully: ${result.tasks_updated || 0} article generated`);
            await loadTasks();
          }
        } else {
          // Log error
          addAiLog({
            timestamp: new Date().toISOString(),
            type: 'error',
            action: 'generate_content (Row Action)',
            data: { error: result.error || 'Failed to generate content' },
          });
          toast.error(result.error || 'Failed to generate content');
        }
      } catch (error: any) {
        // Log error
        addAiLog({
          timestamp: new Date().toISOString(),
          type: 'error',
          action: 'generate_content (Row Action)',
          data: { error: error.message || 'Unknown error occurred' },
        });
        toast.error(`Failed to generate content: ${error.message}`);
      }
    }
  }, [toast, loadTasks, progressModal]);

  // Bulk action handler
  const handleBulkAction = useCallback(async (action: string, ids: string[]) => {
    // generate_content removed from bulk actions - only available as row action
    if (action === 'generate_images') {
      if (ids.length === 0) {
        toast.error('Please select at least one task to generate images');
        return;
      }
      if (ids.length > 10) {
        toast.error('Maximum 10 tasks allowed for image generation');
        return;
      }
      const numIds = ids.map(id => parseInt(id));
      const selectedTasks = tasks.filter(t => numIds.includes(t.id));
      const requestData = {
        ids: numIds,
        task_count: numIds.length,
        task_titles: selectedTasks.map(t => t.title),
      };
      
      // Log request
      addAiLog({
        timestamp: new Date().toISOString(),
        type: 'request',
        action: 'generate_images (Bulk Action)',
        data: requestData,
      });
      
      try {
        const result = await autoGenerateImages(numIds);
        if (result.success) {
          if (result.task_id) {
            // Log success with task_id
            addAiLog({
              timestamp: new Date().toISOString(),
              type: 'success',
              action: 'generate_images (Bulk Action)',
              data: { task_id: result.task_id, message: result.message, task_count: numIds.length },
            });
            // Async task - show progress modal
            progressModal.openModal(result.task_id, 'Generating Images');
            toast.success('Image generation started');
          } else {
            // Log success with results
            addAiLog({
              timestamp: new Date().toISOString(),
              type: 'success',
              action: 'generate_images (Bulk Action)',
              data: { images_created: result.images_created || 0, message: result.message, task_count: numIds.length },
            });
            // Synchronous completion
            toast.success(`Image generation complete: ${result.images_created || 0} images generated`);
            await loadTasks();
          }
        } else {
          // Log error
          addAiLog({
            timestamp: new Date().toISOString(),
            type: 'error',
            action: 'generate_images (Bulk Action)',
            data: { error: result.error || 'Failed to generate images', task_count: numIds.length },
          });
          toast.error(result.error || 'Failed to generate images');
        }
      } catch (error: any) {
        // Log error
        addAiLog({
          timestamp: new Date().toISOString(),
          type: 'error',
          action: 'generate_images (Bulk Action)',
          data: { error: error.message || 'Unknown error occurred', task_count: numIds.length },
        });
        toast.error(`Failed to generate images: ${error.message}`);
      }
    } else {
      toast.info(`Bulk action "${action}" for ${ids.length} items`);
    }
  }, [toast, loadTasks, progressModal, tasks]);

  // Log AI function progress steps
  useEffect(() => {
    if (!progressModal.taskId || !progressModal.isOpen) {
      return;
    }

    const progress = progressModal.progress;
    const currentStep = progress.details?.phase || '';
    const currentPercentage = progress.percentage;
    const currentMessage = progress.message;
    const currentStatus = progress.status;

    // Log step changes
    if (currentStep && currentStep !== lastLoggedStepRef.current) {
      const stepType = currentStatus === 'error' ? 'error' : 
                      currentStatus === 'completed' ? 'success' : 'step';
      
      addAiLog({
        timestamp: new Date().toISOString(),
        type: stepType,
        action: progressModal.title || 'AI Function',
        stepName: currentStep,
        percentage: currentPercentage,
        data: {
          step: currentStep,
          message: currentMessage,
          percentage: currentPercentage,
          status: currentStatus,
          details: progress.details,
        },
      });
      
      lastLoggedStepRef.current = currentStep;
      lastLoggedPercentageRef.current = currentPercentage;
    }
    // Log percentage changes for same step (if significant change)
    else if (currentStep && Math.abs(currentPercentage - lastLoggedPercentageRef.current) >= 10) {
      const stepType = currentStatus === 'error' ? 'error' : 
                      currentStatus === 'completed' ? 'success' : 'step';
      
      addAiLog({
        timestamp: new Date().toISOString(),
        type: stepType,
        action: progressModal.title || 'AI Function',
        stepName: currentStep,
        percentage: currentPercentage,
        data: {
          step: currentStep,
          message: currentMessage,
          percentage: currentPercentage,
          status: currentStatus,
          details: progress.details,
        },
      });
      
      lastLoggedPercentageRef.current = currentPercentage;
    }
    // Log status changes (error, completed)
    else if (currentStatus === 'error' || currentStatus === 'completed') {
      // Only log if we haven't already logged this status for this step
      if (currentStep !== lastLoggedStepRef.current || 
          (currentStatus === 'error' && lastLoggedStepRef.current !== 'error') ||
          (currentStatus === 'completed' && lastLoggedStepRef.current !== 'completed')) {
        const stepType = currentStatus === 'error' ? 'error' : 'success';
        
        addAiLog({
          timestamp: new Date().toISOString(),
          type: stepType,
          action: progressModal.title || 'AI Function',
          stepName: currentStep || 'Final',
          percentage: currentPercentage,
          data: {
            step: currentStep || 'Final',
            message: currentMessage,
            percentage: currentPercentage,
            status: currentStatus,
            details: progress.details,
          },
        });
        
        lastLoggedStepRef.current = currentStep || currentStatus;
      }
    }
  }, [progressModal.progress, progressModal.taskId, progressModal.isOpen, progressModal.title, addAiLog]);

  // Reset step tracking when modal closes or opens
  useEffect(() => {
    if (!progressModal.isOpen) {
      lastLoggedStepRef.current = null;
      lastLoggedPercentageRef.current = -1;
      hasReloadedRef.current = false; // Reset reload flag when modal closes
    } else {
      // Reset reload flag when modal opens for a new task
      hasReloadedRef.current = false;
    }
  }, [progressModal.isOpen, progressModal.taskId]);

  // Create page config
  const pageConfig = useMemo(() => {
    return createTasksPageConfig({
      clusters,
      activeSector,
      formData,
      setFormData,
      searchTerm,
      setSearchTerm,
      statusFilter,
      setStatusFilter,
      clusterFilter,
      setClusterFilter,
      structureFilter,
      setStructureFilter,
      typeFilter,
      setTypeFilter,
      setCurrentPage,
    });
  }, [clusters, activeSector, formData, searchTerm, statusFilter, clusterFilter, structureFilter, typeFilter]);

  // Calculate header metrics
  const headerMetrics = useMemo(() => {
    if (!pageConfig?.headerMetrics) return [];
    return pageConfig.headerMetrics.map((metric) => ({
      label: metric.label,
      value: metric.calculate({ tasks, totalCount }),
      accentColor: metric.accentColor,
    }));
  }, [pageConfig?.headerMetrics, tasks, totalCount]);

  const resetForm = useCallback(() => {
    setFormData({
      title: '',
      description: '',
      keywords: '',
      cluster_id: null,
      content_structure: 'blog_post',
      content_type: 'blog_post',
      status: 'queued',
      word_count: 0,
    });
    setIsEditMode(false);
    setEditingTask(null);
  }, []);

  // Handle create/edit
  const handleSave = async () => {
    try {
      if (isEditMode && editingTask) {
        await updateTask(editingTask.id, formData);
        toast.success('Task updated successfully');
      } else {
        await createTask(formData);
        toast.success('Task created successfully');
      }
      setIsModalOpen(false);
      resetForm();
      loadTasks();
    } catch (error: any) {
      toast.error(`Failed to save: ${error.message}`);
    }
  };

  const handleTaskClick = (kanbanTask: KanbanTask) => {
    const apiTask = tasks.find(t => String(t.id) === kanbanTask.id);
    if (apiTask) {
      setEditingTask(apiTask);
      setFormData({
        title: apiTask.title || '',
        description: apiTask.description || '',
        keywords: apiTask.keywords || '',
        cluster_id: apiTask.cluster_id || null,
        content_structure: apiTask.content_structure || 'blog_post',
        content_type: apiTask.content_type || 'blog_post',
        status: apiTask.status || 'queued',
        word_count: apiTask.word_count || 0,
      });
      setIsEditMode(true);
      setIsModalOpen(true);
    }
  };

  const handleTaskMove = async (taskId: string, newStatus: "todo" | "in_progress" | "completed") => {
    const apiTask = tasks.find(t => String(t.id) === taskId);
    if (!apiTask) return;

    // Map Kanban status back to API status
    const statusMap: Record<string, string> = {
      'todo': 'queued',
      'in_progress': 'in_progress',
      'completed': 'completed',
    };

    try {
      await updateTask(apiTask.id, { status: statusMap[newStatus] || 'queued' });
      toast.success('Task status updated');
      loadTasks();
    } catch (error: any) {
      toast.error(`Failed to update task: ${error.message}`);
    }
  };

  // Calculate workflow steps for Tasks page
  const todoCount = tasks.filter(t => t.status === 'queued' || t.status === 'draft').length;
  const inProgressCount = tasks.filter(t => t.status === 'in_progress' || t.status === 'generating' || t.status === 'review').length;
  const completedCount = tasks.filter(t => t.status === 'completed' || t.status === 'published').length;
  const contentCount = tasks.filter(t => t.content && t.content.length > 0).length;

  const workflowSteps: WorkflowStep[] = [
    {
      number: 1,
      title: "Queue Tasks",
      status: todoCount > 0 ? "completed" : "pending",
      count: todoCount,
      path: "/writer/tasks",
      description: "Tasks queued for content generation",
    },
    {
      number: 2,
      title: "Generate Content",
      status: inProgressCount > 0 ? "in_progress" : contentCount > 0 ? "completed" : "pending",
      count: contentCount,
      path: "/writer/tasks",
      description: "AI content generation",
    },
    {
      number: 3,
      title: "Review & Edit",
      status: tasks.filter(t => t.status === 'review').length > 0 ? "in_progress" : "pending",
      count: tasks.filter(t => t.status === 'review').length,
      path: "/writer/content",
      description: "Content review and editing",
    },
    {
      number: 4,
      title: "Publish",
      status: completedCount > 0 ? "completed" : "pending",
      count: completedCount,
      path: "/writer/content",
      description: "Published content",
    },
  ];

  return (
    <>
      {/* Workflow Pipeline - Show for all views */}
      <div className="mb-6">
        <ComponentCard title="Content Creation Workflow" desc="Track your content creation progress">
          <WorkflowPipeline
            steps={workflowSteps}
            onStepClick={(step) => {
              navigate(step.path);
            }}
            showConnections={true}
          />
        </ComponentCard>
      </div>

      {/* View Toggle - Only show for Kanban/List views */}
      {currentView !== 'table' && (
        <div className="mb-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
              <TaskIcon className="text-brand-500 size-6" />
              Tasks
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 hidden sm:block">
              Manage content generation queue and tasks
            </p>
          </div>
          <ViewToggle currentView={currentView} onViewChange={setCurrentView} />
        </div>
      )}

      {/* Table View */}
      {currentView === 'table' && (
        <>
          <div className="mb-4 flex justify-end">
            <ViewToggle currentView={currentView} onViewChange={setCurrentView} />
          </div>
          <TablePageTemplate
          title="Tasks"
          titleIcon={<TaskIcon className="text-brand-500 size-5" />}
          subtitle="Manage content generation queue and tasks"
          columns={pageConfig.columns}
          data={tasks}
          loading={loading}
          showContent={showContent}
          filters={pageConfig.filters}
          filterValues={{
            search: searchTerm,
            status: statusFilter,
            cluster_id: clusterFilter,
            content_structure: structureFilter,
            content_type: typeFilter,
          }}
          onFilterChange={(key, value) => {
            const stringValue = value === null || value === undefined ? '' : String(value);
            if (key === 'search') {
              setSearchTerm(stringValue);
            } else if (key === 'status') {
              setStatusFilter(stringValue);
            } else if (key === 'cluster_id') {
              setClusterFilter(stringValue);
            } else if (key === 'content_structure') {
              setStructureFilter(stringValue);
            } else if (key === 'content_type') {
              setTypeFilter(stringValue);
            }
            setCurrentPage(1);
          }}
          onEdit={(row) => {
            setEditingTask(row);
            setFormData({
              title: row.title || '',
              description: row.description || '',
              keywords: row.keywords || '',
              cluster_id: row.cluster_id || null,
              content_structure: row.content_structure || 'blog_post',
              content_type: row.content_type || 'blog_post',
              status: row.status || 'queued',
              word_count: row.word_count || 0,
            });
            setIsEditMode(true);
            setIsModalOpen(true);
          }}
          onCreate={() => {
            resetForm();
            setIsModalOpen(true);
          }}
          createLabel="Add Task"
          onCreateIcon={<PlusIcon />}
          onDelete={async (id: number) => {
            await deleteTask(id);
            loadTasks();
          }}
          onBulkDelete={async (ids: number[]) => {
            const result = await bulkDeleteTasks(ids);
            // Clear selection first
            setSelectedIds([]);
            // Reset to page 1 if we deleted all items on current page
            if (currentPage > 1 && tasks.length <= ids.length) {
              setCurrentPage(1);
            }
            // Always reload data to refresh the table
            await loadTasks();
            return result;
          }}
          onBulkExport={handleBulkExport}
          onBulkUpdateStatus={handleBulkUpdateStatus}
          onBulkAction={handleBulkAction}
          onRowAction={handleRowAction}
          getItemDisplayName={(row: Task) => row.title}
          onExport={async () => {
            toast.info('Export functionality coming soon');
          }}
          onExportIcon={<DownloadIcon />}
          selectionLabel="task"
          pagination={{
            currentPage,
            totalPages,
            totalCount,
            onPageChange: setCurrentPage,
          }}
          selection={{
            selectedIds,
            onSelectionChange: setSelectedIds,
          }}
          sorting={{
            sortBy,
            sortDirection,
            onSort: handleSort,
          }}
          headerMetrics={headerMetrics}
          onFilterReset={() => {
            setSearchTerm('');
            setStatusFilter('');
            setClusterFilter('');
            setStructureFilter('');
            setTypeFilter('');
            setCurrentPage(1);
          }}
        />
        </>
      )}

      {/* Kanban View */}
      {currentView === 'kanban' && (
        <KanbanBoard
          tasks={kanbanTasks}
          onTaskClick={handleTaskClick}
          onTaskMove={handleTaskMove}
          onAddTask={() => {
            resetForm();
            setIsModalOpen(true);
          }}
          onFilterChange={(filter) => {
            // Map filter to status filter
            const statusMap: Record<string, string> = {
              'All': '',
              'Todo': 'queued',
              'InProgress': 'in_progress',
              'Completed': 'completed',
            };
            setStatusFilter(statusMap[filter] || '');
            setCurrentPage(1);
            loadTasks();
          }}
        />
      )}

      {/* List View */}
      {currentView === 'list' && (
        <TaskList
          tasks={kanbanTasks}
          onTaskClick={handleTaskClick}
          onTaskToggle={async (taskId, completed) => {
            const apiTask = tasks.find(t => String(t.id) === taskId);
            if (apiTask) {
              try {
                await updateTask(apiTask.id, { status: completed ? 'completed' : 'queued' });
                toast.success('Task updated');
                loadTasks();
              } catch (error: any) {
                toast.error(`Failed to update task: ${error.message}`);
              }
            }
          }}
          onAddTask={() => {
            resetForm();
            setIsModalOpen(true);
          }}
          onFilterChange={(filter) => {
            // Map filter to status filter
            const statusMap: Record<string, string> = {
              'All': '',
              'Todo': 'queued',
              'InProgress': 'in_progress',
              'Completed': 'completed',
            };
            setStatusFilter(statusMap[filter] || '');
            setCurrentPage(1);
            loadTasks();
          }}
        />
      )}

      {/* Progress Modal for AI Functions */}
      <ProgressModal
        isOpen={progressModal.isOpen}
        title={progressModal.title}
        percentage={progressModal.progress.percentage}
        status={progressModal.progress.status}
        message={progressModal.progress.message}
        details={progressModal.progress.details}
        taskId={progressModal.taskId || undefined}
        functionId={progressModal.functionId}
        onClose={() => {
          const wasCompleted = progressModal.progress.status === 'completed';
          progressModal.closeModal();
          // Reload data after modal closes (if completed)
          if (wasCompleted && !hasReloadedRef.current) {
            hasReloadedRef.current = true;
            loadTasks();
            setTimeout(() => {
              hasReloadedRef.current = false;
            }, 1000);
          }
        }}
      />

      {/* AI Function Logs - Display below table (only when Resource Debug is enabled) */}
      {resourceDebugEnabled && aiLogs.length > 0 && (
        <div className="mt-6 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
              AI Function Logs
            </h3>
            <button
              onClick={() => setAiLogs([])}
              className="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
            >
              Clear Logs
            </button>
          </div>
          <div className="space-y-2 max-h-96 overflow-y-auto">
            {aiLogs.slice().reverse().map((log, index) => (
              <div
                key={index}
                className={`p-3 rounded border text-xs font-mono ${
                  log.type === 'request'
                    ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
                    : log.type === 'success'
                    ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                    : log.type === 'error'
                    ? 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
                    : 'bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800'
                }`}
              >
                <div className="flex items-center justify-between mb-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className={`font-semibold ${
                      log.type === 'request'
                        ? 'text-blue-700 dark:text-blue-300'
                        : log.type === 'success'
                        ? 'text-green-700 dark:text-green-300'
                        : log.type === 'error'
                        ? 'text-red-700 dark:text-red-300'
                        : 'text-purple-700 dark:text-purple-300'
                    }`}>
                      [{log.type.toUpperCase()}]
                    </span>
                    <span className="text-gray-700 dark:text-gray-300">
                      {log.action}
                    </span>
                    {log.stepName && (
                      <span className="text-xs px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
                        {log.stepName}
                      </span>
                    )}
                    {log.percentage !== undefined && (
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        {log.percentage}%
                      </span>
                    )}
                  </div>
                  <span className="text-gray-500 dark:text-gray-400">
                    {new Date(log.timestamp).toLocaleTimeString()}
                  </span>
                </div>
                <pre className="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words">
                  {JSON.stringify(log.data, null, 2)}
                </pre>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Create/Edit Modal */}
      <FormModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          resetForm();
        }}
        onSubmit={handleSave}
        title={isEditMode ? 'Edit Task' : 'Add Task'}
        submitLabel={isEditMode ? 'Update' : 'Create'}
        fields={pageConfig.formFields(clusters)}
      />
    </>
  );
}
