// app/components/admin/websites/WebsitesTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
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 { BaseTableItem, PaginationData, TableColumn, TableAction } from '@/types/admin-table';
import { useRouter } from 'next/navigation';

interface Category {
  id: string;
  name: string;
  slug: string;
}

interface SpecialCategory {
  id: string;
  name: string;
  slug: string;
}

interface User {
  id: string;
  email: string;
  display_name: string;
  first_name: string;
  last_name: string;
}

interface TrafficRange {
  label: string;
  min: number;
  max: number | null;
}

interface Website extends BaseTableItem {
  id: string;
  name: string;
  slug: string;
  domain: string;
  da: number | null;
  dr: number | null;
  traffic: string;
  spam_score: number | null;
  backlinks: number | null;
  link_type: 'Dofollow' | 'Nofollow';
  base_price: number;
  sale_price: number | null;
  content_service_price: number;
  category_id: string;
  category_name: string;
  category_slug: string;
  user_id: string;
  user_name?: string;
  user_email?: string;
  niches: string[];
  niche_names?: string[];
  niche_pricing: Record<string, number>;
  description: string;
  meta_title: string;
  meta_description: string;
  is_indexable: boolean;
  schemas: unknown[];
  status: 'active' | 'inactive' | 'sold_out';
  featured: boolean;
  featured_image: string;
  featured_image_alt_text: string;
  created_at: string;
  updated_at: string;
}

interface WebsitesTableProps {
  initialData?: {
    websites: Website[];
    pagination: PaginationData;
    categories: Category[];
    specialCategories: SpecialCategory[];
    trafficRanges: TrafficRange[];
    users?: User[];
  };
}

interface FilterFormData {
  search: string;
  status: string;
  category: string;
  user_id: string;
  featured: string;
  min_da: string;
  max_da: string;
  min_dr: string;
  max_dr: string;
  min_backlinks: string;
  max_backlinks: string;
  link_type: string;
  min_price: string;
  max_price: string;
  min_sale_price: string;
  max_sale_price: string;
  min_traffic: string;
  max_traffic: string;
  min_spam_score: string;
  max_spam_score: string;
  special_category: string;
  min_special_price: string;
  max_special_price: string;
}

export default function WebsitesTable({ initialData }: WebsitesTableProps) {
  const [websites, setWebsites] = useState<Website[]>(initialData?.websites || []);
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<Category[]>(initialData?.categories || []);
  const [specialCategories, setSpecialCategories] = useState<SpecialCategory[]>(initialData?.specialCategories || []);
  const [users, setUsers] = useState<User[]>(initialData?.users || []);
  const [trafficRanges, setTrafficRanges] = useState<TrafficRange[]>(initialData?.trafficRanges || []);
  const [pagination, setPagination] = useState<PaginationData>(initialData?.pagination || {
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState<FilterFormData>({
    search: '',
    status: '',
    category: '',
    user_id: '',
    featured: '',
    min_da: '',
    max_da: '',
    min_dr: '',
    max_dr: '',
    min_backlinks: '',
    max_backlinks: '',
    link_type: '',
    min_price: '',
    max_price: '',
    min_sale_price: '',
    max_sale_price: '',
    min_traffic: '',
    max_traffic: '',
    min_spam_score: '',
    max_spam_score: '',
    special_category: '',
    min_special_price: '',
    max_special_price: ''
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();
  const router = useRouter();

  const canCreateWebsite = hasPermission(PERMISSIONS.WEBSITES_CREATE);
  const canEditWebsite = hasPermission(PERMISSIONS.WEBSITES_UPDATE);
  const canDeleteWebsite = hasPermission(PERMISSIONS.WEBSITES_DELETE);
  const canToggleStatus = hasPermission(PERMISSIONS.WEBSITES_UPDATE);
  const canExport = hasPermission(PERMISSIONS.WEBSITES_EXPORT);
  const canBulkDelete = hasPermission(PERMISSIONS.WEBSITES_BULK_DELETE);

  const fetchWebsites = useCallback(async (page = 1, appliedFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString()
      });

      Object.entries(appliedFilters).forEach(([key, value]) => {
        if (value && value !== '') {
          params.append(key, value);
        }
      });

      const response = await fetch(`/api/backend/admin/websites?${params}`);
      const data = await response.json();

      if (response.ok) {
        setWebsites(data.websites);
        setCategories(data.categories || []);
        setSpecialCategories(data.specialCategories || []);
        setUsers(data.users || []);
        setTrafficRanges(data.trafficRanges || []);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view websites');
        } else {
          toast.error(data.error || 'Failed to fetch websites');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch websites');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  const handleFilterChange = (key: keyof FilterFormData, value: string) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleApplyFilters = (e: React.FormEvent) => {
    e.preventDefault();
    fetchWebsites(1);
  };

  const handleResetFilters = () => {
    const resetFilters = {
      search: '',
      status: '',
      category: '',
      user_id: '',
      featured: '',
      min_da: '',
      max_da: '',
      min_dr: '',
      max_dr: '',
      min_backlinks: '',
      max_backlinks: '',
      link_type: '',
      min_price: '',
      max_price: '',
      min_sale_price: '',
      max_sale_price: '',
      min_traffic: '',
      max_traffic: '',
      min_spam_score: '',
      max_spam_score: '',
      special_category: '',
      min_special_price: '',
      max_special_price: ''
    };
    setFilters(resetFilters);
    fetchWebsites(1, resetFilters);
  };

  const handlePageChange = (page: number) => {
    fetchWebsites(page);
  };

  const formatTraffic = (trafficValue: string) => {
    if (!trafficValue) return 'N/A';
    try {
      const trafficNum = parseInt(trafficValue);
      if (isNaN(trafficNum)) return trafficValue;
      if (trafficNum >= 1000) {
        const inK = trafficNum / 1000;
        return inK % 1 === 0 ? `${inK}k` : `${inK.toFixed(1)}k`;
      }
      return trafficNum.toString();
    } catch {
      return trafficValue;
    }
  };

  const formatBacklinks = (backlinks: number | null) => {
    if (backlinks === null || backlinks === undefined) return 'N/A';
    if (backlinks >= 1000000) return `${(backlinks / 1000000).toFixed(1)}M`;
    if (backlinks >= 1000) return `${(backlinks / 1000).toFixed(1)}k`;
    return backlinks.toString();
  };

  const toggleWebsiteStatus = async (websiteId: string, newStatus: 'active' | 'inactive' | 'sold_out') => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update website status');
      return;
    }
    try {
      const response = await fetch(`/api/backend/admin/websites/${websiteId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      const data = await response.json();
      if (response.ok) {
        toast.success(`Website status updated to ${newStatus} successfully`);
        fetchWebsites(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update website status');
      }
    } catch (error) {
      toast.error('Failed to update website status');
      console.error(error);
    }
  };

  const handleDeleteClick = (website: Website) => {
    if (!canDeleteWebsite) {
      toast.error('You do not have permission to delete websites');
      return;
    }
    showAlert({
      title: 'Delete Website',
      message: `Are you sure you want to delete "${website.name}"? This action cannot be undone.`,
      confirmText: 'Delete Website',
      cancelText: 'Cancel',
      onConfirm: () => deleteWebsite(website.id),
    });
  };

  const handleEditPage = (websiteId: string) => {
    if (!canEditWebsite) {
      toast.error('You do not have permission to edit websites');
      return;
    }
    router.push(`/admin/dashboard/websites/edit/${websiteId}`);
  };

  const deleteWebsite = async (websiteId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/websites/${websiteId}`, {
        method: 'DELETE',
      });
      const data = await response.json();
      if (response.ok) {
        toast.success('Website deleted successfully');
        fetchWebsites(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete website');
      }
    } catch (error) {
      toast.error('Failed to delete website');
      console.error(error);
    }
  };

  const handleBulkDelete = async (selectedIds: string[]) => {
    if (!canBulkDelete) {
      toast.error('You do not have permission to delete websites in bulk');
      return;
    }
    try {
      const response = await fetch('/api/backend/admin/websites/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });
      const data = await response.json();
      if (response.ok) {
        if (data.skipped?.length > 0) {
          toast.success(`${data.deletedCount} website${data.deletedCount !== 1 ? 's' : ''} deleted, ${data.skipped.length} skipped`);
        } else {
          toast.success(`${data.deletedCount} website${data.deletedCount !== 1 ? 's' : ''} deleted`);
        }
        fetchWebsites(pagination.page);
      } else {
        toast.error(data.error || 'Bulk delete failed');
      }
    } catch {
      toast.error('Bulk delete failed');
    }
  };

  const handleExport = async () => {
    if (!canExport) {
      toast.error('You do not have permission to export websites');
      return;
    }
    try {
      const params = new URLSearchParams();
      Object.entries(filters).forEach(([key, value]) => {
        if (value && value !== '') {
          params.append(key, value);
        }
      });
      params.append('export', 'true');

      const response = await fetch(`/api/backend/admin/websites/export?${params}`);
      if (!response.ok) throw new Error('Export failed');

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `websites-export-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('Export completed successfully');
    } catch (error) {
      console.error('Export error:', error);
      toast.error('Failed to export websites');
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-success-bg text-var-success">
            Active
          </span>
        );
      case 'inactive':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-warning-bg text-var-warning">
            Inactive
          </span>
        );
      case 'sold_out':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-danger-bg text-var-danger">
            Sold Out
          </span>
        );
      default:
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-surface-hover text-var-text-muted">
            Unknown
          </span>
        );
    }
  };

  const getLinkTypeBadge = (linkType: string) => {
    return linkType === 'Dofollow' ? (
      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-success-bg text-var-success">
        Do-Follow
      </span>
    ) : (
      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-surface-hover text-var-text-muted">
        No-Follow
      </span>
    );
  };

  const getPriceDisplay = (website: Website) => {
    if (website.sale_price !== null && website.sale_price !== undefined) {
      if (website.sale_price === 0) {
        return (
          <div className="flex items-center space-x-2">
            <span className="text-sm line-through text-var-text-muted">
              ${website.base_price}
            </span>
            <span className="text-sm font-bold text-var-success">
              FREE
            </span>
          </div>
        );
      } else if (website.sale_price > 0) {
        return (
          <div className="flex items-center space-x-2">
            <span className="text-sm line-through text-var-text-muted">
              ${website.base_price}
            </span>
            <span className="text-sm font-bold text-var-danger">
              ${website.sale_price}
            </span>
          </div>
        );
      }
    }
    return (
      <span className="text-sm font-medium text-var-text">
        ${website.base_price}
      </span>
    );
  };

  const getSpecialNichesDisplay = (website: Website) => {
    const nicheEntries = Object.entries(website.niche_pricing || {});
    
    if (nicheEntries.length === 0) {
      return <span className="text-xs text-var-text-muted italic">No special pricing</span>;
    }

    const specialNicheNames = nicheEntries.map(([categoryId, price]) => {
      const category = specialCategories.find(cat => cat.id === categoryId);
      return {
        name: category?.name || `Category ${categoryId.substring(0, 8)}...`,
        price: price
      };
    });

    return (
      <div className="space-y-1">
        {specialNicheNames.slice(0, 2).map((niche, idx) => (
          <div key={idx} className="flex items-center justify-between text-xs">
            <span className="font-medium text-var-accent-purple truncate max-w-25">
              {niche.name}
            </span>
            <span className="font-bold text-var-success">
              ${niche.price}
            </span>
          </div>
        ))}
        {specialNicheNames.length > 2 && (
          <div className="text-xs text-var-text-muted">
            +{specialNicheNames.length - 2} more special niches
          </div>
        )}
      </div>
    );
  };

  const getUserDisplay = (website: Website) => {
    if (website.user_name) return website.user_name;
    if (website.user_email) return website.user_email;
    return '—';
  };

  const hasActiveFilters = Object.values(filters).some(value => value && value !== '');
  const activeFilterCount = Object.values(filters).filter(v => v && v !== '').length;

  const columns: TableColumn<Website>[] = [
    {
      key: 'website',
      label: 'Website',
      render: (website) => (
        <div>
          <div className="text-sm font-medium text-var-text">
            {website.name}
          </div>
          <div className="text-sm text-var-text-muted">
            {website.domain}
          </div>
          <code className="text-xs font-mono text-var-text-secondary bg-var-surface-hover px-2 py-1 rounded mt-1 inline-block">
            /{website.slug}
          </code>
        </div>
      )
    },
    {
      key: 'metrics',
      label: 'Metrics',
      render: (website) => (
        <div className="space-y-1">
          <div className="flex items-center space-x-4">
            {website.da !== null && (
              <div className="flex items-center">
                <span className="text-xs font-medium text-var-text-muted mr-1">
                  DA:
                </span>
                <span className="text-sm font-medium text-var-text">
                  {website.da}
                </span>
              </div>
            )}
            {website.dr !== null && (
              <div className="flex items-center">
                <span className="text-xs font-medium text-var-text-muted mr-1">
                  DR:
                </span>
                <span className="text-sm font-medium text-var-text">
                  {website.dr}
                </span>
              </div>
            )}
          </div>
          {website.spam_score !== null && (
            <div className="flex items-center">
              <span className="text-xs font-medium text-var-text-muted mr-1">
                Spam:
              </span>
              <span className={`text-sm font-medium ${
                website.spam_score < 30 ? 'text-var-success' : 
                website.spam_score < 60 ? 'text-var-warning' : 'text-var-danger'
              }`}>
                {website.spam_score}
              </span>
            </div>
          )}
          {website.traffic && (
            <div className="text-xs text-var-text-muted">
              Traffic: {formatTraffic(website.traffic)}
            </div>
          )}
        </div>
      )
    },
    {
      key: 'backlinks_type',
      label: 'Backlinks / Type',
      render: (website) => (
        <div className="space-y-2">
          <div className="text-sm font-medium text-var-text">
            {website.backlinks !== null ? formatBacklinks(website.backlinks) : 'N/A'}
          </div>
          <div>{getLinkTypeBadge(website.link_type)}</div>
        </div>
      )
    },
    {
      key: 'pricing',
      label: 'Pricing',
      render: (website) => (
        <div>
          {getPriceDisplay(website)}
          <div className="text-xs text-var-text-muted mt-1">
            Content: ${website.content_service_price}
          </div>
          {website.sale_price !== null && website.sale_price !== undefined && website.sale_price > 0 && (
            <div className="text-xs font-medium mt-1 text-var-danger">
              Sale Active
            </div>
          )}
        </div>
      )
    },
    {
      key: 'niches',
      label: 'Niches',
      render: (website) => (
        website.niche_names && website.niche_names.length > 0 ? (
          <div className="flex flex-wrap gap-1">
            {website.niche_names.slice(0, 3).map((nicheName, idx) => (
              <span key={idx} className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-var-primary-muted text-var-primary">
                {nicheName}
              </span>
            ))}
            {website.niche_names.length > 3 && (
              <span className="text-xs text-var-text-muted">
                +{website.niche_names.length - 3}
              </span>
            )}
          </div>
        ) : (
          <span className="text-xs text-var-text-muted italic">
            No niches
          </span>
        )
      )
    },
    {
      key: 'special_niches',
      label: 'Special Niches',
      render: (website) => getSpecialNichesDisplay(website)
    },
    {
      key: 'owner',
      label: 'Owner',
      render: (website) => (
        <span className="text-sm text-var-text-secondary">
          {getUserDisplay(website)}
        </span>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (website) => getStatusBadge(website.status)
    },
    {
      key: 'category',
      label: 'Category',
      render: (website) => (
        website.category_name ? (
          <span className="text-sm font-medium text-var-text">
            {website.category_name}
          </span>
        ) : (
          <span className="text-sm text-var-text-muted italic">
            None
          </span>
        )
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (website) => (
        <span className="text-sm text-var-text-muted">
          {new Date(website.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  const actions: TableAction<Website>[] = [
    ...(canEditWebsite ? [{
      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: (website: Website) => handleEditPage(website.id),
      condition: () => canEditWebsite,
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit website'
    }] : []),
    
    ...(canToggleStatus ? [{
      key: 'toggle-status',
      icon: (website: Website) => {
        if (website.status === 'active') {
          return (
            <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>
          );
        } else if (website.status === 'inactive') {
          return (
            <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>
          );
        } else {
          return (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" 
              />
            </svg>
          );
        }
      },
      onClick: (website: Website) => {
        const nextStatus: 'active' | 'inactive' | 'sold_out' = 
          website.status === 'active' ? 'inactive' : 
          website.status === 'inactive' ? 'sold_out' : 'active';
        toggleWebsiteStatus(website.id, nextStatus);
      },
      condition: () => canToggleStatus,
      className: (website: Website) => {
        if (website.status === 'active') return 'text-var-success hover:text-var-success/80 hover:bg-var-success-bg';
        if (website.status === 'inactive') return 'text-var-warning hover:text-var-warning/80 hover:bg-var-warning-bg';
        return 'text-var-text-muted hover:text-var-text hover:bg-var-surface-hover';
      },
      title: (website: Website) => {
        if (website.status === 'active') return 'Deactivate website';
        if (website.status === 'inactive') return 'Mark as sold out';
        return 'Activate website';
      }
    }] : []),

    ...(canDeleteWebsite ? [{
      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: (website: Website) => handleDeleteClick(website),
      condition: () => canDeleteWebsite,
      className: 'text-var-danger hover:text-var-danger/80 hover:bg-var-danger-bg',
      title: 'Delete website'
    }] : [])
  ];

  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/20',
      requiresConfirm: true,
      confirmTitle: 'Delete selected websites',
      confirmMessage: (count: number) =>
        `Are you sure you want to delete ${count} website${count !== 1 ? 's' : ''}? This action cannot be undone.`,
      onClick: handleBulkDelete,
    }] : []),
  ];

  useEffect(() => {
    if (!initialData) {
      fetchWebsites();
    }
  }, [fetchWebsites, initialData]);

  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">
        <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">
              Website Management
            </h2>
            <p className="text-sm text-var-text-muted mt-1">
              {pagination.total} website{pagination.total !== 1 ? 's' : ''} found
              {activeFilterCount > 0 && (
                <span className="ml-2 px-2 py-1 text-xs font-medium bg-var-primary-muted text-var-primary rounded-full">
                  {activeFilterCount} filter{activeFilterCount !== 1 ? 's' : ''} active
                </span>
              )}
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            {canExport && (
              <button
                onClick={handleExport}
                className="inline-flex items-center px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-all duration-200"
              >
                <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                Export
              </button>
            )}
            
            {/* Toggle Filters Button */}
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="inline-flex items-center px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-all duration-200"
            >
              <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>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
              {activeFilterCount > 0 && !showFilters && (
                <span className="ml-2 px-1.5 py-0.5 text-xs font-medium bg-var-primary text-white rounded-full">
                  {activeFilterCount}
                </span>
              )}
            </button>
            
            {canCreateWebsite && (
              <Link
                href="/admin/dashboard/websites/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 Website
              </Link>
            )}
          </div>
        </div>

        {/* All Filters - Only show when showFilters is true */}
        {showFilters && (
          <form onSubmit={handleApplyFilters} className="mt-6 space-y-6">
            {/* Row 1: Search, Status, Featured, Link Type */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Search
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <svg className="h-4 w-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg>
                  </div>
                  <input
                    type="text"
                    value={filters.search}
                    onChange={(e) => handleFilterChange('search', e.target.value)}
                    placeholder="Search by name, slug, or domain..."
                    className="w-full pl-10 pr-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Status
                </label>
                <select
                  value={filters.status}
                  onChange={(e) => handleFilterChange('status', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All Status</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                  <option value="sold_out">Sold Out</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Featured
                </label>
                <select
                  value={filters.featured}
                  onChange={(e) => handleFilterChange('featured', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All</option>
                  <option value="true">Featured Only</option>
                  <option value="false">Not Featured</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Link Type
                </label>
                <select
                  value={filters.link_type}
                  onChange={(e) => handleFilterChange('link_type', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All Types</option>
                  <option value="Dofollow">Do-Follow</option>
                  <option value="Nofollow">No-Follow</option>
                </select>
              </div>
            </div>

            {/* Row 2: DA, DR, Spam Score, Backlinks */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  DA Range (0-100)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_da}
                    onChange={(e) => handleFilterChange('min_da', e.target.value)}
                    placeholder="Min"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_da}
                    onChange={(e) => handleFilterChange('max_da', e.target.value)}
                    placeholder="Max"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  DR Range (0-100)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_dr}
                    onChange={(e) => handleFilterChange('min_dr', e.target.value)}
                    placeholder="Min"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_dr}
                    onChange={(e) => handleFilterChange('max_dr', e.target.value)}
                    placeholder="Max"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Spam Score (0-100)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_spam_score}
                    onChange={(e) => handleFilterChange('min_spam_score', e.target.value)}
                    placeholder="Min"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_spam_score}
                    onChange={(e) => handleFilterChange('max_spam_score', e.target.value)}
                    placeholder="Max"
                    min="0"
                    max="100"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Backlinks Range
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_backlinks}
                    onChange={(e) => handleFilterChange('min_backlinks', e.target.value)}
                    placeholder="Min"
                    min="0"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_backlinks}
                    onChange={(e) => handleFilterChange('max_backlinks', e.target.value)}
                    placeholder="Max"
                    min="0"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>
            </div>

            {/* Row 3: Main Category, Website Owner, Special Category, Traffic Range */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Main Category
                </label>
                <select
                  value={filters.category}
                  onChange={(e) => handleFilterChange('category', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All Categories</option>
                  {categories.map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Website Owner
                </label>
                <select
                  value={filters.user_id}
                  onChange={(e) => handleFilterChange('user_id', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All Users</option>
                  {users.map((user) => (
                    <option key={user.id} value={user.id}>
                      {user.display_name || `${user.first_name} ${user.last_name}`.trim() || user.email}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Special Category
                </label>
                <select
                  value={filters.special_category}
                  onChange={(e) => handleFilterChange('special_category', e.target.value)}
                  className="w-full px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text"
                >
                  <option value="">All Special Categories</option>
                  {specialCategories.map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Traffic Range
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_traffic}
                    onChange={(e) => handleFilterChange('min_traffic', e.target.value)}
                    placeholder="Min"
                    min="0"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_traffic}
                    onChange={(e) => handleFilterChange('max_traffic', e.target.value)}
                    placeholder="Max"
                    min="0"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
                <div className="mt-2">
                  <select
                    onChange={(e) => {
                      const selectedRange = trafficRanges.find(range => range.label === e.target.value);
                      if (selectedRange) {
                        setFilters(prev => ({
                          ...prev,
                          min_traffic: selectedRange.min.toString(),
                          max_traffic: selectedRange.max ? selectedRange.max.toString() : ''
                        }));
                      }
                    }}
                    className="w-full px-3 py-1.5 border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text text-sm"
                  >
                    <option value="">Select Preset</option>
                    {trafficRanges.map((range) => (
                      <option key={range.label} value={range.label}>
                        {range.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>

            {/* Row 4: Base Price, Sale Price, Special Price */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Base Price Range ($)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_price}
                    onChange={(e) => handleFilterChange('min_price', e.target.value)}
                    placeholder="Min"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_price}
                    onChange={(e) => handleFilterChange('max_price', e.target.value)}
                    placeholder="Max"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Sale Price Range ($)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_sale_price}
                    onChange={(e) => handleFilterChange('min_sale_price', e.target.value)}
                    placeholder="Min"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_sale_price}
                    onChange={(e) => handleFilterChange('max_sale_price', e.target.value)}
                    placeholder="Max"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
                <p className="text-xs text-var-text-muted mt-1">
                  Filters websites with active sales
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Special Price Range ($)
                </label>
                <div className="flex space-x-2">
                  <input
                    type="number"
                    value={filters.min_special_price}
                    onChange={(e) => handleFilterChange('min_special_price', e.target.value)}
                    placeholder="Min"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                  <input
                    type="number"
                    value={filters.max_special_price}
                    onChange={(e) => handleFilterChange('max_special_price', e.target.value)}
                    placeholder="Max"
                    min="0"
                    step="0.01"
                    className="w-1/2 px-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted"
                  />
                </div>
                <p className="text-xs text-var-text-muted mt-1">
                  {filters.special_category ? 'For selected special category' : 'For any special category'}
                </p>
              </div>
            </div>

            {/* Filter Actions */}
            <div className="flex items-center justify-between pt-4 border-t border-var-border">
              <div className="text-sm text-var-text-muted">
                {hasActiveFilters ? (
                  <span className="inline-flex items-center">
                    <svg className="w-4 h-4 mr-2 text-var-primary" 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>
                    Active filters applied
                  </span>
                ) : (
                  <span className="text-var-text-muted">No filters applied</span>
                )}
              </div>
              
              <div className="flex space-x-3">
                <button
                  type="button"
                  onClick={handleResetFilters}
                  className="px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors duration-200"
                >
                  Reset All
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 text-sm font-medium text-white bg-var-primary rounded-xl hover:bg-var-primary-hover transition-colors duration-200"
                >
                  Apply Filters
                </button>
              </div>
            </div>
          </form>
        )}
      </div>

      {/* Table */}
      <DataTable
        data={websites}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No websites found"
        emptyDescription={hasActiveFilters ? "Try adjusting your filters" : "Get started by creating your first website"}
        onCreateNew={canCreateWebsite && !hasActiveFilters ? () => {
          router.push('/admin/dashboard/websites/new');
        } : undefined}
        createNewLabel="Create your first website →"
        keyExtractor={(website) => website.id}
      />

      {/* Pagination */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}