// app/components/admin/posts/PostsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { usePermissions } from '@/hooks/usePermissions';
import { PERMISSIONS } from '@/lib/permissions';
import { useAlert } from '@/contexts/AlertContext';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, PaginationData, TableColumn, TableAction } from '@/types/admin-table';

// ── Types ─────────────────────────────────────────────────────────────────────

interface Post extends BaseTableItem {
  id: string;
  post_title: string;
  post_slug: string;
  post_excerpt: string | null;
  post_featured_image: string | null;
  post_status: 'draft' | 'published' | 'pending_review';
  is_featured: boolean;
  is_indexable: boolean;
  reading_time_minutes: number | null;
  post_sidebar_id: string | null;
  post_sidebar_on_mobile: boolean;
  post_create_date: string;
  post_update_date: string;
  category_name: string | null;
  author_name: string | null;
  sidebar_name: string | null;
}

interface Category {
  id: string;
  name: string;
}

interface PostsTableProps {
  initialData?: {
    posts: Post[];
    pagination: PaginationData;
  };
}

// ── Constants ─────────────────────────────────────────────────────────────────

const STATUS_STYLES: Record<string, string> = {
  published: 'bg-var-success-bg text-var-success-text border border-var-success-border',
  draft: 'bg-var-surface-hover text-var-text-muted border border-var-border',
  pending_review: 'bg-var-warning-bg text-var-warning-text border border-var-warning-border',
};

const STATUS_LABELS: Record<string, string> = {
  published: 'Published',
  draft: 'Draft',
  pending_review: 'Pending Review',
};

// ── Component ─────────────────────────────────────────────────────────────────

export default function PostsTable({ initialData }: PostsTableProps) {
  const router = useRouter();
  const [posts, setPosts] = useState<Post[]>(initialData?.posts || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [pagination, setPagination] = useState<PaginationData>(
    initialData?.pagination || { page: 1, limit: 10, total: 0, pages: 0 }
  );
  const [filters, setFilters] = useState<FilterValues>({ 
    search: '', 
    status: '', 
    category: '' 
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const canCreate = hasPermission(PERMISSIONS.CONTENT_CREATE);
  const canEdit = hasPermission(PERMISSIONS.CONTENT_UPDATE);
  const canDelete = hasPermission(PERMISSIONS.CONTENT_DELETE);
  const canBulkDelete = hasPermission(PERMISSIONS.CONTENT_BULK_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search posts...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'published', label: 'Published' },
        { value: 'draft', label: 'Draft' },
        { value: 'pending_review', label: 'Pending Review' }
      ]
    },
    {
      key: 'category',
      label: 'Category',
      type: 'select',
      options: categories.map(c => ({ value: c.id, label: c.name }))
    }
  ];

  // ── Load categories for filter dropdown ──────────────────────────────────────

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const res = await fetch('/api/backend/admin/posts/categories');
        const data = await res.json();
        if (res.ok) setCategories(data.categories || []);
      } catch {
        // non-fatal — filter just won't have options
      }
    };
    fetchCategories();
  }, []);

  // ── Fetch posts ───────────────────────────────────────────────────────────────

  const fetchPosts = useCallback(async (page = 1, newFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters,
      });
      const res = await fetch(`/api/backend/admin/posts?${params}`);
      const data = await res.json();
      if (res.ok) {
        setPosts(data.posts);
        setPagination(data.pagination);
      } else {
        toast.error(data.error || 'Failed to fetch posts');
      }
    } catch {
      toast.error('Failed to fetch posts');
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchPosts(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchPosts(page);
  };

  // ── Handlers ──────────────────────────────────────────────────────────────────

  const handleStatusChange = async (postId: string, newStatus: string) => {
    if (!canEdit) { 
      toast.error('No permission'); 
      return; 
    }
    
    try {
      const res = await fetch(`/api/backend/admin/posts/${postId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ post_status: newStatus }),
      });
      
      const data = await res.json();
      
      if (res.ok) {
        toast.success(data.message || 'Status updated successfully');
        fetchPosts(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch {
      toast.error('Failed to update status');
    }
  };

  const handleDeleteClick = (post: Post) => {
    if (!canDelete) { 
      toast.error('No permission'); 
      return; 
    }
    
    showAlert({
      title: 'Delete Post',
      message: `Are you sure you want to delete "${post.post_title}"? This action cannot be undone.`,
      confirmText: 'Delete Post',
      cancelText: 'Cancel',
      onConfirm: () => deletePost(post.id),
    });
  };

  const deletePost = async (id: string) => {
    try {
      const res = await fetch(`/api/backend/admin/posts/${id}`, { 
        method: 'DELETE' 
      });
      const data = await res.json();
      
      if (res.ok) {
        toast.success(data.message || 'Post deleted successfully');
        fetchPosts(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete post');
      }
    } catch {
      toast.error('Failed to delete post');
    }
  };

  // Handle bulk delete
  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/posts/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        if (data.notFoundIds && data.notFoundIds.length > 0) {
          toast.success(
            `${data.deletedCount} post${data.deletedCount !== 1 ? 's' : ''} deleted, ${data.notFoundIds.length} not found`
          );
        } else if (data.deletedCount === 1) {
          toast.success(data.message);
        } else {
          toast.success(data.message);
        }
        
        fetchPosts(pagination.page);
      } else {
        toast.error(data.error || 'Bulk delete failed');
      }
    } catch {
      toast.error('Bulk delete failed');
    }
  };

  // Bulk actions configuration
  const bulkActions = [
    ...(canBulkDelete ? [{
      key: 'bulk-delete',
      label: 'Delete selected',
      icon: (
        <svg 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>
      ),
      className: 'bg-var-danger-bg text-var-danger hover:bg-var-danger-bg',
      requiresConfirm: true,
      confirmTitle: 'Delete selected posts',
      confirmMessage: (count: number) => {
        return `Are you sure you want to delete ${count} post${count !== 1 ? 's' : ''}? This action cannot be undone.`;
      },
      onClick: handleBulkDelete,
    }] : []),
  ];

  // ── Helper functions for rendering ───────────────────────────────────────────

  const getPostThumbnail = (post: Post) => {
    if (post.post_featured_image) {
      return (
        <Image
          src={post.post_featured_image}
          alt={post.post_title}
          width={40}
          height={40}
          className="w-10 h-10 rounded-lg object-cover shrink-0 border border-var-border"
        />
      );
    }
    
    return (
      <div className="w-10 h-10 rounded-lg bg-var-primary flex items-center justify-center shrink-0">
        <svg className="w-5 h-5 text-white" 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>
      </div>
    );
  };

  const getReadingTimeIcon = () => (
    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );

  const getSidebarIcon = () => (
    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V5z" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 3v18" />
    </svg>
  );

  const getViewIcon = () => (
    <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>
  );

  // ── Table columns configuration ───────────────────────────────────────────────

  const columns: TableColumn<Post>[] = [
    {
      key: 'post',
      label: 'Post',
      render: (post) => (
        <div className="flex items-start gap-3 max-w-xs">
          {getPostThumbnail(post)}
          <div className="min-w-0">
            <div className="flex items-center gap-1.5 flex-wrap">
              <p className="text-sm font-semibold text-var-text truncate">{post.post_title}</p>
              {post.is_featured && (
                <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-var-warning-bg text-var-warning-text border border-var-warning-border shrink-0">
                  ★ Featured
                </span>
              )}
            </div>
            <code className="text-xs text-var-text-muted bg-var-surface-hover px-1.5 py-0.5 rounded mt-1 inline-block truncate max-w-45">
              /{post.post_slug}
            </code>
            {post.reading_time_minutes && (
              <p className="text-xs text-var-text-muted mt-0.5 flex items-center gap-1">
                {getReadingTimeIcon()}
                {post.reading_time_minutes} min read
              </p>
            )}
          </div>
        </div>
      )
    },
    {
      key: 'category_author',
      label: 'Category / Author',
      render: (post) => (
        <div className="space-y-1.5">
          {post.category_name ? (
            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-var-primary-muted text-var-primary-text border border-var-primary">
              {post.category_name}
            </span>
          ) : (
            <span className="text-xs text-var-text-muted italic">No category</span>
          )}
          {post.author_name && (
            <p className="text-xs text-var-text-muted">by {post.author_name}</p>
          )}
        </div>
      )
    },
    {
      key: 'sidebar',
      label: 'Sidebar',
      render: (post) => (
        post.post_sidebar_id ? (
          <div className="space-y-1">
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-var-info-bg text-var-info-text border border-var-info-border">
              {getSidebarIcon()}
              {post.sidebar_name || 'Sidebar'}
            </span>
            <p className="text-xs text-var-text-muted">
              {post.post_sidebar_on_mobile ? '📱 All devices' : '🖥️ Desktop only'}
            </p>
          </div>
        ) : (
          <span className="text-xs text-var-text-muted italic">No sidebar</span>
        )
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (post) => (
        canEdit ? (
          <select
            value={post.post_status}
            onChange={(e) => handleStatusChange(post.id, e.target.value)}
            className={`text-xs font-medium px-2.5 py-1 rounded-full border-0 cursor-pointer focus:ring-2 focus:ring-var-primary bg-var-surface ${STATUS_STYLES[post.post_status]}`}
            onClick={(e) => e.stopPropagation()}
          >
            <option value="draft">Draft</option>
            <option value="published">Published</option>
            <option value="pending_review">Pending Review</option>
          </select>
        ) : (
          <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${STATUS_STYLES[post.post_status]}`}>
            {STATUS_LABELS[post.post_status]}
          </span>
        )
      )
    },
    {
      key: 'date',
      label: 'Date',
      render: (post) => (
        <div className="text-sm text-var-text-muted whitespace-nowrap">
          <p>{new Date(post.post_create_date).toLocaleDateString()}</p>
          {post.post_update_date !== post.post_create_date && (
            <p className="text-xs text-var-text-muted mt-0.5">
              Updated {new Date(post.post_update_date).toLocaleDateString()}
            </p>
          )}
        </div>
      )
    }
  ];

  // ── Table actions configuration ───────────────────────────────────────────────

  const actions: TableAction<Post>[] = [
    // View live button
    {
      key: 'view',
      icon: getViewIcon(),
      onClick: (post) => {
        window.open(`/blog/${post.post_slug}`, '_blank');
      },
      className: 'text-var-text-muted hover:text-var-text hover:bg-var-surface-hover',
      title: 'View post'
    },
    
    // Edit button
    ...(canEdit ? [{
      key: 'edit',
      icon: (
        <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>
      ),
      onClick: (post: Post) => {
        router.push(`/admin/dashboard/posts/edit/${post.id}`);
      },
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit post'
    }] : []),

    // Delete button
    ...(canDelete ? [{
      key: 'delete',
      icon: (
        <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>
      ),
      onClick: (post: Post) => handleDeleteClick(post),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete post'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchPosts();
    }
  }, [fetchPosts, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      {/* ── Header + Filters ───────────────────────────────────────────── */}
      <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
          <div>
            <h2 className="text-lg font-semibold text-var-text">Blog Posts</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} post{pagination.total !== 1 ? 's' : ''} total
            </p>
          </div>
          
          <div className="flex items-center gap-3">
            {/* Filter Toggle Button */}
            <button
              onClick={toggleFilters}
              className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
              title={filtersVisible ? "Hide filters" : "Show filters"}
            >
              <svg className="w-4 h-4 mr-2" 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>
              {filtersVisible ? 'Hide Filters' : 'Show Filters'}
            </button>

            {canCreate && (
              <Link
                href="/admin/dashboard/posts/new"
                className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                New Post
              </Link>
            )}
          </div>
        </div>

        {/* Filters - Conditionally rendered */}
        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      {/* ── Table ──────────────────────────────────────────────────────── */}
      <DataTable
        data={posts}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No posts yet"
        emptyDescription="Create your first blog post to get started"
        onCreateNew={canCreate ? () => {
          router.push('/admin/dashboard/posts/new');
        } : undefined}
        createNewLabel="Write your first post →"
        keyExtractor={(post) => post.id}
      />

      {/* ── Pagination ─────────────────────────────────────────────────── */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}