// app/components/admin/categories/CategoriesTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
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';
import { useRouter } from 'next/navigation';

interface Category extends BaseTableItem {
  id: string;
  name: string;
  slug: string;
  description: string;
  status: boolean;
  is_indexable: boolean;
  meta_title: string;
  meta_description: string;
  schemas: unknown[];
  featured_image: string;
  featured_image_alt_text: string;
  parent_id: string;
  parent_name: string;
  parent_slug: string;
  category_type: string;
  created_at: string;
  updated_at: string;
}

interface CategoriesTableProps {
  initialData?: {
    categories: Category[];
    pagination: PaginationData;
  };
}

export default function CategoriesTable({ initialData }: CategoriesTableProps) {
  const [categories, setCategories] = useState<Category[]>(initialData?.categories || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationData>(initialData?.pagination || {
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [filters, setFilters] = useState<FilterValues>({
    search: '',
    status: '',
    category_type: ''
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const router = useRouter();

  // Check permissions
  const canCreateCategory = hasPermission(PERMISSIONS.CATEGORIES_CREATE);
  const canEditCategory = hasPermission(PERMISSIONS.CATEGORIES_UPDATE);
  const canDeleteCategory = hasPermission(PERMISSIONS.CATEGORIES_DELETE);
  const canToggleStatus = hasPermission(PERMISSIONS.CATEGORIES_UPDATE);
  const canBulkDelete = hasPermission(PERMISSIONS.CATEGORIES_BULK_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name or slug...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' }
      ]
    },
    {
      key: 'category_type',
      label: 'Category Type',
      type: 'select',
      options: [
        { value: 'GENERAL', label: 'General' },
        { value: 'SPECIAL', label: 'Special' }
      ]
    }
  ];

  // Fetch categories with filters and pagination
  const fetchCategories = useCallback(async (page = 1, newFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters
      });

      const response = await fetch(`/api/backend/admin/categories?${params}`);
      const data = await response.json();

      if (response.ok) {
        setCategories(data.categories);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view categories');
        } else {
          toast.error(data.error || 'Failed to fetch categories');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch categories');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchCategories(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchCategories(page);
  };

  // Handle category status toggle
  const toggleCategoryStatus = async (categoryId: string, currentStatus: boolean) => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update category status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/categories/${categoryId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          status: !currentStatus
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`Category ${!currentStatus ? 'activated' : 'deactivated'} successfully`);
        fetchCategories(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to update categories');
        } else {
          toast.error(data.error || 'Failed to update category status');
        }
      }
    } catch (error) {
      toast.error('Failed to update category status');
      console.error(error);
    }
  };

  // Handle category deletion with custom alert
  const handleDeleteClick = (category: Category) => {
    if (!canDeleteCategory) {
      toast.error('You do not have permission to delete categories');
      return;
    }

    showAlert({
      title: 'Delete Category',
      message: `Are you sure you want to delete "${category.name}"? This action cannot be undone and will remove all associated content.`,
      confirmText: 'Delete Category',
      cancelText: 'Cancel',
      onConfirm: () => deleteCategory(category.id),
    });
  };

  const handleEditPage = (categoryId: string) => {
    if (!canEditCategory) {
      toast.error('You do not have permission to edit categories');
      return;
    }
    router.push(`/admin/dashboard/categories/edit/${categoryId}`);
  };

  // Actual delete function
  const deleteCategory = async (categoryId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/categories/${categoryId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Category deleted successfully');
        fetchCategories(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to delete categories');
        } else {
          toast.error(data.error || 'Failed to delete category');
        }
      }
    } catch (error) {
      toast.error('Failed to delete category');
      console.error(error);
    }
  };

  // ─── Bulk delete ────────────────────────────────────────────────────────────
  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/categories/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        // Show partial-skip warning if some were skipped
        if (data.skipped?.length > 0) {
          toast.success(
            `${data.deletedCount} categor${data.deletedCount !== 1 ? 'ies' : 'y'} deleted, ${data.skipped.length} skipped`
          );
        } else {
          toast.success(
            `${data.deletedCount} categor${data.deletedCount !== 1 ? 'ies' : 'y'} deleted`
          );
        }
        fetchCategories(pagination.page);
      } else {
        toast.error(data.error || 'Bulk delete failed');
      }
    } catch {
      toast.error('Bulk delete failed');
    }
  };

  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 categories',
      confirmMessage: (count: number) =>
        `Are you sure you want to delete ${count} categor${count !== 1 ? 'ies' : 'y'}? Categories with posts or child categories will be skipped. This action cannot be undone.`,
      onClick: handleBulkDelete,
    }] : []),
  ];
  // ────────────────────────────────────────────────────────────────────────────

  // Helper functions for rendering
  const getCategoryImage = (category: Category) => {
    if (category.featured_image) {
      return (
        <Image
          src={category.featured_image}
          alt={category.featured_image_alt_text || category.name}
          className="w-8 h-8 rounded-full object-cover border-2 border-var-surface shadow-var-card"
          width={32}
          height={32}
        />
      );
    }
    
    return (
      <div className="w-8 h-8 bg-var-primary rounded-full flex items-center justify-center text-white text-sm font-bold shadow-var-card">
        {category.name[0]}
      </div>
    );
  };

  const getParentCategoryDisplay = (category: Category) => {
    if (!category.parent_name) {
      return (
        <span className="text-sm text-var-text-muted italic">None (Root)</span>
      );
    }
    
    return (
      <div className="flex items-center">
        <span className="text-sm font-medium text-var-text">{category.parent_name}</span>
        <code className="ml-2 text-xs font-mono text-var-text-muted bg-var-surface-hover px-1 py-0.5 rounded">
          /{category.parent_slug}
        </code>
      </div>
    );
  };

  const getCategoryTypeBadge = (type: string) => {
    if (type === 'SPECIAL') {
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-info-bg text-var-info-text">
          Special
        </span>
      );
    }
    return (
      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-primary-muted text-var-primary-text">
        General
      </span>
    );
  };

  // Table columns configuration
  const columns: TableColumn<Category>[] = [
    {
      key: 'name',
      label: 'Category',
      render: (category) => (
        <div className="flex items-center">
          <div className="relative">
            {getCategoryImage(category)}
          </div>
          <div className="ml-4">
            <div className="text-sm font-medium text-var-text">
              {category.name}
            </div>
            <code className="text-xs font-mono text-var-text-muted bg-var-surface-hover px-2 py-1 rounded">
              /{category.slug}
            </code>
          </div>
        </div>
      )
    },
    {
      key: 'type',
      label: 'Type',
      render: (category) => getCategoryTypeBadge(category.category_type)
    },
    {
      key: 'parent',
      label: 'Parent Category',
      render: (category) => getParentCategoryDisplay(category)
    },
    {
      key: 'status',
      label: 'Status',
      render: (category) => (
        <div className="flex items-center space-x-2">
          <div className={`w-2 h-2 rounded-full ${
            category.status ? 'bg-var-success' : 'bg-var-danger'
          }`}></div>
          <span className={`text-sm font-medium ${
            category.status ? 'text-var-success-text' : 'text-var-danger-text'
          }`}>
            {category.status ? 'Active' : 'Inactive'}
          </span>
        </div>
      )
    },
    {
      key: 'seo',
      label: 'SEO',
      render: (category) => (
        <div className="flex flex-wrap gap-1">
          {category.is_indexable ? (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-success-bg text-var-success-text">
              Indexable
            </span>
          ) : (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-warning-bg text-var-warning-text">
              No Index
            </span>
          )}
          {category.schemas?.length > 0 && (
            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-info-bg text-var-info-text">
              {category.schemas.length} Schema{category.schemas.length !== 1 ? 's' : ''}
            </span>
          )}
        </div>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (category) => (
        <span className="text-sm text-var-text-muted">
          {new Date(category.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  // Table actions configuration
  const actions: TableAction<Category>[] = [
    // Edit Button
    ...(canEditCategory ? [{
      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: (category: Category) => handleEditPage(category.id),
      condition: () => canEditCategory,
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit category'
    }] : []),
    
    // Status Toggle Button
    ...(canToggleStatus ? [{
      key: 'toggle-status',
      icon: (category: Category) => (
        category.status ? (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        ) : (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        )
      ),
      onClick: (category: Category) => toggleCategoryStatus(category.id, category.status),
      condition: () => canToggleStatus,
      className: (category: Category) => 
        category.status
          ? 'text-var-warning hover:text-var-warning-text hover:bg-var-warning-bg'
          : 'text-var-success hover:text-var-success-text hover:bg-var-success-bg',
      title: (category: Category) => 
        category.status ? 'Deactivate category' : 'Activate category'
    }] : []),

    // Delete Button
    ...(canDeleteCategory ? [{
      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: (category: Category) => handleDeleteClick(category),
      condition: () => canDeleteCategory,
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete category'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchCategories();
    }
  }, [fetchCategories, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      {/* Header */}
      <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 space-y-4 lg:space-y-0">
          <div>
            <h2 className="text-lg font-semibold text-var-text">Category Management</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} categor{pagination.total !== 1 ? 'ies' : 'y'} found
            </p>
          </div>
          
          <div className="flex items-center space-x-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>

            {canCreateCategory && (
              <Link
                href="/admin/dashboard/categories/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>
                Add Category
              </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={categories}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No categories found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreateCategory ? () => {
          window.location.href = '/admin/dashboard/categories/new';
        } : undefined}
        createNewLabel="Create your first category →"
        keyExtractor={(category) => category.id}
      />

      {/* Pagination */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}