'use client';

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import DataTable, { Column } from '@/components/ui/DataTable';
import Pagination from '@/components/ui/Pagination';
import FilterPanel from '@/components/ui/FilterPanel';
import Toolbar from '@/components/ui/Toolbar';
import Modal from '@/components/ui/CustomModal';
import CommonTimelineModal from '@/components/ui/CommonTimelineModal'; // ✅ Changed to CommonTimelineModal
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2, Globe, Check, X, FileText, Star } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Post {
  id: string;
  category_id: string | null;
  image: string | null;
  is_active: boolean;
  is_featured: boolean;
  is_draft: boolean;
  published_at: string | null;
  default_title: string;
  translations_count: number;
  category_name: string | null;
  deleted_at: string | null;
  created_at: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface TabCounts {
  active: number;
  deleted: number;
  drafts: number;
  published: number;
}

interface PostsTableProps {
  canEdit: boolean;
  canDelete: boolean;
  canBulkDelete: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canBulkRestore: boolean;
  canViewTimeline: boolean;
  canActivateDeactivate: boolean;
  initialPosts: {
    posts: Post[];
    pagination: PaginationData;
  };
  initialCounts: TabCounts;
}

type TabType = 'active' | 'deleted' | 'drafts' | 'published';

interface ActiveFilters {
  search: string;
  status: string;
  category_id: string;
  is_featured: string;
  startDate: string;
  endDate: string;
}

interface DeletedFilters {
  search: string;
  startDate: string;
  endDate: string;
}

interface ModalConfig {
  isOpen: boolean;
  type: 'danger' | 'warning' | 'info' | 'success';
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm: () => void;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = { 
  search: '', status: '', category_id: '', is_featured: '', startDate: '', endDate: '' 
};
const EMPTY_DELETED_FILTERS: DeletedFilters = { search: '', startDate: '', endDate: '' };

const MODAL_CLOSED: ModalConfig = {
  isOpen: false, type: 'danger', title: '', message: '',
  confirmText: 'Confirm', cancelText: 'Cancel', onConfirm: () => {},
};

// ─── API Helpers ──────────────────────────────────────────────────────────────

async function fetchPostsApi(
  page: number,
  tab: TabType,
  active: ActiveFilters,
  deleted: DeletedFilters,
  signal: AbortSignal,
) {
  const params = new URLSearchParams({
    page: String(page),
    limit: '10',
    includeDeleted: tab === 'deleted' ? 'true' : 'false',
  });

  if (tab === 'deleted') {
    if (deleted.search.trim()) params.append('search', deleted.search.trim());
    if (deleted.startDate) params.append('deletedStartDate', deleted.startDate);
    if (deleted.endDate) params.append('deletedEndDate', deleted.endDate);
  } else {
    if (active.search.trim()) params.append('search', active.search.trim());
    if (active.status) params.append('status', active.status);
    if (active.category_id) params.append('category_id', active.category_id);
    if (active.is_featured) params.append('is_featured', active.is_featured);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/posts?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch posts');
  return res.json() as Promise<{ data: { posts: Post[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/posts/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function StatusBadge({ post }: { post: Post }) {
  if (post.deleted_at) {
    return (
      <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full" style={{
        background: 'var(--color-danger-light)',
        color: 'var(--color-danger)',
      }}>
        Deleted
      </span>
    );
  }
  if (post.is_draft) {
    return (
      <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full" style={{
        background: 'var(--color-warning-light)',
        color: 'var(--color-warning)',
      }}>
        Draft
      </span>
    );
  }
  if (!post.is_active) {
    return (
      <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full" style={{
        background: 'var(--color-warning-light)',
        color: 'var(--color-warning)',
      }}>
        Inactive
      </span>
    );
  }
  return (
    <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full" style={{
      background: 'var(--color-success-light)',
      color: 'var(--color-success)',
    }}>
      Published
    </span>
  );
}

function FeaturedBadge({ isFeatured }: { isFeatured: boolean }) {
  if (!isFeatured) return null;
  return (
    <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full" style={{
      background: 'var(--color-cta-light)',
      color: 'var(--color-cta)',
    }}>
      <Star size={12} />
      Featured
    </span>
  );
}

function PostImage({ image }: { image: string | null }) {
  if (!image) {
    return (
      <div className="w-12 h-12 rounded-lg flex items-center justify-center" style={{
        background: 'var(--color-surface-alt)',
        color: 'var(--color-text-tertiary)',
      }}>
        <FileText size={20} />
      </div>
    );
  }

  return (
    <div className="relative w-12 h-12 rounded-lg overflow-hidden shrink-0">
      <Image
        src={`https://res.cloudinary.com/${process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME}/image/upload/${image}.webp`}
        alt="Post image"
        fill
        className="object-cover"
        sizes="48px"
      />
    </div>
  );
}

function TranslationsBadge({ count }: { count: number }) {
  return (
    <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full" style={{
      background: 'var(--color-cta-light)',
      color: 'var(--color-cta)',
    }}>
      <Globe size={12} />
      {count} {count === 1 ? 'lang' : 'langs'}
    </span>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function PostsTable({
  canEdit,
  canDelete,
  canBulkDelete,
  canViewDeleted,
  canPermanentDelete,
  canRestore,
  canBulkRestore,
  canViewTimeline,
  canActivateDeactivate,
  initialPosts,
  initialCounts,
}: PostsTableProps) {
  const router = useRouter();

  // ── Core state ────────────────────────────────────────────────────────────
  const [posts, setPosts] = useState<Post[]>(initialPosts.posts);
  const [pagination, setPagination] = useState<PaginationData>(initialPosts.pagination);
  const [counts, setCounts] = useState<TabCounts>(initialCounts);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('active');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [showFilters, setShowFilters] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);

  // ── Timeline state ──────────────────────────────────────────────────────
  // ✅ Changed to match Categories pattern
  const [timelineModal, setTimelineModal] = useState<{
    isOpen: boolean;
    postId: string;
    postName: string;
  }>({
    isOpen: false,
    postId: '',
    postName: '',
  });

  // ── Committed filters ─────────────────────────────────────────────────────
  const [activeFilters, setActiveFilters] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [deletedFilters, setDeletedFilters] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Draft filters ─────────────────────────────────────────────────────────
  const [draftActive, setDraftActive] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [draftDeleted, setDraftDeleted] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Refs ──────────────────────────────────────────────────────────────────
  const abortRef = useRef<AbortController | null>(null);
  const postsRef = useRef(posts);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { postsRef.current = posts; }, [posts]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  // ── Fetch functions ──────────────────────────────────────────────────────
  const fetchPosts = useCallback(async (
    page: number,
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
  ) => {
    abortRef.current?.abort();
    const ctrl = new AbortController();
    abortRef.current = ctrl;

    setLoading(true);
    try {
      const json = await fetchPostsApi(page, tab, committed.active, committed.deleted, ctrl.signal);
      setPosts(json.data.posts);
      setPagination(json.data.pagination);
      setCurrentPage(page);
      setSelectedIds(new Set());
    } catch (err) {
      if ((err as Error).name === 'AbortError') return;
      console.error('Failed to fetch posts:', err);
      toast.error('Failed to load posts');
    } finally {
      if (abortRef.current === ctrl) setLoading(false);
    }
  }, []);

  const refreshCounts = useCallback(async () => {
    try {
      const updated = await fetchCountsApi();
      setCounts(updated);
    } catch {
      console.warn('Could not refresh post counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(async (
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
    page: number,
  ) => {
    await Promise.all([
      fetchPosts(page, tab, committed),
      refreshCounts(),
    ]);
  }, [fetchPosts, refreshCounts]);

  // ── Modal helpers ─────────────────────────────────────────────────────────
  const closeModal = useCallback(() => {
    if (!isDeleting) setModal(MODAL_CLOSED);
  }, [isDeleting]);

  const openModal = useCallback((config: Omit<ModalConfig, 'isOpen'>) => {
    setModal({ isOpen: true, ...config });
  }, []);

  // ── Timeline handlers ─────────────────────────────────────────────────────
  // ✅ Simplified to match Categories pattern
  const handleTimelineClick = useCallback((post: Post) => {
    setTimelineModal({
      isOpen: true,
      postId: post.id,
      postName: post.default_title || 'Post',
    });
  }, []);

  // ── Status Change Handler ──────────────────────────────────────────────────
  const handleStatusChange = useCallback(async (id: string, action: 'activate' | 'deactivate') => {
    setIsDeleting(true);
    try {
      const newStatus = action === 'activate' ? 1 : 0;
      const res = await fetch(`/api/posts/${id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: newStatus })
      });
      
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success(`Post ${action}d successfully`);
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, `Failed to ${action} post`));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── CRUD operations ───────────────────────────────────────────────────────

  const handleRestorePost = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/posts/${id}/restore`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Post restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore post');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkRestore = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/posts/bulk/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Posts restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore posts');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handlePermanentDelete = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/posts/${id}/permanent`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Post permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete post');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkPermanentDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/posts/bulk/permanent', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Posts permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete posts');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleDeletePost = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/posts/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Post deleted successfully');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete post'));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/posts/bulk', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedRef.current) }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Posts deleted successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to delete posts');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── Action handlers ───────────────────────────────────────────────────────

  const handleEditClick = useCallback((id: string) => {
    router.push(`/admin/dashboard/posts/edit/${id}`);
  }, [router]);

  const handleDeleteClick = useCallback((post: Post) => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Delete Post',
        message: `Are you sure you want to permanently delete "${post.default_title}"? This cannot be undone.`,
        confirmText: 'Permanently Delete',
        cancelText: 'Cancel',
        onConfirm: () => handlePermanentDelete(post.id),
      });
      return;
    }

    openModal({
      type: 'danger',
      title: 'Delete Post',
      message: `Are you sure you want to delete "${post.default_title}"? It will move to deleted items.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDeletePost(post.id),
    });
  }, [activeTab, handleDeletePost, handlePermanentDelete, openModal]);

  const handleRestoreClick = useCallback((post: Post) => {
    openModal({
      type: 'info',
      title: 'Restore Post',
      message: `Restore "${post.default_title}"?`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestorePost(post.id),
    });
  }, [handleRestorePost, openModal]);

  const handleActivateClick = useCallback((post: Post) => {
    openModal({
      type: 'success',
      title: 'Activate Post',
      message: `Activate "${post.default_title}"?`,
      confirmText: 'Activate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(post.id, 'activate'),
    });
  }, [handleStatusChange, openModal]);

  const handleDeactivateClick = useCallback((post: Post) => {
    openModal({
      type: 'warning',
      title: 'Deactivate Post',
      message: `Deactivate "${post.default_title}"?`,
      confirmText: 'Deactivate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(post.id, 'deactivate'),
    });
  }, [handleStatusChange, openModal]);

  // ── Bulk actions ──────────────────────────────────────────────────────────

  const showBulkDeleteConfirmation = useCallback(() => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Bulk Delete',
        message: `Permanently delete ${selectedRef.current.size} post(s)? This cannot be undone.`,
        confirmText: 'Permanently Delete All',
        cancelText: 'Cancel',
        onConfirm: handleBulkPermanentDelete,
      });
      return;
    }

    openModal({
      type: 'danger',
      title: 'Bulk Delete Posts',
      message: `Delete ${selectedRef.current.size} post(s)? They will move to deleted items.`,
      confirmText: 'Delete All',
      cancelText: 'Cancel',
      onConfirm: handleBulkDelete,
    });
  }, [activeTab, handleBulkDelete, handleBulkPermanentDelete, openModal]);

  const showBulkRestoreConfirmation = useCallback(() => {
    openModal({
      type: 'info',
      title: 'Bulk Restore Posts',
      message: `Restore ${selectedRef.current.size} post(s)?`,
      confirmText: 'Restore All',
      cancelText: 'Cancel',
      onConfirm: handleBulkRestore,
    });
  }, [handleBulkRestore, openModal]);

  // ── Tab change ────────────────────────────────────────────────────────────
  const handleTabChange = useCallback((tab: TabType) => {
    setActiveTab(tab);
    setShowFilters(false);
    const freshActive = EMPTY_ACTIVE_FILTERS;
    const freshDeleted = EMPTY_DELETED_FILTERS;
    setActiveFilters(freshActive);
    setDeletedFilters(freshDeleted);
    setDraftActive(freshActive);
    setDraftDeleted(freshDeleted);
    fetchPosts(1, tab, { active: freshActive, deleted: freshDeleted });
  }, [fetchPosts]);

  // ── Filter panel ──────────────────────────────────────────────────────────
  const handleToggleFilters = useCallback(() => {
    setShowFilters(prev => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchPosts(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchPosts(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchPosts]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchPosts(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchPosts(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchPosts]);

  // ── Pagination ────────────────────────────────────────────────────────────
  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchPosts(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchPosts, activeTab, activeFilters, deletedFilters]);

  // ── Selection ─────────────────────────────────────────────────────────────
  const handleSelectAll = useCallback(() => {
    setSelectedIds(prev =>
      prev.size === postsRef.current.length
        ? new Set()
        : new Set(postsRef.current.map(r => r.id)),
    );
  }, []);

  const handleSelectPost = useCallback((id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) { next.delete(id); } else { next.add(id); }
      return next;
    });
  }, []);

  // ── Columns ───────────────────────────────────────────────────────────────
  const columns = useMemo<Column<Post>[]>(() => {
    const cols: Column<Post>[] = [
      {
        key: 'title',
        header: 'Title',
        render: (post) => (
          <div className="flex items-center gap-3">
            <PostImage image={post.image} />
            <div>
              <div className="font-medium" style={{ color: 'var(--color-text)' }}>
                {post.default_title}
              </div>
              <div className="text-xs flex items-center gap-2" style={{ color: 'var(--color-text-tertiary)' }}>
                <span>ID: {post.id.substring(0, 8)}...</span>
                {post.category_name && (
                  <span className="px-1.5 py-0.5 rounded text-xs" style={{
                    background: 'var(--color-surface-alt)',
                    color: 'var(--color-text-secondary)',
                  }}>
                    {post.category_name}
                  </span>
                )}
              </div>
            </div>
          </div>
        ),
      },
      {
        key: 'translations',
        header: 'Languages',
        render: (post) => <TranslationsBadge count={post.translations_count} />,
      },
      {
        key: 'featured',
        header: 'Featured',
        render: (post) => <FeaturedBadge isFeatured={post.is_featured} />,
      },
      {
        key: 'status',
        header: 'Status',
        render: (post) => <StatusBadge post={post} />,
      },
      {
        key: 'published_at',
        header: 'Published',
        render: (post) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {post.published_at ? new Date(post.published_at).toLocaleDateString() : '—'}
          </span>
        ),
      },
      {
        key: 'created_at',
        header: 'Created',
        render: (post) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {new Date(post.created_at).toLocaleDateString()}
          </span>
        ),
      },
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (post) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {post.deleted_at ? new Date(post.deleted_at).toLocaleDateString() : '-'}
          </span>
        ),
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (post) => {
        const actions: React.ReactNode[] = [];

        // Timeline button
        if (canViewTimeline) {
          actions.push(
            <button
              key="timeline"
              onClick={() => handleTimelineClick(post)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-text-secondary)' }}
              title="View Timeline"
            >
              <History size={16} />
            </button>,
          );
        }

        if (activeTab === 'deleted') {
          if (canRestore) actions.push(
            <button
              key="restore"
              onClick={() => handleRestoreClick(post)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-success)' }}
              title="Restore Post"
            >
              <ArchiveRestore size={16} />
            </button>,
          );
          if (canPermanentDelete) actions.push(
            <button
              key="perm-del"
              onClick={() => handleDeleteClick(post)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-danger)' }}
              title="Permanently Delete"
            >
              <Trash2 size={16} />
            </button>,
          );
        } else {
          // Activate/Deactivate buttons - only for non-draft posts
          if (canActivateDeactivate && !post.is_draft) {
            if (post.is_active) {
              actions.push(
                <button
                  key="deactivate"
                  onClick={() => handleDeactivateClick(post)}
                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                  style={{ color: 'var(--color-warning)' }}
                  title="Deactivate Post"
                >
                  <X size={16} />
                </button>
              );
            } else if (!post.deleted_at) {
              actions.push(
                <button
                  key="activate"
                  onClick={() => handleActivateClick(post)}
                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                  style={{ color: 'var(--color-success)' }}
                  title="Activate Post"
                >
                  <Check size={16} />
                </button>
              );
            }
          }

          if (canEdit) actions.push(
            <button
              key="edit"
              onClick={() => handleEditClick(post.id)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-info)' }}
              title="Edit Post"
            >
              <SquarePen size={16} />
            </button>,
          );

          if (canDelete) {
            actions.push(
              <button
                key="delete"
                onClick={() => handleDeleteClick(post)}
                className="p-1 rounded hover:bg-surface-alt transition-colors"
                style={{ color: 'var(--color-danger)' }}
                title="Delete"
              >
                <Trash2 size={16} />
              </button>
            );
          }
        }

        return <div className="flex justify-end gap-2">{actions}</div>;
      },
    });

    return cols;
  }, [
    activeTab, canEdit, canDelete, canPermanentDelete, canRestore,
    canViewTimeline, canActivateDeactivate,
    handleEditClick, handleDeleteClick, handleRestoreClick,
    handleTimelineClick, handleActivateClick, handleDeactivateClick,
  ]);

  // ── Filter fields ─────────────────────────────────────────────────────────
  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch',
          label: 'Search',
          type: 'text' as const,
          placeholder: 'Search by title...',
          value: draftDeleted.search,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, search: v })),
        },
        {
          name: 'deletedStartDate',
          label: 'Deleted From',
          type: 'date' as const,
          value: draftDeleted.startDate,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, startDate: v })),
        },
        {
          name: 'deletedEndDate',
          label: 'Deleted To',
          type: 'date' as const,
          value: draftDeleted.endDate,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, endDate: v })),
        },
      ];
    }
    return [
      {
        name: 'search',
        label: 'Search',
        type: 'text' as const,
        placeholder: 'Search by title...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive(p => ({ ...p, search: v })),
      },
      {
        name: 'status',
        label: 'Status',
        type: 'select' as const,
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'inactive', label: 'Inactive' },
          { value: 'draft', label: 'Draft' },
          { value: 'published', label: 'Published' },
        ],
        value: draftActive.status,
        onChange: (v: string) => setDraftActive(p => ({ ...p, status: v })),
      },
      {
        name: 'is_featured',
        label: 'Featured',
        type: 'select' as const,
        options: [
          { value: '', label: 'All' },
          { value: 'true', label: 'Featured' },
          { value: 'false', label: 'Not Featured' },
        ],
        value: draftActive.is_featured,
        onChange: (v: string) => setDraftActive(p => ({ ...p, is_featured: v })),
      },
      {
        name: 'startDate',
        label: 'Created From',
        type: 'date' as const,
        value: draftActive.startDate,
        onChange: (v: string) => setDraftActive(p => ({ ...p, startDate: v })),
      },
      {
        name: 'endDate',
        label: 'Created To',
        type: 'date' as const,
        value: draftActive.endDate,
        onChange: (v: string) => setDraftActive(p => ({ ...p, endDate: v })),
      },
    ];
  }, [activeTab, draftActive, draftDeleted]);

  // ── Bulk action bar ───────────────────────────────────────────────────────
  const bulkActionBar = useMemo(() => {
    if (selectedIds.size === 0) return null;

    if (activeTab === 'deleted') {
      return (
        <div className="flex gap-2">
          {canBulkRestore && (
            <button
              onClick={showBulkRestoreConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-success)', color: 'white' }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 12a9 9 0 1 0 9-9m0 0v6m0-6h-6"/><path d="M21 12a9 9 0 1 1-9-9"/>
              </svg>
              Restore ({selectedIds.size})
            </button>
          )}
          {canPermanentDelete && (
            <button
              onClick={showBulkDeleteConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-danger)', color: 'white' }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
              </svg>
              Permanently Delete ({selectedIds.size})
            </button>
          )}
        </div>
      );
    }
    
    if (canBulkDelete) {
      return (
        <button
          onClick={showBulkDeleteConfirmation}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
          style={{ background: 'var(--color-danger)', color: 'white' }}
        >
          <svg width="16" height="16" {...ICON_STROKE}>
            <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
          </svg>
          Delete ({selectedIds.size})
        </button>
      );
    }
    return null;
  }, [
    selectedIds, activeTab,
    canBulkDelete, canBulkRestore, canPermanentDelete,
    showBulkDeleteConfirmation, showBulkRestoreConfirmation,
  ]);

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="space-y-4">
      {/* Tabs - including Drafts and Published */}
      <div className="flex border-b flex-wrap" style={{ borderColor: 'var(--color-border)' }}>
        <button
          onClick={() => handleTabChange('active')}
          className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
            activeTab === 'active'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
          }`}
        >
          All Active ({counts.active})
        </button>
        <button
          onClick={() => handleTabChange('drafts')}
          className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
            activeTab === 'drafts'
              ? 'border-yellow-500 text-yellow-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
          }`}
        >
          Drafts ({counts.drafts})
        </button>
        <button
          onClick={() => handleTabChange('published')}
          className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
            activeTab === 'published'
              ? 'border-green-500 text-green-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
          }`}
        >
          Published ({counts.published})
        </button>
        {canViewDeleted && (
          <button
            onClick={() => handleTabChange('deleted')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'deleted'
                ? 'border-red-500 text-red-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Deleted ({counts.deleted})
          </button>
        )}
      </div>

      <Toolbar
        leftActions={
          <>
            <button
              onClick={handleToggleFilters}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all border"
              style={{
                borderColor: 'var(--color-border)',
                color: 'var(--color-text)',
                background: 'var(--color-surface)'
              }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M6 12h12M10 18h4"/>
              </svg>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
            {bulkActionBar}
          </>
        }
      />

      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      <DataTable
        columns={columns}
        data={posts}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelectPost}
        onSelectAll={handleSelectAll}
        getRowId={(post) => post.id}
        showCheckbox={activeTab === 'deleted' ? (canPermanentDelete || canBulkRestore) : canBulkDelete}
        emptyMessage={activeTab === 'deleted' ? 'No deleted posts found' : 'No posts found'}
        skeletonRows={10}
      />

      {!loading && pagination.totalPages > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={pagination.totalPages}
          totalItems={pagination.total}
          itemsPerPage={pagination.limit}
          onPageChange={handlePageChange}
          showItemsInfo
        />
      )}

      {/* Confirmation Modal */}
      <Modal
        isOpen={modal.isOpen}
        onClose={closeModal}
        onConfirm={modal.onConfirm}
        title={modal.title}
        message={modal.message}
        confirmText={modal.confirmText}
        cancelText={modal.cancelText}
        type={modal.type}
        isLoading={isDeleting}
      />

      {/* ✅ Timeline Modal - Using CommonTimelineModal like Categories */}
      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={() => setTimelineModal({ isOpen: false, postId: '', postName: '' })}
        entityType="post"
        entityId={timelineModal.postId}
        entityName={timelineModal.postName}
        title="Post Timeline"
      />
    </div>
  );
}