/**
 * Content Plan Table Component
 *
 * A comprehensive table component using TanStack Table for CRUD operations
 */

import {
    useState,
    useMemo,
    useCallback,
    useEffect,
    useRef,
} from '@wordpress/element';
import React from 'react';
import { __ } from '@wordpress/i18n';
import { useContentPlan } from '../context/ContentPlanContext';
import DeleteConfirmationModal from './DeleteConfirmationModal';
import GeneratePostModal from './GeneratePostModal';
import StructureDisplay from './StructureDisplay';
import KeywordDisplay from './KeywordDisplay';
import Tooltip from './Tooltip';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import {
    useReactTable,
    getCoreRowModel,
    getFilteredRowModel,
    getPaginationRowModel,
    getSortedRowModel,
    flexRender,
    createColumnHelper,
    getExpandedRowModel,
    Row,
} from '@tanstack/react-table';
import { ContentPlanItem } from '../types';
import { LANGUAGE_OPTIONS } from '../utils/languageOptions';

interface ContentPlanTableProps {
    currentTooltipId?: string | null;
    onTooltipDismiss?: () => void;
    currentTooltipIndex?: number;
    totalTooltipCount?: number;
    onSkipTutorial?: () => void;
}

const ContentPlanTable: React.FC<ContentPlanTableProps> = ({
    currentTooltipId = null,
    onTooltipDismiss,
    currentTooltipIndex,
    totalTooltipCount,
    onSkipTutorial,
}) => {
    const {
        getString,
        openSidebar,
        contentPlan,
        loading,
        error,
        fetchContentPlanItems,
        deleteContentPlanItemAPI,
        bulkDeleteContentPlanItems,
        openGenerationModal,
        getLatestContentPlanDate,
        taskFilterId,
        clearTaskFilter,
        tasks,
        settings,
        saveSettings,
    } = useContentPlan();

    const [filteredData, setFilteredData] = useState<ContentPlanItem[]>([]);
    const [searchTerm, setSearchTerm] = useState<string>('');
    const [currentPlanId] = useState<number>(1); // Default to plan ID 1 for now
    const [deleteModalOpen, setDeleteModalOpen] = useState<boolean>(false);
    const [itemToDelete, setItemToDelete] = useState<
        ContentPlanItem | undefined
    >(undefined);
    const [generateModalOpen, setGenerateModalOpen] = useState<boolean>(false);
    const [itemToGenerate, setItemToGenerate] =
        useState<ContentPlanItem | null>(null);
    const [expanded, setExpanded] = useState({});
    const [dateRangeStart, setDateRangeStart] = useState<Date | null>(null);
    const [dateRangeEnd, setDateRangeEnd] = useState<Date | null>(null);
    const [datePreset, setDatePreset] = useState<string>('future');
    const [sorting, setSorting] = useState([
        { id: 'scheduled_on', desc: false }, // Sort by scheduled_on ascending (nearest first)
    ]);
    const [pagination, setPagination] = useState({
        pageIndex: 0,
        pageSize: 10,
    });
    const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set());
    const [columnVisibility, setColumnVisibility] = useState({});
    const [isMobile, setIsMobile] = useState(false);
    const tableContainerRef = useRef<HTMLDivElement>(null);

    // Check if tutorial should be shown
    const showTutorial = settings && settings.tutorial_watched !== true;

    // Detect mobile screen size
    useEffect(() => {
        const checkMobile = () => {
            setIsMobile(window.innerWidth < 768);
        };
        checkMobile();
        window.addEventListener('resize', checkMobile);
        return () => window.removeEventListener('resize', checkMobile);
    }, []);

    // Hide columns on mobile
    useEffect(() => {
        if (isMobile) {
            setColumnVisibility({
                id: false,
                structure: false,
                keywords: false,
                lang: false,
                post: false,
                expander: false,
            });
        } else {
            setColumnVisibility({});
        }
    }, [isMobile]);

    // Helper function to get WordPress admin edit URL for a post
    const getPostEditUrl = useCallback(
        (postId: string | number | null): string | null => {
            if (!postId) return null;
            // Construct WordPress admin edit URL
            const adminUrl = `${window.location.origin}/wp-admin/post.php?post=${postId}&action=edit`;
            return adminUrl;
        },
        []
    );

    // Event handler for generating posts
    const handleGenerate = useCallback((item: ContentPlanItem): void => {
        setItemToGenerate(item);
        setGenerateModalOpen(true);
    }, []);

    // Column definitions
    const columnHelper = createColumnHelper<ContentPlanItem>();

    const columns = useMemo(
        () => [
            columnHelper.display({
                id: 'checkbox',
                header: () => (
                    <input
                        type="checkbox"
                        checked={
                            selectedItems.size > 0 &&
                            selectedItems.size === filteredData.length
                        }
                        onChange={e => {
                            if (e.target.checked) {
                                setSelectedItems(
                                    new Set(filteredData.map(item => item.id))
                                );
                            } else {
                                setSelectedItems(new Set());
                            }
                        }}
                        className="w-4 h-4 cursor-pointer"
                    />
                ),
                cell: ({ row }) => (
                    <input
                        type="checkbox"
                        checked={selectedItems.has(row.original.id)}
                        onChange={e => {
                            const newSelected = new Set(selectedItems);
                            if (e.target.checked) {
                                newSelected.add(row.original.id);
                            } else {
                                newSelected.delete(row.original.id);
                            }
                            setSelectedItems(newSelected);
                        }}
                        className="w-4 h-4 cursor-pointer"
                    />
                ),
                size: 50,
            }),
            columnHelper.display({
                id: 'expander',
                header: () => null,
                cell: ({ row }) => (
                    <button
                        onClick={() => row.toggleExpanded()}
                        className="p-2 hover:bg-gray-100 rounded-full"
                    >
                        <svg
                            className={`w-5 h-5 transition-transform ${
                                row.getIsExpanded()
                                    ? 'transform rotate-180'
                                    : ''
                            }`}
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M19 9l-7 7-7-7"
                            />
                        </svg>
                    </button>
                ),
                size: 50,
            }),
            columnHelper.display({
                id: 'actions',
                header: getString('table_columns', 'actions', 'Actions'),
                cell: info => {
                    const status =
                        (info.row.original as any).status || 'planned';
                    const isPlanned = status === 'planned';
                    const isDraftReadyAi = status === 'draft_ready_ai';
                    // Check if there are any pending tasks (queued or processing)
                    const hasPendingTasks = tasks.some(
                        task =>
                            task.status === 'queued' ||
                            task.status === 'processing'
                    );
                    return (
                        <div className="flex flex-wrap gap-2 sm:gap-3 items-center">
                            {/* Show Generate button for planned items */}
                            {isPlanned && (
                                <button
                                    onClick={
                                        hasPendingTasks
                                            ? undefined
                                            : () =>
                                                  handleGenerate(
                                                      info.row.original
                                                  )
                                    }
                                    disabled={hasPendingTasks}
                                    className={`flex items-center gap-1 text-orange-500 hover:text-orange-600 text-xs sm:text-sm font-bold bg-white px-1 sm:px-2 py-1 rounded w-full ${
                                        hasPendingTasks
                                            ? 'opacity-50 cursor-not-allowed'
                                            : ''
                                    }`}
                                    title={
                                        hasPendingTasks
                                            ? getString(
                                                  'table_cells',
                                                  'generation_disabled_pending_task',
                                                  'Please wait for the current task to complete'
                                              )
                                            : getString(
                                                  'table_cells',
                                                  'generate',
                                                  'Generate'
                                              )
                                    }
                                >
                                    <svg
                                        className="w-3 h-3 sm:w-4 sm:h-4"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
                                        />
                                    </svg>
                                    <span className="hidden sm:inline">
                                        {getString(
                                            'table_cells',
                                            'generate',
                                            'Generate'
                                        )}
                                    </span>
                                </button>
                            )}
                            {/* Show Regenerate button for draft_ready_ai items */}
                            {isDraftReadyAi && (
                                <button
                                    onClick={
                                        hasPendingTasks
                                            ? undefined
                                            : () =>
                                                  handleGenerate(
                                                      info.row.original
                                                  )
                                    }
                                    disabled={hasPendingTasks}
                                    className={`flex items-center gap-1 text-orange-500 hover:text-orange-600 text-xs sm:text-sm font-bold bg-white px-1 sm:px-2 py-1 rounded w-full ${
                                        hasPendingTasks
                                            ? 'opacity-50 cursor-not-allowed'
                                            : ''
                                    }`}
                                    title={
                                        hasPendingTasks
                                            ? getString(
                                                  'table_cells',
                                                  'generation_disabled_pending_task',
                                                  'Please wait for the current task to complete'
                                              )
                                            : getString(
                                                  'table_cells',
                                                  'regenerate',
                                                  'Regenerate'
                                              )
                                    }
                                >
                                    <svg
                                        className="w-3 h-3 sm:w-4 sm:h-4"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                                        />
                                    </svg>
                                    <span className="hidden sm:inline">
                                        {getString(
                                            'table_cells',
                                            'regenerate',
                                            'Regenerate'
                                        )}
                                    </span>
                                </button>
                            )}
                            <button
                                onClick={() => handleEdit(info.row.original)}
                                className="text-primary hover:text-primary-dark"
                                title={getString('table_cells', 'edit', 'Edit')}
                            >
                                <svg
                                    className="w-4 h-4 sm:w-5 sm:h-5"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                                    />
                                </svg>
                            </button>
                            <button
                                onClick={() => handleDelete(info.row.original)}
                                className="text-red-600 hover:text-red-700"
                                title={getString(
                                    'table_cells',
                                    'delete',
                                    'Delete'
                                )}
                            >
                                <svg
                                    className="w-4 h-4 sm:w-5 sm:h-5"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                                    />
                                </svg>
                            </button>
                        </div>
                    );
                },
                size: 120,
            }),
            columnHelper.accessor('id', {
                header: getString('table_columns', 'id', 'ID'),
                cell: info => info.getValue(),
                size: 60,
            }),
            columnHelper.accessor('title', {
                header: getString('table_columns', 'title', 'Title'),
                cell: info => {
                    const value =
                        info.getValue() ||
                        getString('table_cells', 'untitled', 'Untitled');
                    if (!searchTerm.trim()) {
                        return (
                            <div className="font-medium text-wp-text break-words">
                                {value}
                            </div>
                        );
                    }
                    const regex = new RegExp(
                        `(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`,
                        'ig'
                    );
                    const parts = String(value).split(regex);
                    return (
                        <div className="font-medium text-wp-text break-words">
                            {parts.map((part, idx) =>
                                regex.test(part) ? (
                                    <mark
                                        key={idx}
                                        className="bg-yellow-200 px-0.5 rounded"
                                    >
                                        {part}
                                    </mark>
                                ) : (
                                    <span key={idx}>{part}</span>
                                )
                            )}
                        </div>
                    );
                },
                size: 100,
            }),
            columnHelper.accessor('structure', {
                header: getString('table_columns', 'structure', 'Structure'),
                cell: info => {
                    const value = info.getValue();
                    return (
                        <StructureDisplay
                            structure={value}
                            getString={getString}
                            maxWidth="max-w-xs"
                        />
                    );
                },
                size: 300,
            }),
            columnHelper.accessor('keywords', {
                header: getString('table_columns', 'keywords', 'Keywords'),
                cell: info => {
                    const value = info.getValue();
                    return (
                        <KeywordDisplay
                            keywords={value}
                            getString={getString}
                            maxWidth="max-w-xs"
                        />
                    );
                },
                size: 200,
            }),
            columnHelper.accessor('post', {
                header: getString('table_columns', 'post', 'Post'),
                cell: info => {
                    const value = info.getValue();
                    const status = (info.row.original as any).status;

                    // Only show post field if status is not 'planned'
                    if (status === 'planned') {
                        return (
                            <span className="text-wp-gray italic">
                                {getString(
                                    'table_cells',
                                    'not_available',
                                    'Not available'
                                )}
                            </span>
                        );
                    }

                    if (!value) {
                        return (
                            <span className="text-wp-gray italic">
                                {getString('table_cells', 'no_post', 'No post')}
                            </span>
                        );
                    }

                    // Convert post ID to edit URL
                    const editUrl = getPostEditUrl(value);
                    if (editUrl) {
                        return (
                            <a
                                href={editUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center gap-1 text-primary hover:text-primary-dark text-sm font-medium underline"
                            >
                                <svg
                                    className="w-4 h-4"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                                    />
                                </svg>
                                {getString(
                                    'table_cells',
                                    'view_post',
                                    'View Post'
                                )}
                            </a>
                        );
                    }

                    // Fallback: show post ID as text
                    return <span className="text-wp-text">Post #{value}</span>;
                },
                size: 150,
            }),
            columnHelper.display({
                id: 'status',
                header: getString('table_columns', 'status', 'Status'),
                cell: info => {
                    const value =
                        (info.row.original as any).status || 'planned';
                    const statusClasses = {
                        planned: 'bg-gray-100 text-gray-800',
                        draft_ready_ai: 'bg-blue-100 text-blue-800',
                        draft_ready_manual: 'bg-green-100 text-green-800',
                        published: 'bg-purple-100 text-purple-800',
                    };
                    return (
                        <span
                            className={`px-2 py-1 text-xs font-medium rounded-full ${
                                statusClasses[
                                    value as keyof typeof statusClasses
                                ] || statusClasses.planned
                            }`}
                        >
                            {getString(
                                `status_${value}`,
                                'label',
                                value
                                    .replace(/_/g, ' ')
                                    .replace(/\b\w/g, (l: string) =>
                                        l.toUpperCase()
                                    )
                            )}
                        </span>
                    );
                },
                size: 150,
            }),
            columnHelper.accessor('scheduled_on', {
                header: getString(
                    'table_columns',
                    'scheduled_on',
                    'Scheduled On'
                ),
                cell: info => {
                    const value = info.getValue();
                    if (!value) {
                        return (
                            <span className="text-wp-gray italic">
                                {getString(
                                    'table_cells',
                                    'not_scheduled',
                                    'Not scheduled'
                                )}
                            </span>
                        );
                    }
                    return (
                        <span className="text-wp-text">
                            {new Date(value).toLocaleDateString()}
                        </span>
                    );
                },
                size: 150,
            }),
        ],
        [
            getString,
            selectedItems,
            filteredData,
            searchTerm,
            getPostEditUrl,
            handleGenerate,
            tasks,
        ]
    );

    // Table instance
    // Expanded row content renderer
    const renderExpandedRow = (row: Row<ContentPlanItem>) => {
        const item = row.original;
        return (
            <div className="p-3 sm:p-4 bg-gray-50">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 max-w-2xl">
                    <div>
                        <h4 className="text-xs sm:text-sm font-medium text-gray-500">
                            {getString('table_columns', 'created', 'Created')}
                        </h4>
                        <p className="mt-1 text-xs sm:text-sm text-gray-900">
                            {new Date(item.created_at).toLocaleDateString()}
                        </p>
                    </div>
                    <div>
                        <h4 className="text-xs sm:text-sm font-medium text-gray-500">
                            {getString(
                                'table_columns',
                                'last_modified',
                                'Last Modified'
                            )}
                        </h4>
                        <p className="mt-1 text-xs sm:text-sm text-gray-900">
                            {new Date(
                                item.updated_at || item.created_at
                            ).toLocaleDateString()}
                        </p>
                    </div>
                    {item.lang && (
                        <div>
                            <h4 className="text-xs sm:text-sm font-medium text-gray-500">
                                {getString(
                                    'table_columns',
                                    'language',
                                    'Language'
                                )}
                            </h4>
                            <p className="mt-1 text-xs sm:text-sm text-gray-900">
                                {(() => {
                                    const languageOption =
                                        LANGUAGE_OPTIONS.find(
                                            opt => opt.value === item.lang
                                        );
                                    return languageOption
                                        ? languageOption.label
                                        : item.lang;
                                })()}
                            </p>
                        </div>
                    )}
                </div>
            </div>
        );
    };

    const table = useReactTable({
        data: filteredData,
        columns,
        state: {
            expanded,
            sorting,
            pagination,
            columnVisibility,
        },
        onExpandedChange: updater => {
            if (typeof updater === 'function') {
                setExpanded(prev => updater(prev));
            } else {
                setExpanded(updater);
            }
        },
        onSortingChange: setSorting,
        onPaginationChange: setPagination,
        onColumnVisibilityChange: setColumnVisibility,
        manualPagination: false,
        autoResetPageIndex: true,
        getRowCanExpand: () => true,
        getCoreRowModel: getCoreRowModel(),
        getSortedRowModel: getSortedRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
        getExpandedRowModel: getExpandedRowModel(),
    });

    // Event handlers
    const handleEdit = (item: ContentPlanItem): void => {
        // Dispatch event to ContentPlanItemSidebar with the item data
        window.dispatchEvent(
            new CustomEvent('editContentPlanItem', {
                detail: { item },
            })
        );
        openSidebar('content-plan-item');
    };

    const handleDelete = (item: ContentPlanItem): void => {
        setItemToDelete(item);
        setDeleteModalOpen(true);
    };

    const handleDeleteItem = useCallback(
        async (itemId: number): Promise<void> => {
            try {
                await deleteContentPlanItemAPI(itemId, currentPlanId);
            } catch (err) {
                // Error is handled by context
                console.error('Error deleting item:', err);
            }
        },
        [deleteContentPlanItemAPI, currentPlanId]
    );

    const handleBulkDelete = useCallback(async (): Promise<void> => {
        if (selectedItems.size === 0) return;

        try {
            await bulkDeleteContentPlanItems(
                Array.from(selectedItems),
                currentPlanId
            );
            setSelectedItems(new Set()); // Clear selection after successful deletion
        } catch (err) {
            // Error is handled by context
            console.error('Error bulk deleting items:', err);
        }
    }, [bulkDeleteContentPlanItems, selectedItems, currentPlanId]);

    // Get task filter item IDs
    const taskFilterItemIds = useMemo(() => {
        if (!taskFilterId) return null;
        const task = tasks.find(t => t.id === taskFilterId);
        if (!task) return null;

        // For content plan generation tasks: use item_ids array
        const itemIds = task.result?.output?.item_ids;
        if (itemIds && Array.isArray(itemIds) && itemIds.length > 0) {
            return itemIds;
        }

        // For post generation tasks: use single item_id from input
        const itemId = task.result?.input?.item_id;
        if (itemId !== undefined && itemId !== null) {
            return [itemId];
        }

        return null;
    }, [taskFilterId, tasks]);

    // Filter data based on search term, date range, and task filter
    const applyFilters = useCallback(
        (
            items: ContentPlanItem[],
            search: string,
            startDate: Date | null,
            endDate: Date | null,
            itemIds: number[] | null
        ): ContentPlanItem[] => {
            let filtered = items;

            // Apply task filter first (by item IDs)
            if (itemIds && itemIds.length > 0) {
                filtered = filtered.filter(item => itemIds.includes(item.id));
            }

            // Apply search filter
            if (search.trim()) {
                const searchLower = search.toLowerCase();
                filtered = filtered.filter(
                    item =>
                        item.title?.toLowerCase().includes(searchLower) ||
                        item.structure?.toLowerCase().includes(searchLower) ||
                        item.keywords?.toLowerCase().includes(searchLower)
                );
            }

            // Apply date range filter
            if (startDate || endDate) {
                filtered = filtered.filter(item => {
                    if (!item.scheduled_on) return false;

                    try {
                        // Parse the scheduled date string and normalize to date only (ignore time)
                        // Handle both "YYYY-MM-DD HH:MM:SS" and "YYYY-MM-DD" formats, and Date objects
                        let scheduledDateStr: string;
                        if (typeof item.scheduled_on === 'string') {
                            scheduledDateStr = item.scheduled_on.split(' ')[0]; // Get just the date part "YYYY-MM-DD"
                        } else {
                            // If it's already a Date object or timestamp, convert to string first
                            const dateObj = new Date(item.scheduled_on);
                            scheduledDateStr = dateObj
                                .toISOString()
                                .split('T')[0];
                        }

                        const [year, month, day] = scheduledDateStr
                            .split('-')
                            .map(Number);

                        // Create date in local timezone to avoid timezone issues
                        const itemDate = new Date(year, month - 1, day); // month is 0-indexed
                        itemDate.setHours(0, 0, 0, 0);

                        if (startDate) {
                            const start = new Date(startDate);
                            start.setHours(0, 0, 0, 0);
                            // Compare dates only (ignore time)
                            if (itemDate.getTime() < start.getTime())
                                return false;
                        }

                        if (endDate) {
                            const end = new Date(endDate);
                            end.setHours(23, 59, 59, 999);
                            // Compare dates only (ignore time)
                            if (itemDate.getTime() > end.getTime())
                                return false;
                        }

                        return true;
                    } catch (error) {
                        // If date parsing fails, exclude the item
                        console.error(
                            'Error parsing scheduled date:',
                            item.scheduled_on,
                            error
                        );
                        return false;
                    }
                });
            }

            return filtered;
        },
        []
    );

    // Search functionality
    const handleSearch = useCallback((term: string): void => {
        setSearchTerm(term);
    }, []);

    // Debounce search input
    useEffect(() => {
        const id = setTimeout(() => {
            const filtered = applyFilters(
                contentPlan.contentPlanItems,
                searchTerm,
                dateRangeStart,
                dateRangeEnd,
                taskFilterItemIds
            );
            setFilteredData(filtered);
        }, 300);
        return () => clearTimeout(id);
    }, [
        searchTerm,
        contentPlan.contentPlanItems,
        dateRangeStart,
        dateRangeEnd,
        taskFilterItemIds,
        applyFilters,
    ]);

    // Helper: filter to valid dates only (prevents "Invalid time value" in DatePicker)
    const getValidDatesFromItems = useCallback(
        (items: typeof contentPlan.contentPlanItems): Date[] => {
            return items
                .filter(item => item.scheduled_on)
                .map(item => new Date(item.scheduled_on!))
                .filter(d => !isNaN(d.getTime()));
        },
        []
    );

    // Helper functions to get min/max dates from items
    const getMinDateFromItems = useCallback((): Date | null => {
        const validDates = getValidDatesFromItems(contentPlan.contentPlanItems);
        if (validDates.length === 0) return null;
        return new Date(Math.min(...validDates.map(d => d.getTime())));
    }, [contentPlan.contentPlanItems, getValidDatesFromItems]);

    const getMaxDateFromItems = useCallback((): Date | null => {
        const validDates = getValidDatesFromItems(contentPlan.contentPlanItems);
        if (validDates.length === 0) return null;
        return new Date(Math.max(...validDates.map(d => d.getTime())));
    }, [contentPlan.contentPlanItems, getValidDatesFromItems]);

    // Get minimum date from items that are in the past (before today)
    const getMinPastDateFromItems = useCallback((): Date | null => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const pastDates = getValidDatesFromItems(
            contentPlan.contentPlanItems
        ).filter(d => {
            const dNorm = new Date(d);
            dNorm.setHours(0, 0, 0, 0);
            return dNorm < today;
        });

        if (pastDates.length === 0) return null;
        return new Date(Math.min(...pastDates.map(d => d.getTime())));
    }, [contentPlan.contentPlanItems, getValidDatesFromItems]);

    // Date range change handlers
    const handleDateRangeChange = useCallback(
        (dates: [Date | null, Date | null] | Date | null): void => {
            if (!Array.isArray(dates)) {
                setDatePreset('custom');
                setDateRangeStart(dates);
                setDateRangeEnd(null);
                return;
            }
            const [start, end] = dates;
            setDatePreset('custom');
            setDateRangeStart(start);
            setDateRangeEnd(end);
            const filtered = applyFilters(
                contentPlan.contentPlanItems,
                searchTerm,
                start,
                end,
                taskFilterItemIds
            );
            setFilteredData(filtered);
        },
        [
            contentPlan.contentPlanItems,
            searchTerm,
            applyFilters,
            taskFilterItemIds,
        ]
    );

    // Preset change handler
    const handlePresetChange = useCallback(
        (preset: string): void => {
            setDatePreset(preset);

            let newStartDate: Date | null = null;
            let newEndDate: Date | null = null;

            if (preset === 'future') {
                // Future posts: current day to maximum date
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                newStartDate = today;
                newEndDate = getMaxDateFromItems();
            } else if (preset === 'past') {
                // Past posts: minimum date from past items to yesterday
                const yesterday = new Date();
                yesterday.setDate(yesterday.getDate() - 1);
                yesterday.setHours(23, 59, 59, 999);

                // Get minimum date from past items, or fallback to minimum from all items
                // but ensure it's not in the future (clamp to yesterday if needed)
                let minPastDate = getMinPastDateFromItems();
                if (!minPastDate) {
                    // If no past items found, try using minimum from all items
                    const minDate = getMinDateFromItems();
                    if (minDate && minDate <= yesterday) {
                        minPastDate = minDate;
                    } else {
                        // Fallback: use 1 year ago if no valid date found
                        minPastDate = new Date();
                        minPastDate.setFullYear(minPastDate.getFullYear() - 1);
                        minPastDate.setHours(0, 0, 0, 0);
                    }
                }

                // Ensure start date is not after end date
                if (minPastDate && minPastDate > yesterday) {
                    newStartDate = yesterday;
                    newEndDate = yesterday;
                } else {
                    newStartDate = minPastDate;
                    newEndDate = yesterday;
                }
            }
            // For "custom", don't change the dates

            if (preset !== 'custom') {
                setDateRangeStart(newStartDate);
                setDateRangeEnd(newEndDate);
                const filtered = applyFilters(
                    contentPlan.contentPlanItems,
                    searchTerm,
                    newStartDate,
                    newEndDate,
                    taskFilterItemIds
                );
                setFilteredData(filtered);
            }
        },
        [
            contentPlan.contentPlanItems,
            searchTerm,
            applyFilters,
            getMinDateFromItems,
            getMaxDateFromItems,
            getMinPastDateFromItems,
            taskFilterItemIds,
        ]
    );

    // Initialize default date range (future posts preset)
    useEffect(() => {
        if (
            contentPlan.contentPlanItems.length > 0 &&
            !dateRangeStart &&
            !dateRangeEnd
        ) {
            // Initialize with "future" preset
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const maxDate = getMaxDateFromItems();

            setDateRangeStart(today);
            setDateRangeEnd(maxDate);
            setDatePreset('future');
        }
    }, [
        contentPlan.contentPlanItems,
        dateRangeStart,
        dateRangeEnd,
        getMaxDateFromItems,
    ]);

    // Update date range when items are added and preset is "future" or "past"
    useEffect(() => {
        if (
            contentPlan.contentPlanItems.length > 0 &&
            datePreset !== 'custom'
        ) {
            if (datePreset === 'future') {
                // Update end date to include new items
                const maxDate = getMaxDateFromItems();
                if (maxDate) {
                    setDateRangeEnd(currentEnd => {
                        if (!currentEnd || maxDate > currentEnd) {
                            return maxDate;
                        }
                        return currentEnd;
                    });
                }
            } else if (datePreset === 'past') {
                // Ensure end date is always yesterday for past posts
                const yesterday = new Date();
                yesterday.setDate(yesterday.getDate() - 1);
                yesterday.setHours(23, 59, 59, 999);
                setDateRangeEnd(yesterday);

                // Update start date to include new past items (earlier dates)
                let minPastDate = getMinPastDateFromItems();
                if (!minPastDate) {
                    // Fallback: use minimum from all items if it's in the past
                    const minDate = getMinDateFromItems();
                    if (minDate && minDate <= yesterday) {
                        minPastDate = minDate;
                    } else {
                        // Fallback: use 1 year ago
                        minPastDate = new Date();
                        minPastDate.setFullYear(minPastDate.getFullYear() - 1);
                        minPastDate.setHours(0, 0, 0, 0);
                    }
                }

                if (minPastDate) {
                    setDateRangeStart(currentStart => {
                        if (!currentStart || minPastDate! < currentStart) {
                            return minPastDate!;
                        }
                        return currentStart;
                    });
                }
            }
        }
    }, [
        contentPlan.contentPlanItems.length,
        datePreset,
        getMaxDateFromItems,
        getMinDateFromItems,
        getMinPastDateFromItems,
    ]);

    // Update filtered data when data changes
    useEffect(() => {
        const filtered = applyFilters(
            contentPlan.contentPlanItems,
            searchTerm,
            dateRangeStart,
            dateRangeEnd,
            taskFilterItemIds
        );
        setFilteredData(filtered);
    }, [
        contentPlan.contentPlanItems,
        searchTerm,
        dateRangeStart,
        dateRangeEnd,
        taskFilterItemIds,
        applyFilters,
    ]);

    // Load data on component mount - now handled by context
    // useEffect(() => {
    //   fetchContentPlanItems(currentPlanId);
    // }, [fetchContentPlanItems, currentPlanId]);

    // Listen for refresh events from the sidebar
    useEffect(() => {
        const handleRefresh = (): void => {
            fetchContentPlanItems(currentPlanId);
        };

        const handleDelete = (event: CustomEvent): void => {
            const { itemId } = event.detail;
            if (itemId) {
                handleDeleteItem(itemId);
            }
        };

        window.addEventListener('contentPlanItemUpdated', handleRefresh);
        window.addEventListener(
            'deleteContentPlanItem',
            handleDelete as EventListener
        );
        return () => {
            window.removeEventListener('contentPlanItemUpdated', handleRefresh);
            window.removeEventListener(
                'deleteContentPlanItem',
                handleDelete as EventListener
            );
        };
    }, [fetchContentPlanItems, currentPlanId, handleDeleteItem]);

    // Scroll to table when task filter is applied
    useEffect(() => {
        if (
            taskFilterId &&
            tableContainerRef.current &&
            filteredData.length > 0
        ) {
            // Use setTimeout to ensure the DOM has updated with filtered data
            setTimeout(() => {
                tableContainerRef.current?.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                });
            }, 100);
        }
    }, [taskFilterId, filteredData.length]);

    if (loading && contentPlan.contentPlanItems.length === 0) {
        return (
            <div className="flex items-center justify-center py-8">
                <div className="cpepai-spinner"></div>
                <span className="ml-2">
                    {getString(
                        'content_plan_table',
                        'loading_items',
                        'Loading content plan items...'
                    )}
                </span>
            </div>
        );
    }

    return (
        <div className="space-y-4 sm:space-y-6">
            {/* Header */}
            <div className="flex justify-between items-center mb-3 sm:mb-4">
                <h3 className="text-base sm:text-lg font-medium text-wp-text">
                    {getString(
                        'content_plan_table',
                        'content_plan_items',
                        'Content Plan Items'
                    )}
                </h3>
            </div>

            {/* Action Bar - Buttons and Search */}
            <div className="flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-3 sm:gap-0 mb-4">
                {/* Left side - Buttons */}
                <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 w-full sm:w-auto">
                    {(() => {
                        // Check if there are any pending tasks (queued or processing)
                        const hasPendingTasks = tasks.some(
                            task =>
                                task.status === 'queued' ||
                                task.status === 'processing'
                        );

                        const buttonText = getString(
                            'app',
                            'generate_content_plan',
                            'Generate content plan with AI'
                        );
                        const button = (
                            <button
                                className={`cpepai-button cpepai-button--secondary w-full sm:w-auto text-sm sm:text-base ${
                                    hasPendingTasks
                                        ? 'opacity-50 cursor-not-allowed'
                                        : ''
                                }`}
                                onClick={
                                    hasPendingTasks
                                        ? undefined
                                        : openGenerationModal
                                }
                                disabled={hasPendingTasks}
                                title={
                                    hasPendingTasks
                                        ? getString(
                                              'content_plan_table',
                                              'generation_disabled_pending_task',
                                              'Please wait for the current task to complete'
                                          )
                                        : undefined
                                }
                            >
                                {buttonText}
                            </button>
                        );

                        return (
                            <Tooltip
                                show={showTutorial}
                                tooltipId="generate-ai"
                                currentTooltipId={currentTooltipId}
                                content="Start here. AI will analyze your site and create a complete content plan with topics, structure, and publish dates."
                                hint="Recommended for first-time users"
                                position="bottom"
                                onDismiss={onTooltipDismiss}
                                currentIndex={
                                    currentTooltipIndex !== undefined
                                        ? currentTooltipIndex + 1
                                        : undefined
                                }
                                totalCount={totalTooltipCount}
                                onSkip={onSkipTutorial}
                            >
                                {button}
                            </Tooltip>
                        );
                    })()}
                    <Tooltip
                        show={showTutorial}
                        tooltipId="schedule-manual"
                        currentTooltipId={currentTooltipId}
                        content="Already have ideas? Add a single post manually and schedule it without using AI."
                        position="bottom"
                        onDismiss={onTooltipDismiss}
                        currentIndex={
                            currentTooltipIndex !== undefined
                                ? currentTooltipIndex + 1
                                : undefined
                        }
                        totalCount={totalTooltipCount}
                        onSkip={onSkipTutorial}
                    >
                        <button
                            onClick={() => openSidebar('content-plan-item')}
                            className="cpepai-button w-full sm:w-auto text-sm sm:text-base"
                        >
                            {getString(
                                'content_plan_table',
                                'add_new_item',
                                'Schedule new post manually'
                            )}
                        </button>
                    </Tooltip>
                </div>

                {/* Right side - Search */}
                <div className="flex-1 sm:flex-initial sm:max-w-md sm:ml-4">
                    <input
                        type="text"
                        placeholder={getString(
                            'content_plan_table',
                            'search_placeholder',
                            'Search content plan items...'
                        )}
                        value={searchTerm}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            handleSearch(e.target.value)
                        }
                        className="w-full h-10 sm:h-12 px-2 sm:px-3 py-2 sm:py-3 text-sm sm:text-base border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                </div>
            </div>

            {/* Content Plan Summary */}
            <div className="mb-4 p-3 sm:p-4 bg-gray-50 rounded-lg">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-0">
                    <div className="text-xs sm:text-sm text-gray-600">
                        <span className="font-medium">
                            {contentPlan.contentPlanItems.length}
                        </span>{' '}
                        {getString(
                            'content_plan_table',
                            'content_plan_items_lower',
                            'content plan items'
                        )}
                        {getLatestContentPlanDate() && (
                            <>
                                {' '}
                                {getString(
                                    'content_plan_table',
                                    'scheduled_until',
                                    'scheduled until'
                                )}{' '}
                                <span className="font-medium text-gray-800">
                                    {getLatestContentPlanDate()}
                                </span>
                            </>
                        )}
                    </div>
                    <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 w-full sm:w-auto">
                        {/* Task Filter Indicator */}
                        {taskFilterId && taskFilterItemIds && (
                            <div className="flex items-center gap-2 px-2 sm:px-3 py-1 bg-blue-100 border border-blue-300 rounded text-xs sm:text-sm">
                                <svg
                                    className="w-3 h-3 sm:w-4 sm:h-4 text-blue-600 flex-shrink-0"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        strokeWidth={2}
                                        d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
                                    />
                                </svg>
                                <span className="text-blue-800 font-medium break-words">
                                    {getString(
                                        'content_plan_table',
                                        'task_filter_active',
                                        `Task filter: ${taskFilterItemIds.length} item${taskFilterItemIds.length === 1 ? '' : 's'}`
                                    )}
                                </span>
                                <button
                                    onClick={clearTaskFilter}
                                    className="text-blue-600 hover:text-blue-800 ml-1 flex-shrink-0"
                                    title={getString(
                                        'content_plan_table',
                                        'clear_task_filter',
                                        'Clear task filter'
                                    )}
                                >
                                    <svg
                                        className="w-3 h-3 sm:w-4 sm:h-4"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M6 18L18 6M6 6l12 12"
                                        />
                                    </svg>
                                </button>
                            </div>
                        )}
                        {taskFilterId && (
                            <span className="hidden sm:inline text-gray-400">
                                |
                            </span>
                        )}
                        <div className="flex items-center gap-2 flex-wrap">
                            <label className="text-xs sm:text-sm text-gray-600 whitespace-nowrap">
                                {getString(
                                    'content_plan_table',
                                    'date_filter',
                                    'Date filter'
                                )}
                                :
                            </label>
                            <select
                                value={datePreset}
                                onChange={e =>
                                    handlePresetChange(e.target.value)
                                }
                                className="px-2 sm:px-3 py-1 text-xs sm:text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-primary cursor-pointer"
                            >
                                <option value="future">
                                    {getString(
                                        'content_plan_table',
                                        'future_posts',
                                        'Future posts'
                                    )}
                                </option>
                                <option value="past">
                                    {getString(
                                        'content_plan_table',
                                        'past_posts',
                                        'Past posts'
                                    )}
                                </option>
                                <option value="custom">
                                    {getString(
                                        'content_plan_table',
                                        'custom',
                                        'Custom'
                                    )}
                                </option>
                            </select>
                            <span className="hidden sm:inline text-gray-400">
                                |
                            </span>
                            <DatePicker
                                selected={
                                    dateRangeStart &&
                                    !isNaN(dateRangeStart.getTime())
                                        ? dateRangeStart
                                        : null
                                }
                                onChange={handleDateRangeChange}
                                startDate={
                                    dateRangeStart &&
                                    !isNaN(dateRangeStart.getTime())
                                        ? dateRangeStart
                                        : null
                                }
                                endDate={
                                    dateRangeEnd &&
                                    !isNaN(dateRangeEnd.getTime())
                                        ? dateRangeEnd
                                        : null
                                }
                                selectsRange
                                dateFormat="MMM d, yyyy"
                                placeholderText={getString(
                                    'content_plan_table',
                                    'select_date_range',
                                    'Select date range'
                                )}
                                className="px-2 py-1 text-xs sm:text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-primary cursor-pointer w-full sm:w-60"
                                wrapperClassName="inline-block w-full sm:w-auto"
                                calendarClassName="react-datepicker-popper"
                            />
                        </div>
                    </div>
                </div>
            </div>

            {/* Error Display */}
            {error && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="flex items-center justify-between">
                        <span className="text-red-800">{error}</span>
                        <button
                            onClick={() => {
                                /* Error will be cleared by context */
                            }}
                            className="text-red-600 hover:text-red-700"
                        >
                            <svg
                                className="w-4 h-4"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M6 18L18 6M6 6l12 12"
                                />
                            </svg>
                        </button>
                    </div>
                </div>
            )}

            {/* Table Container */}
            <Tooltip
                show={showTutorial}
                tooltipId="content-plan-header"
                currentTooltipId={currentTooltipId}
                content="This is your content roadmap. Once generated, all your planned posts will appear here."
                position="top"
                onDismiss={onTooltipDismiss}
                currentIndex={
                    currentTooltipIndex !== undefined
                        ? currentTooltipIndex + 1
                        : undefined
                }
                totalCount={totalTooltipCount}
                onSkip={onSkipTutorial}
            >
                <div
                    ref={tableContainerRef}
                    className="bg-white border border-gray-200 rounded-lg overflow-hidden relative"
                >
                    {/* Table - Desktop View */}
                    <div className="hidden md:block">
                        <div className="overflow-x-auto max-h-[60vh] sm:max-h-[70vh] overflow-y-auto">
                            <table
                                className="min-w-full divide-y divide-gray-200"
                                style={{ tableLayout: 'fixed' }}
                            >
                                <thead className="bg-gray-50 sticky top-0 z-10">
                                    {table
                                        .getHeaderGroups()
                                        .map(headerGroup => (
                                            <tr key={headerGroup.id}>
                                                {headerGroup.headers.map(
                                                    header => (
                                                        <th
                                                            key={header.id}
                                                            onClick={header.column.getToggleSortingHandler?.()}
                                                            className={`px-3 sm:px-4 md:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider select-none cursor-pointer ${
                                                                header.column
                                                                    .id ===
                                                                'title'
                                                                    ? '!w-[200px]'
                                                                    : ''
                                                            }`}
                                                            style={{
                                                                width:
                                                                    header
                                                                        .column
                                                                        .id ===
                                                                    'title'
                                                                        ? '200px'
                                                                        : header
                                                                                .column
                                                                                .id ===
                                                                            'structure'
                                                                          ? '300px'
                                                                          : header
                                                                                  .column
                                                                                  .id ===
                                                                              'keywords'
                                                                            ? '200px'
                                                                            : header
                                                                                    .column
                                                                                    .id ===
                                                                                'status'
                                                                              ? '150px'
                                                                              : header
                                                                                      .column
                                                                                      .id ===
                                                                                  'scheduled_on'
                                                                                ? '150px'
                                                                                : header
                                                                                        .column
                                                                                        .id ===
                                                                                    'post'
                                                                                  ? '150px'
                                                                                  : header
                                                                                          .column
                                                                                          .id ===
                                                                                      'actions'
                                                                                    ? '120px'
                                                                                    : header
                                                                                            .column
                                                                                            .id ===
                                                                                        'id'
                                                                                      ? '60px'
                                                                                      : header.getSize(),
                                                            }}
                                                        >
                                                            {header.isPlaceholder ? null : (
                                                                <div className="flex items-center gap-1">
                                                                    {flexRender(
                                                                        header
                                                                            .column
                                                                            .columnDef
                                                                            .header,
                                                                        header.getContext()
                                                                    )}
                                                                    {header.column.getIsSorted() ===
                                                                        'asc' && (
                                                                        <svg
                                                                            className="w-3 h-3"
                                                                            viewBox="0 0 20 20"
                                                                            fill="currentColor"
                                                                        >
                                                                            <path d="M10 6l-4 6h8l-4-6z" />
                                                                        </svg>
                                                                    )}
                                                                    {header.column.getIsSorted() ===
                                                                        'desc' && (
                                                                        <svg
                                                                            className="w-3 h-3 rotate-180"
                                                                            viewBox="0 0 20 20"
                                                                            fill="currentColor"
                                                                        >
                                                                            <path d="M10 6l-4 6h8l-4-6z" />
                                                                        </svg>
                                                                    )}
                                                                </div>
                                                            )}
                                                        </th>
                                                    )
                                                )}
                                            </tr>
                                        ))}
                                </thead>
                                <tbody className="bg-white divide-y divide-gray-200">
                                    {table.getRowModel().rows.length === 0 ? (
                                        <tr>
                                            <td
                                                colSpan={
                                                    table
                                                        .getAllColumns()
                                                        .filter(col =>
                                                            col.getIsVisible()
                                                        ).length
                                                }
                                                className="px-3 sm:px-4 md:px-6 py-12 sm:py-16 text-center"
                                            >
                                                <div className="flex flex-col items-center justify-center space-y-4">
                                                    <svg
                                                        className="w-12 h-12 sm:w-16 sm:h-16 text-gray-400"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        viewBox="0 0 24 24"
                                                    >
                                                        <path
                                                            strokeLinecap="round"
                                                            strokeLinejoin="round"
                                                            strokeWidth={2}
                                                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                                                        />
                                                    </svg>
                                                    <p className="text-sm sm:text-base text-gray-600">
                                                        {getString(
                                                            'content_plan_table',
                                                            'no_items',
                                                            'No content plan items yet'
                                                        )}
                                                    </p>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : (
                                        table.getRowModel().rows.map(row => (
                                            <React.Fragment key={row.id}>
                                                <tr
                                                    className={`hover:bg-gray-50 ${
                                                        selectedItems.has(
                                                            row.original.id
                                                        )
                                                            ? 'bg-blue-50'
                                                            : ''
                                                    }`}
                                                >
                                                    {row
                                                        .getVisibleCells()
                                                        .map(cell => (
                                                            <td
                                                                key={cell.id}
                                                                className={`px-3 sm:px-4 md:px-6 py-3 sm:py-4 text-xs sm:text-sm ${
                                                                    cell.column
                                                                        .id ===
                                                                    'title'
                                                                        ? '!w-[200px] break-words'
                                                                        : 'whitespace-nowrap'
                                                                }`}
                                                                style={{
                                                                    width:
                                                                        cell
                                                                            .column
                                                                            .id ===
                                                                        'title'
                                                                            ? '200px'
                                                                            : cell
                                                                                    .column
                                                                                    .id ===
                                                                                'structure'
                                                                              ? '300px'
                                                                              : cell
                                                                                      .column
                                                                                      .id ===
                                                                                  'keywords'
                                                                                ? '200px'
                                                                                : cell
                                                                                        .column
                                                                                        .id ===
                                                                                    'status'
                                                                                  ? '150px'
                                                                                  : cell
                                                                                          .column
                                                                                          .id ===
                                                                                      'scheduled_on'
                                                                                    ? '150px'
                                                                                    : cell
                                                                                            .column
                                                                                            .id ===
                                                                                        'post'
                                                                                      ? '150px'
                                                                                      : cell
                                                                                              .column
                                                                                              .id ===
                                                                                          'actions'
                                                                                        ? '120px'
                                                                                        : cell
                                                                                                .column
                                                                                                .id ===
                                                                                            'id'
                                                                                          ? '60px'
                                                                                          : undefined,
                                                                }}
                                                            >
                                                                {flexRender(
                                                                    cell.column
                                                                        .columnDef
                                                                        .cell,
                                                                    cell.getContext()
                                                                )}
                                                            </td>
                                                        ))}
                                                </tr>
                                                {row.getIsExpanded() && (
                                                    <tr
                                                        className={
                                                            selectedItems.has(
                                                                row.original.id
                                                            )
                                                                ? 'bg-blue-50'
                                                                : ''
                                                        }
                                                    >
                                                        <td
                                                            colSpan={
                                                                row.getVisibleCells()
                                                                    .length
                                                            }
                                                        >
                                                            {renderExpandedRow(
                                                                row
                                                            )}
                                                        </td>
                                                    </tr>
                                                )}
                                            </React.Fragment>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Mobile Card View */}
                    <div className="md:hidden space-y-3 p-3">
                        {table.getRowModel().rows.length === 0 ? (
                            <div className="bg-white border border-gray-200 rounded-lg p-8 text-center">
                                <div className="flex flex-col items-center justify-center space-y-4">
                                    <svg
                                        className="w-12 h-12 text-gray-400"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                                        />
                                    </svg>
                                    <p className="text-sm text-gray-600">
                                        {getString(
                                            'content_plan_table',
                                            'no_items',
                                            'No content plan items yet'
                                        )}
                                    </p>
                                </div>
                            </div>
                        ) : (
                            table.getRowModel().rows.map(row => {
                                const item = row.original;
                                const status =
                                    (item as any).status || 'planned';
                                const isPlanned = status === 'planned';
                                const isDraftReadyAi =
                                    status === 'draft_ready_ai';
                                const statusClasses = {
                                    planned: 'bg-gray-100 text-gray-800',
                                    draft_ready_ai: 'bg-blue-100 text-blue-800',
                                    draft_ready_manual:
                                        'bg-green-100 text-green-800',
                                    published: 'bg-purple-100 text-purple-800',
                                };

                                return (
                                    <div
                                        key={row.id}
                                        className={`bg-white border border-gray-200 rounded-lg p-4 ${
                                            selectedItems.has(item.id)
                                                ? 'bg-blue-50 border-blue-200'
                                                : ''
                                        }`}
                                    >
                                        {/* Header Row */}
                                        <div className="flex items-start justify-between mb-3">
                                            <div className="flex items-start gap-2 flex-1 min-w-0">
                                                <input
                                                    type="checkbox"
                                                    checked={selectedItems.has(
                                                        item.id
                                                    )}
                                                    onChange={e => {
                                                        const newSelected =
                                                            new Set(
                                                                selectedItems
                                                            );
                                                        if (e.target.checked) {
                                                            newSelected.add(
                                                                item.id
                                                            );
                                                        } else {
                                                            newSelected.delete(
                                                                item.id
                                                            );
                                                        }
                                                        setSelectedItems(
                                                            newSelected
                                                        );
                                                    }}
                                                    className="w-4 h-4 cursor-pointer mt-1 flex-shrink-0"
                                                />
                                                <div className="flex-1 min-w-0">
                                                    <h3 className="font-medium text-wp-text text-sm mb-1 break-words">
                                                        {item.title ||
                                                            getString(
                                                                'table_cells',
                                                                'untitled',
                                                                'Untitled'
                                                            )}
                                                    </h3>
                                                    <div className="flex items-center gap-2 flex-wrap">
                                                        <span
                                                            className={`px-2 py-0.5 text-xs font-medium rounded-full ${
                                                                statusClasses[
                                                                    status as keyof typeof statusClasses
                                                                ] ||
                                                                statusClasses.planned
                                                            }`}
                                                        >
                                                            {getString(
                                                                `status_${status}`,
                                                                'label',
                                                                status
                                                                    .replace(
                                                                        /_/g,
                                                                        ' '
                                                                    )
                                                                    .replace(
                                                                        /\b\w/g,
                                                                        (
                                                                            l: string
                                                                        ) =>
                                                                            l.toUpperCase()
                                                                    )
                                                            )}
                                                        </span>
                                                        {item.scheduled_on && (
                                                            <span className="text-xs text-gray-600">
                                                                {(() => {
                                                                    const d =
                                                                        new Date(
                                                                            item.scheduled_on!
                                                                        );
                                                                    return !isNaN(
                                                                        d.getTime()
                                                                    )
                                                                        ? d.toLocaleDateString()
                                                                        : '—';
                                                                })()}
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Structure - Collapsible */}
                                        {item.structure && (
                                            <div className="mb-3">
                                                <StructureDisplay
                                                    structure={item.structure}
                                                    getString={getString}
                                                    maxWidth="max-w-full"
                                                    layout="vertical"
                                                />
                                            </div>
                                        )}

                                        {/* Keywords */}
                                        {item.keywords && (
                                            <div className="mb-3">
                                                <KeywordDisplay
                                                    keywords={item.keywords}
                                                    getString={getString}
                                                    maxWidth="max-w-full"
                                                    alwaysShowAll={false}
                                                />
                                            </div>
                                        )}

                                        {/* Language */}
                                        {item.lang && (
                                            <div className="mb-3">
                                                <h4 className="text-xs sm:text-sm font-medium text-gray-500 mb-1">
                                                    {getString(
                                                        'table_columns',
                                                        'language',
                                                        'Language'
                                                    )}
                                                    :
                                                </h4>
                                                <p className="text-xs sm:text-sm text-gray-900">
                                                    {(() => {
                                                        const languageOption =
                                                            LANGUAGE_OPTIONS.find(
                                                                opt =>
                                                                    opt.value ===
                                                                    item.lang
                                                            );
                                                        return languageOption
                                                            ? languageOption.label
                                                            : item.lang;
                                                    })()}
                                                </p>
                                            </div>
                                        )}

                                        {/* Post Link */}
                                        {status !== 'planned' && item.post && (
                                            <div className="mb-3">
                                                {(() => {
                                                    const editUrl =
                                                        getPostEditUrl(
                                                            item.post
                                                        );
                                                    if (editUrl) {
                                                        return (
                                                            <a
                                                                href={editUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                className="flex items-center gap-1 text-primary hover:text-primary-dark text-xs font-medium underline"
                                                            >
                                                                <svg
                                                                    className="w-3 h-3"
                                                                    fill="none"
                                                                    stroke="currentColor"
                                                                    viewBox="0 0 24 24"
                                                                >
                                                                    <path
                                                                        strokeLinecap="round"
                                                                        strokeLinejoin="round"
                                                                        strokeWidth={
                                                                            2
                                                                        }
                                                                        d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                                                                    />
                                                                </svg>
                                                                {getString(
                                                                    'table_cells',
                                                                    'view_post',
                                                                    'View Post'
                                                                )}
                                                            </a>
                                                        );
                                                    }
                                                    return null;
                                                })()}
                                            </div>
                                        )}

                                        {/* Actions */}
                                        <div className="flex flex-col gap-2 pt-3 border-t border-gray-200">
                                            {/* Generate/Regenerate buttons */}
                                            <div
                                                className="flex items-center gap-2"
                                                style={{ maxWidth: '200px' }}
                                            >
                                                {(() => {
                                                    // Check if there are any pending tasks (queued or processing)
                                                    const hasPendingTasks =
                                                        tasks.some(
                                                            task =>
                                                                task.status ===
                                                                    'queued' ||
                                                                task.status ===
                                                                    'processing'
                                                        );
                                                    return (
                                                        <>
                                                            {isPlanned && (
                                                                <button
                                                                    onClick={
                                                                        hasPendingTasks
                                                                            ? undefined
                                                                            : () =>
                                                                                  handleGenerate(
                                                                                      item
                                                                                  )
                                                                    }
                                                                    disabled={
                                                                        hasPendingTasks
                                                                    }
                                                                    className={`flex items-center gap-1 text-orange-500 hover:text-orange-600 text-xs font-bold bg-white px-2 py-1 rounded border border-orange-200 w-full ${
                                                                        hasPendingTasks
                                                                            ? 'opacity-50 cursor-not-allowed'
                                                                            : ''
                                                                    }`}
                                                                    title={
                                                                        hasPendingTasks
                                                                            ? getString(
                                                                                  'table_cells',
                                                                                  'generation_disabled_pending_task',
                                                                                  'Please wait for the current task to complete'
                                                                              )
                                                                            : getString(
                                                                                  'table_cells',
                                                                                  'generate',
                                                                                  'Generate'
                                                                              )
                                                                    }
                                                                >
                                                                    <svg
                                                                        className="w-3 h-3"
                                                                        fill="none"
                                                                        stroke="currentColor"
                                                                        viewBox="0 0 24 24"
                                                                    >
                                                                        <path
                                                                            strokeLinecap="round"
                                                                            strokeLinejoin="round"
                                                                            strokeWidth={
                                                                                2
                                                                            }
                                                                            d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
                                                                        />
                                                                    </svg>
                                                                    {getString(
                                                                        'table_cells',
                                                                        'generate',
                                                                        'Generate'
                                                                    )}
                                                                </button>
                                                            )}
                                                            {isDraftReadyAi && (
                                                                <button
                                                                    onClick={
                                                                        hasPendingTasks
                                                                            ? undefined
                                                                            : () =>
                                                                                  handleGenerate(
                                                                                      item
                                                                                  )
                                                                    }
                                                                    disabled={
                                                                        hasPendingTasks
                                                                    }
                                                                    className={`flex items-center gap-1 text-orange-500 hover:text-orange-600 text-xs font-bold bg-white px-2 py-1 rounded border border-orange-200 w-full ${
                                                                        hasPendingTasks
                                                                            ? 'opacity-50 cursor-not-allowed'
                                                                            : ''
                                                                    }`}
                                                                    title={
                                                                        hasPendingTasks
                                                                            ? getString(
                                                                                  'table_cells',
                                                                                  'generation_disabled_pending_task',
                                                                                  'Please wait for the current task to complete'
                                                                              )
                                                                            : getString(
                                                                                  'table_cells',
                                                                                  'regenerate',
                                                                                  'Regenerate'
                                                                              )
                                                                    }
                                                                >
                                                                    <svg
                                                                        className="w-3 h-3"
                                                                        fill="none"
                                                                        stroke="currentColor"
                                                                        viewBox="0 0 24 24"
                                                                    >
                                                                        <path
                                                                            strokeLinecap="round"
                                                                            strokeLinejoin="round"
                                                                            strokeWidth={
                                                                                2
                                                                            }
                                                                            d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                                                                        />
                                                                    </svg>
                                                                    {getString(
                                                                        'table_cells',
                                                                        'regenerate',
                                                                        'Regenerate'
                                                                    )}
                                                                </button>
                                                            )}
                                                        </>
                                                    );
                                                })()}
                                            </div>
                                            {/* Edit and Delete buttons */}
                                            <div className="flex items-center gap-2">
                                                <button
                                                    onClick={() =>
                                                        handleEdit(item)
                                                    }
                                                    className="text-primary hover:text-primary-dark p-1"
                                                    title={getString(
                                                        'table_cells',
                                                        'edit',
                                                        'Edit'
                                                    )}
                                                >
                                                    <svg
                                                        className="w-4 h-4"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        viewBox="0 0 24 24"
                                                    >
                                                        <path
                                                            strokeLinecap="round"
                                                            strokeLinejoin="round"
                                                            strokeWidth={2}
                                                            d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                                                        />
                                                    </svg>
                                                </button>
                                                <button
                                                    onClick={() =>
                                                        handleDelete(item)
                                                    }
                                                    className="text-red-600 hover:text-red-700 p-1"
                                                    title={getString(
                                                        'table_cells',
                                                        'delete',
                                                        'Delete'
                                                    )}
                                                >
                                                    <svg
                                                        className="w-4 h-4"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        viewBox="0 0 24 24"
                                                    >
                                                        <path
                                                            strokeLinecap="round"
                                                            strokeLinejoin="round"
                                                            strokeWidth={2}
                                                            d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                                                        />
                                                    </svg>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>

                    {/* Pagination Controls */}
                    <div className="bg-white px-3 sm:px-4 md:px-6 py-2 sm:py-3 border-t border-gray-200">
                        <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 sm:gap-0">
                            {/* Left side - Results info */}
                            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2 sm:gap-4">
                                <p className="text-xs sm:text-sm text-gray-700">
                                    {getString(
                                        'content_plan_table',
                                        'showing',
                                        'Showing'
                                    )}{' '}
                                    <span className="font-medium">
                                        {filteredData.length === 0
                                            ? 0
                                            : table.getState().pagination
                                                  .pageIndex *
                                                  table.getState().pagination
                                                      .pageSize +
                                              1}
                                    </span>{' '}
                                    {getString(
                                        'content_plan_table',
                                        'to',
                                        'to'
                                    )}{' '}
                                    <span className="font-medium">
                                        {Math.min(
                                            (table.getState().pagination
                                                .pageIndex +
                                                1) *
                                                table.getState().pagination
                                                    .pageSize,
                                            filteredData.length
                                        )}
                                    </span>{' '}
                                    {getString(
                                        'content_plan_table',
                                        'of',
                                        'of'
                                    )}{' '}
                                    <span className="font-medium">
                                        {filteredData.length}
                                    </span>{' '}
                                    {getString(
                                        'content_plan_table',
                                        'content_plan_items_lower',
                                        'content plan items'
                                    )}
                                </p>

                                {/* Page size selector */}
                                <div className="flex items-center gap-2">
                                    <label
                                        htmlFor="pageSize"
                                        className="text-xs sm:text-sm text-gray-700 whitespace-nowrap"
                                    >
                                        {getString(
                                            'content_plan_table',
                                            'items_per_page',
                                            'Items per page'
                                        )}
                                        :
                                    </label>
                                    <select
                                        id="pageSize"
                                        value={
                                            table.getState().pagination.pageSize
                                        }
                                        onChange={e => {
                                            table.setPageSize(
                                                Number(e.target.value)
                                            );
                                        }}
                                        className="px-2 py-1 text-xs sm:text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-primary cursor-pointer"
                                    >
                                        {[10, 20, 30, 50, 100].map(pageSize => (
                                            <option
                                                key={pageSize}
                                                value={pageSize}
                                            >
                                                {pageSize}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                            </div>

                            {/* Right side - Page navigation */}
                            <div className="flex items-center gap-1 sm:gap-2 flex-wrap justify-center sm:justify-end">
                                <button
                                    onClick={() => table.setPageIndex(0)}
                                    disabled={!table.getCanPreviousPage()}
                                    className="px-2 sm:px-3 py-1 text-xs sm:text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                                    title={getString(
                                        'content_plan_table',
                                        'first_page',
                                        'First page'
                                    )}
                                >
                                    ««
                                </button>
                                <button
                                    onClick={() => table.previousPage()}
                                    disabled={!table.getCanPreviousPage()}
                                    className="px-2 sm:px-3 py-1 text-xs sm:text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                                    title={getString(
                                        'content_plan_table',
                                        'previous_page',
                                        'Previous page'
                                    )}
                                >
                                    «
                                </button>
                                <span className="text-xs sm:text-sm text-gray-700 whitespace-nowrap">
                                    {getString(
                                        'content_plan_table',
                                        'page',
                                        'Page'
                                    )}{' '}
                                    <span className="font-medium">
                                        {table.getState().pagination.pageIndex +
                                            1}
                                    </span>{' '}
                                    {getString(
                                        'content_plan_table',
                                        'of',
                                        'of'
                                    )}{' '}
                                    <span className="font-medium">
                                        {table.getPageCount()}
                                    </span>
                                </span>
                                <button
                                    onClick={() => table.nextPage()}
                                    disabled={!table.getCanNextPage()}
                                    className="px-2 sm:px-3 py-1 text-xs sm:text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                                    title={getString(
                                        'content_plan_table',
                                        'next_page',
                                        'Next page'
                                    )}
                                >
                                    »
                                </button>
                                <button
                                    onClick={() =>
                                        table.setPageIndex(
                                            table.getPageCount() - 1
                                        )
                                    }
                                    disabled={!table.getCanNextPage()}
                                    className="px-2 sm:px-3 py-1 text-xs sm:text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                                    title={getString(
                                        'content_plan_table',
                                        'last_page',
                                        'Last page'
                                    )}
                                >
                                    »»
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </Tooltip>

            {/* Bulk Delete Panel - Fixed at bottom of viewport */}
            {selectedItems.size > 0 && (
                <div className="fixed bottom-0 left-0 right-0 bg-blue-100 border-t border-blue-200 shadow-2xl z-50">
                    <div className="max-w-7xl mx-auto flex flex-col sm:flex-row items-stretch sm:items-center justify-between px-4 sm:px-6 py-3 sm:py-4 gap-3 sm:gap-0">
                        <div className="flex items-center gap-2 sm:gap-4">
                            <span className="font-medium text-blue-800 text-sm sm:text-base">
                                {selectedItems.size}{' '}
                                {selectedItems.size === 1
                                    ? getString(
                                          'content_plan_table',
                                          'item_selected',
                                          'item selected'
                                      )
                                    : getString(
                                          'content_plan_table',
                                          'items_selected',
                                          'items selected'
                                      )}
                            </span>
                            <button
                                onClick={() => setSelectedItems(new Set())}
                                className="text-blue-600 hover:text-blue-800 underline text-xs sm:text-sm"
                            >
                                {getString(
                                    'content_plan_table',
                                    'clear_selection',
                                    'Clear selection'
                                )}
                            </button>
                        </div>
                        <button
                            onClick={handleBulkDelete}
                            className="bg-red-600 hover:bg-red-700 text-white px-4 sm:px-6 py-2 rounded-md font-medium transition-colors flex items-center justify-center gap-2 text-sm sm:text-base"
                        >
                            <svg
                                className="w-4 h-4 sm:w-5 sm:h-5"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                                />
                            </svg>
                            {getString(
                                'content_plan_table',
                                'delete_x_items',
                                `Delete ${selectedItems.size} ${
                                    selectedItems.size === 1 ? 'item' : 'items'
                                }`
                            )}
                        </button>
                    </div>
                </div>
            )}

            {/* Delete Confirmation Modal */}
            <DeleteConfirmationModal
                isOpen={deleteModalOpen}
                onClose={() => {
                    setDeleteModalOpen(false);
                    setItemToDelete(undefined);
                }}
                onConfirm={async () => {
                    if (itemToDelete) {
                        try {
                            await deleteContentPlanItemAPI(
                                itemToDelete.id,
                                currentPlanId
                            );
                            setDeleteModalOpen(false);
                            setItemToDelete(undefined);
                        } catch (err) {
                            // Error is handled by context
                        }
                    }
                }}
                itemTitle={itemToDelete?.title}
                item={itemToDelete}
            />

            {/* Generate Post Modal */}
            <GeneratePostModal
                isOpen={generateModalOpen}
                onClose={() => {
                    setGenerateModalOpen(false);
                    setItemToGenerate(null);
                }}
                item={itemToGenerate}
            />
        </div>
    );
};

export default ContentPlanTable;
