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

import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { Link } from 'react-router-dom';
import TablePageTemplate from '../../templates/TablePageTemplate';
import {
  fetchTasks,
  fetchImages,
  fetchContent,
  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 { useToast } from '../../components/ui/toast/ToastContainer';
import { TaskIcon, PlusIcon, DownloadIcon, CheckCircleIcon } from '../../icons';
import { createTasksPageConfig } from '../../config/pages/tasks.config';
import { useSectorStore } from '../../store/sectorStore';
import { useSiteStore } from '../../store/siteStore';
import { usePageSizeStore } from '../../store/pageSizeStore';
import PageHeader from '../../components/common/PageHeader';
import StandardThreeWidgetFooter from '../../components/dashboard/StandardThreeWidgetFooter';
import { DocumentTextIcon } from '@heroicons/react/24/outline';

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

  // Data state
  const [tasks, setTasks] = useState<Task[]>([]);
  const [clusters, setClusters] = useState<Cluster[]>([]);
  const [loading, setLoading] = useState(true);

  // Total counts for footer widget and header metrics (not page-filtered)
  const [totalContent, setTotalContent] = useState(0);
  const [totalDraft, setTotalDraft] = useState(0);
  const [totalReview, setTotalReview] = useState(0);
  const [totalApproved, setTotalApproved] = useState(0);
  const [totalPublished, setTotalPublished] = useState(0);
  const [totalImagesCount, setTotalImagesCount] = useState(0);
  
  // Footer widget specific counts (task-based)
  const [totalQueued, setTotalQueued] = useState(0);
  const [totalProcessing, setTotalProcessing] = useState(0);
  const [totalCompleted, setTotalCompleted] = useState(0);
  
  // Filter state
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [clusterFilter, setClusterFilter] = useState('');
  const [structureFilter, setStructureFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [sourceFilter, setSourceFilter] = 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);
  
  // 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: 'article',
    content_type: 'post',
    status: 'queued',
    word_count: 0,
  });

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

  const hasReloadedRef = useRef<boolean>(false);



  // 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 total metrics for footer widget and header metrics (site-wide totals, no sector filter)
  const loadTotalMetrics = useCallback(async () => {
    try {
      // Batch all API calls in parallel for better performance
      const [allRes, draftRes, reviewRes, approvedRes, publishedRes, imagesRes] = await Promise.all([
        // Get all content (site-wide)
        fetchContent({
          page_size: 1,
          site_id: activeSite?.id,
        }),
        // Get content with status='draft'
        fetchContent({
          page_size: 1,
          site_id: activeSite?.id,
          status: 'draft',
        }),
        // Get content with status='review'
        fetchContent({
          page_size: 1,
          site_id: activeSite?.id,
          status: 'review',
        }),
        // Get content with status='approved'
        fetchContent({
          page_size: 1,
          site_id: activeSite?.id,
          status: 'approved',
        }),
        // Get content with status='published'
        fetchContent({
          page_size: 1,
          site_id: activeSite?.id,
          status: 'published',
        }),
        // Get actual total images count
        fetchImages({ page_size: 1, site_id: activeSite?.id }),
      ]);

      setTotalContent(allRes.count || 0);
      setTotalDraft(draftRes.count || 0);
      setTotalReview(reviewRes.count || 0);
      setTotalApproved(approvedRes.count || 0);
      setTotalPublished(publishedRes.count || 0);
      setTotalImagesCount(imagesRes.count || 0);
    } catch (error) {
      console.error('Error loading total metrics:', error);
    }
  }, [activeSite]);

  // Load total metrics when sector changes
  useEffect(() => {
    loadTotalMetrics();
  }, [loadTotalMetrics]);

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


  // Debounced search - reset to page 1 when search term changes
  // Only depend on searchTerm to avoid pagination reset on page navigation
  useEffect(() => {
    const timer = setTimeout(() => {
      // Always reset to page 1 when search changes
      // The main useEffect will handle reloading when currentPage changes
      setCurrentPage(1);
    }, 500);

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

  // 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;
      // }
      
      try {
        const result = await autoGenerateContent([row.id]);
        
        if (result.success) {
          if (result.task_id) {
            // Async task - show progress modal
            progressModal.openModal(result.task_id, 'Generating Content', 'ai-generate-content-03');
            toast.success('Content generation started');
          } else {
            // Synchronous completion
            toast.success(`Content generated successfully: ${result.tasks_updated || 0} article generated`);
            await loadTasks();
          }
        } else {
          toast.error(result.error || 'Failed to generate content');
        }
      } catch (error: any) {
        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));
      
      try {
        const result = await autoGenerateImages(numIds);
        if (result.success) {
          if (result.task_id) {
            // Async task - show progress modal
            progressModal.openModal(result.task_id, 'Generating Images');
            toast.success('Image generation started');
          } else {
            // Synchronous completion
            toast.success(`Image generation complete: ${result.images_created || 0} images generated`);
            await loadTasks();
          }
        } else {
          toast.error(result.error || 'Failed to generate images');
        }
      } catch (error: any) {
        toast.error(`Failed to generate images: ${error.message}`);
      }
    } else {
      toast.info(`Bulk action "${action}" for ${ids.length} items`);
    }
  }, [toast, loadTasks, progressModal, tasks]);

  // Reset reload flag when modal closes or opens
  useEffect(() => {
    if (!progressModal.isOpen) {
      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,
      sourceFilter,
      setSourceFilter,
      setClusterFilter,
      structureFilter,
      setStructureFilter,
      typeFilter,
      setTypeFilter,
      setCurrentPage,
    });
  }, [clusters, activeSector, formData, searchTerm, statusFilter, clusterFilter, structureFilter, typeFilter, sourceFilter]);

  // Calculate header metrics - use totals from API calls (not page data)
  // This ensures metrics show correct totals across all pages, not just current page
  const headerMetrics = useMemo(() => {
    if (!pageConfig?.headerMetrics) return [];

    // Override the calculate function to use pre-loaded totals instead of filtering page data
    return pageConfig.headerMetrics.map((metric) => {
      let value: number;

      switch (metric.label) {
        case 'Content':
          value = totalContent || 0;
          break;
        case 'Draft':
          value = totalDraft;
          break;
        case 'In Review':
          value = totalReview;
          break;
        case 'Approved':
          value = totalApproved;
          break;
        case 'Published':
          value = totalPublished;
          break;
        case 'Total Images':
          value = totalImagesCount;
          break;
        default:
          value = metric.calculate({ tasks, totalCount });
      }

      return {
        label: metric.label,
        value,
        accentColor: metric.accentColor,
        tooltip: (metric as any).tooltip,
      };
    });
  }, [pageConfig?.headerMetrics, tasks, totalContent, totalDraft, totalReview, totalApproved, totalPublished, totalImagesCount]);

  const resetForm = useCallback(() => {
    setFormData({
      title: '',
      description: '',
      keywords: '',
      cluster_id: null,
      content_structure: 'article',
      content_type: '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}`);
    }
  };

  return (
    <>
      <PageHeader 
        title="Content Queue" 
        badge={{ icon: <DocumentTextIcon />, color: 'blue' }}
        parent="Writer"
      />
      <TablePageTemplate
          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,
            source: sourceFilter,
          }}
          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);
            } else if (key === 'source') {
              setSourceFilter(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 || 'article',
              content_type: row.content_type || 'post',
              status: row.status || 'queued',
              word_count: row.word_count || 0,
            });
            setIsEditMode(true);
            setIsModalOpen(true);
          }}
          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);
          }}
        />

      {/* Three Widget Footer - Section 3 Layout with Standardized Widgets */}
      <StandardThreeWidgetFooter
        submoduleColor="blue"
        module="writer"
        pageProgress={{
          title: 'Page Progress',
          submoduleColor: 'blue',
          metrics: [
            { label: 'Total', value: totalCount },
            { label: 'Complete', value: totalCompleted, percentage: `${totalCount > 0 ? Math.round((totalCompleted / totalCount) * 100) : 0}%` },
            { label: 'Queue', value: totalQueued },
            { label: 'Processing', value: totalProcessing },
          ],
          progress: {
            value: totalCount > 0 ? Math.round((totalCompleted / totalCount) * 100) : 0,
            label: 'Generated',
            color: 'blue',
          },
          hint: totalQueued > 0
            ? `${totalQueued} tasks in queue for content generation`
            : 'All tasks processed!',
          statusInsight: totalQueued > 0
            ? `Select tasks and run content generation to create articles.`
            : totalCompleted > 0
              ? `Content generated. Review drafts on the Content page.`
              : `No tasks yet. Queue ideas from the Planner Ideas page.`,
        }}
        showCredits={true}
        analyticsHref="/account/usage"
      />

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

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