import React, { useState, useEffect } from 'react';
import {
  Shield, UserPlus, UserCheck, Edit2, Trash2, X, Check,
  Mail, Lock, User, Eye, EyeOff, AlertCircle, CheckCircle,
  Search, Filter, Calendar, Download, RefreshCw, Award,
  Clock, Settings, Users, Key, Save, Ban, Copy, Smartphone,
  Globe, BarChart, ShoppingBag, BookOpen, MessageSquare,
  Layers, Image, Phone, Share2, Code, Layout, Home, Sparkles,
  Package, Menu, ArrowLeft
} from 'lucide-react';

// API Base URL
const API_BASE = '/api/admin';

// Tenant auth header helper
const tenantHeaders = (extra: Record<string, string> = {}): Record<string, string> => {
  const h: Record<string, string> = { 'Content-Type': 'application/json', ...extra };
  const token = localStorage.getItem('tenant_token');
  if (token) h['X-Tenant-Token'] = token;
  return h;
};

// Permission icons mapping
const PERMISSION_ICONS: { [key: string]: any } = {
  'dashboard': BarChart,
  'orders': ShoppingBag,
  'leads': Users,
  'products': Package,
  'testimonials': MessageSquare,
  'landing-editor': Layers,
  'appearance': Image,
  'hero': Home,
  'contact': Phone,
  'social': Share2,
  'pixel': Code,
  'moderators': Shield
};

// Available sections for permissions
const PERMISSION_SECTIONS: Array<{ id: string, label: string, icon: string, description: string, color: string }> = [
  { id: 'dashboard', label: 'Dashboard', icon: 'BarChart', description: 'View analytics and reports', color: 'blue' },
  { id: 'orders', label: 'Orders', icon: 'ShoppingBag', description: 'Manage customer orders', color: 'green' },
  { id: 'leads', label: 'Leads', icon: 'Users', description: 'View and manage leads', color: 'purple' },
  { id: 'products', label: 'Products', icon: 'Package', description: 'Manage products inventory', color: 'amber' },
  { id: 'testimonials', label: 'Testimonials', icon: 'MessageSquare', description: 'Manage customer reviews', color: 'pink' },
  { id: 'landing-editor', label: 'Landing Page Editor', icon: 'Layers', description: 'Edit landing pages', color: 'indigo' },
  { id: 'appearance', label: 'Branding', icon: 'Image', description: 'Manage site branding', color: 'cyan' },
  { id: 'hero', label: 'Hero Section', icon: 'Home', description: 'Edit homepage hero', color: 'orange' },
  { id: 'contact', label: 'Contact Info', icon: 'Phone', description: 'Manage contact details', color: 'teal' },
  { id: 'social', label: 'Social Media', icon: 'Share2', description: 'Manage social links', color: 'sky' },
  { id: 'pixel', label: 'GTM Settings', icon: 'Code', description: 'Manage tracking codes', color: 'gray' }
];

// Permission interface
interface Permission {
  canView: boolean;
  canEdit: boolean;
  canDelete: boolean;
}

interface Moderator {
  id: number;
  email: string;
  name: string;
  role: 'moderator';
  permissions: {
    [key: string]: Permission;
  };
  created_at: string;
  updated_at?: string;
  last_login?: string;
}

interface ModeratorFormData {
  email: string;
  password: string;
  name: string;
  permissions: {
    [key: string]: Permission;
  };
}

const ModeratorManagement: React.FC = () => {
  const [moderators, setModerators] = useState<Moderator[]>([]);
  const [loading, setLoading] = useState(true);
  const [showEditor, setShowEditor] = useState(false);
  const [editingModerator, setEditingModerator] = useState<Moderator | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [notification, setNotification] = useState<{ message: string, type: 'success' | 'error', visible: boolean }>({
    message: '',
    type: 'success',
    visible: false
  });
  const [filterStatus, setFilterStatus] = useState<'all' | 'active' | 'inactive'>('all');
  const [selectedModerator, setSelectedModerator] = useState<Moderator | null>(null);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');

  // Form state
  const [formData, setFormData] = useState<ModeratorFormData>({
    email: '',
    password: '',
    name: '',
    permissions: {}
  });

  // Initialize permissions for all sections
  useEffect(() => {
    const initialPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      initialPermissions[section.id] = {
        canView: false,
        canEdit: false,
        canDelete: false
      };
    });
    setFormData(prev => ({ ...prev, permissions: initialPermissions }));
  }, []);

  // Load moderators on mount
  useEffect(() => {
    fetchModerators();
  }, []);

  // Show toast notification
  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setNotification({ message, type, visible: true });
    setTimeout(() => setNotification(prev => ({ ...prev, visible: false })), 3000);
  };

  // =====================================================
  // ✅ FIXED: Fetch all moderators with better error handling
  // =====================================================
  const fetchModerators = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE}/moderators`, {
        method: 'GET',
        credentials: 'include',
        headers: tenantHeaders()
      });

      // ✅ 401 = session expired, need to re-login
      if (response.status === 401) {
        showToast('Session expired. Please logout and login again.', 'error');
        setLoading(false);
        return;
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.success) {
        const moderatorsWithPermissions = (data.data || []).map((mod: any) => ({
          ...mod,
          permissions: mod.permissions || {}
        }));
        setModerators(moderatorsWithPermissions);
      } else {
        showToast(data.error || 'Failed to fetch moderators', 'error');
      }
    } catch (error) {
      console.error('Error fetching moderators:', error);
      showToast('Network error. Please try again.', 'error');
    } finally {
      setLoading(false);
    }
  };

  // Handle permission change
  const handlePermissionChange = (
    sectionId: string,
    field: keyof Permission,
    value: boolean
  ) => {
    setFormData(prev => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [sectionId]: {
          ...(prev.permissions[sectionId] || { canView: false, canEdit: false, canDelete: false }),
          [field]: value
        }
      }
    }));
  };

  // Handle select all permissions for a section
  const handleSelectAll = (sectionId: string, checked: boolean) => {
    setFormData(prev => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [sectionId]: {
          canView: checked,
          canEdit: checked,
          canDelete: checked
        }
      }
    }));
  };

  // Handle select all for all sections
  const handleSelectAllSections = (checked: boolean) => {
    const newPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      newPermissions[section.id] = {
        canView: checked,
        canEdit: checked,
        canDelete: checked
      };
    });
    setFormData(prev => ({ ...prev, permissions: newPermissions }));
  };

  // Quick preset - Give view only permissions
  const setViewOnlyPreset = () => {
    const newPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      newPermissions[section.id] = {
        canView: true,
        canEdit: false,
        canDelete: false
      };
    });
    setFormData(prev => ({ ...prev, permissions: newPermissions }));
    showToast('View-only permissions applied', 'success');
  };

  // Quick preset - Give full access (view + edit)
  const setFullAccessPreset = () => {
    const newPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      newPermissions[section.id] = {
        canView: true,
        canEdit: true,
        canDelete: false
      };
    });
    setFormData(prev => ({ ...prev, permissions: newPermissions }));
    showToast('Full access permissions applied', 'success');
  };

  // Quick preset - Give super access (view + edit + delete)
  const setSuperAccessPreset = () => {
    const newPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      newPermissions[section.id] = {
        canView: true,
        canEdit: true,
        canDelete: true
      };
    });
    setFormData(prev => ({ ...prev, permissions: newPermissions }));
    showToast('Super access permissions applied', 'success');
  };

  // Validate form
  const validateForm = (): boolean => {
    if (!formData.name.trim()) {
      showToast('Name is required', 'error');
      return false;
    }
    if (!formData.email.trim()) {
      showToast('Email is required', 'error');
      return false;
    }
    if (!editingModerator && !formData.password.trim()) {
      showToast('Password is required for new moderator', 'error');
      return false;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      showToast('Invalid email format', 'error');
      return false;
    }

    if (!editingModerator && formData.password.length < 6) {
      showToast('Password must be at least 6 characters', 'error');
      return false;
    }

    return true;
  };

  // =====================================================
  // ✅ FIXED: Create new moderator with better error handling
  // =====================================================
  const createModerator = async () => {
    if (!validateForm()) return;

    try {
      const payload = {
        email: formData.email.trim(),
        password: formData.password,
        name: formData.name.trim(),
        permissions: formData.permissions
      };

      console.log('Creating moderator:', payload);

      const response = await fetch(`${API_BASE}/moderators`, {
        method: 'POST',
        headers: tenantHeaders(),
        body: JSON.stringify(payload),
        credentials: 'include'
      });

      const data = await response.json();

      if (data.success) {
        showToast('✨ Moderator created successfully!', 'success');
        setShowEditor(false);
        resetForm();
        fetchModerators();
      } else {
        showToast(data.error || 'Failed to create moderator', 'error');
      }
    } catch (error) {
      console.error('Error creating moderator:', error);
      showToast('Network error. Please try again.', 'error');
    }
  };

  // =====================================================
  // ✅ FIXED: Update moderator with better error handling
  // =====================================================
  const updateModerator = async () => {
    if (!editingModerator) return;

    try {
      const payload: any = {
        id: editingModerator.id,
        name: formData.name.trim(),
        permissions: formData.permissions
      };

      // Only include password if it's provided
      if (formData.password.trim()) {
        payload.password = formData.password;
      }

      console.log('Updating moderator:', payload);

      const response = await fetch(`${API_BASE}/moderators/${payload.id}`, {
        method: 'PUT',
        headers: tenantHeaders(),
        body: JSON.stringify(payload),
        credentials: 'include'
      });

      const data = await response.json();

      if (data.success) {
        showToast('✅ Moderator updated successfully!', 'success');
        setShowEditor(false);
        setEditingModerator(null);
        resetForm();
        fetchModerators();
      } else {
        showToast(data.error || 'Failed to update moderator', 'error');
      }
    } catch (error) {
      console.error('Error updating moderator:', error);
      showToast('Network error. Please try again.', 'error');
    }
  };

  // =====================================================
  // ✅ FIXED: Delete moderator with better error handling
  // =====================================================
  const deleteModerator = async (id: number, email: string) => {
    if (!confirm(`Are you sure you want to delete moderator "${email}"? This action cannot be undone.`)) {
      return;
    }

    try {
      const response = await fetch(`${API_BASE}/moderators/${id}`, {
        method: 'DELETE',
        headers: tenantHeaders(),
        credentials: 'include'
      });

      const data = await response.json();

      if (data.success) {
        showToast('🗑️ Moderator deleted successfully!', 'success');
        fetchModerators();
      } else {
        showToast(data.error || 'Failed to delete moderator', 'error');
      }
    } catch (error) {
      console.error('Error deleting moderator:', error);
      showToast('Network error. Please try again.', 'error');
    }
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      email: '',
      password: '',
      name: '',
      permissions: {}
    });
    const initialPermissions: { [key: string]: Permission } = {};
    PERMISSION_SECTIONS.forEach(section => {
      initialPermissions[section.id] = {
        canView: false,
        canEdit: false,
        canDelete: false
      };
    });
    setFormData(prev => ({ ...prev, permissions: initialPermissions }));
    setShowPassword(false);
  };

  // Edit moderator
  const editModerator = (moderator: Moderator) => {
    setEditingModerator(moderator);
    setFormData({
      email: moderator.email,
      password: '',
      name: moderator.name || '',
      permissions: moderator.permissions || {}
    });
    setShowEditor(true);
  };

  // Cancel edit/create
  const cancelEdit = () => {
    setShowEditor(false);
    setEditingModerator(null);
    setSelectedModerator(null);
    resetForm();
  };

  // View moderator details
  const viewModerator = (moderator: Moderator) => {
    setSelectedModerator(moderator);
  };

  // Add new moderator
  const addNewModerator = () => {
    setEditingModerator(null);
    resetForm();
    setShowEditor(true);
  };

  // Filter moderators based on search and status
  const filteredModerators = moderators.filter(mod => {
    const matchesSearch = mod.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (mod.name && mod.name.toLowerCase().includes(searchTerm.toLowerCase()));

    return matchesSearch;
  });

  // Check if any permission is selected
  const hasAnyPermission = (): boolean => {
    return Object.values(formData.permissions).some((perm: Permission) =>
      perm?.canView || perm?.canEdit || perm?.canDelete
    );
  };

  // Count total permissions
  const countPermissions = (permissions: { [key: string]: Permission }): number => {
    let count = 0;
    Object.values(permissions).forEach((perm: Permission) => {
      if (perm?.canView) count++;
      if (perm?.canEdit) count++;
      if (perm?.canDelete) count++;
    });
    return count;
  };

  // Get permission level color
  const getPermissionLevel = (permissions: { [key: string]: Permission }): { label: string, color: string } => {
    const totalSections = Object.keys(permissions).length;
    const viewCount = Object.values(permissions).filter((p: Permission) => p?.canView).length;
    const editCount = Object.values(permissions).filter((p: Permission) => p?.canEdit).length;
    const deleteCount = Object.values(permissions).filter((p: Permission) => p?.canDelete).length;

    if (deleteCount === totalSections) return { label: 'Super Admin', color: 'purple' };
    if (editCount === totalSections) return { label: 'Full Access', color: 'blue' };
    if (viewCount === totalSections) return { label: 'View Only', color: 'green' };
    if (viewCount > 0) return { label: 'Custom', color: 'orange' };
    return { label: 'No Access', color: 'gray' };
  };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950">
      {/* Notification Toast */}
      {notification.visible && (
        <div className={`fixed top-6 right-6 z-[9999] px-6 py-4 rounded-2xl shadow-2xl animate-slide-in-right flex items-center gap-3 ${notification.type === 'success' ? 'bg-gradient-to-r from-green-500 to-green-600 text-white' : 'bg-gradient-to-r from-red-500 to-red-600 text-white'
          }`}>
          {notification.type === 'success' ? <CheckCircle size={20} /> : <AlertCircle size={20} />}
          <span className="font-bold">{notification.message}</span>
        </div>
      )}

      {/* Main Content Area */}
      <div className="p-6 md:p-10">
        {!showEditor ? (
          /* ==================== LIST VIEW ==================== */
          <div className="space-y-6 animate-fade-in-up">
            {/* Header Section with Stats */}
            <div className="bg-gradient-to-br from-purple-600 to-purple-800 text-white p-8 rounded-[40px] shadow-xl">
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div>
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-14 h-14 bg-white/20 backdrop-blur rounded-2xl flex items-center justify-center">
                      <Shield size={32} className="text-white" />
                    </div>
                    <h1 className="text-4xl md:text-5xl font-black">Moderator Hub</h1>
                  </div>
                  <p className="text-white/80 text-lg ml-16">
                    Manage your team members and their access permissions
                  </p>
                </div>

                {/* Stats Cards */}
                <div className="flex gap-4">
                  <div className="bg-white/10 backdrop-blur px-6 py-4 rounded-2xl text-center">
                    <div className="text-3xl font-black">{moderators.length}</div>
                    <div className="text-xs text-white/70 uppercase tracking-wider">Total</div>
                  </div>
                  <div className="bg-white/10 backdrop-blur px-6 py-4 rounded-2xl text-center">
                    <div className="text-3xl font-black">
                      {moderators.filter(m => countPermissions(m.permissions) > 0).length}
                    </div>
                    <div className="text-xs text-white/70 uppercase tracking-wider">Active</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Action Bar */}
            <div className="bg-white dark:bg-slate-900 p-6 rounded-[32px] border shadow-sm flex flex-col md:flex-row gap-4 justify-between">
              <div className="flex-1 flex gap-3">
                {/* Search */}
                <div className="relative flex-1">
                  <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
                  <input
                    type="text"
                    placeholder="Search by name or email..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-12 pr-4 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold transition-all"
                  />
                </div>

                {/* View Toggle */}
                <div className="flex bg-slate-100 dark:bg-slate-800 p-1 rounded-2xl">
                  <button
                    onClick={() => setViewMode('grid')}
                    className={`p-3 rounded-xl transition-all ${viewMode === 'grid' ? 'bg-white shadow-md' : 'text-slate-400'}`}
                  >
                    <Layout size={20} />
                  </button>
                  <button
                    onClick={() => setViewMode('list')}
                    className={`p-3 rounded-xl transition-all ${viewMode === 'list' ? 'bg-white shadow-md' : 'text-slate-400'}`}
                  >
                    <Menu size={20} />
                  </button>
                </div>

                {/* Refresh Button */}
                <button
                  onClick={fetchModerators}
                  className="p-4 bg-slate-100 dark:bg-slate-800 rounded-2xl hover:bg-slate-200 transition-all"
                  title="Refresh"
                >
                  <RefreshCw size={20} className={loading ? 'animate-spin' : ''} />
                </button>
              </div>

              {/* Add Button */}
              <button
                onClick={addNewModerator}
                className="px-8 py-4 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white rounded-2xl font-black flex items-center gap-3 transition-all shadow-lg shadow-purple-600/20 active:scale-95"
              >
                <UserPlus size={20} />
                <span>Add Moderator</span>
              </button>
            </div>

            {/* Moderators Grid/List View */}
            {loading ? (
              <div className="bg-white dark:bg-slate-900 p-20 rounded-[40px] border shadow-sm text-center">
                <div className="animate-spin rounded-full h-16 w-16 border-4 border-purple-600 border-t-transparent mx-auto"></div>
                <p className="text-slate-400 mt-6 text-lg font-medium">Loading moderators...</p>
              </div>
            ) : filteredModerators.length === 0 ? (
              <div className="bg-white dark:bg-slate-900 p-20 rounded-[40px] border shadow-sm text-center">
                <div className="w-24 h-24 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-6">
                  <Shield size={48} className="text-purple-400" />
                </div>
                <h3 className="text-3xl font-black text-slate-400 mb-3">No Moderators Found</h3>
                <p className="text-slate-400 text-lg">
                  {searchTerm ? 'No moderators match your search.' : 'Click "Add Moderator" to create your first moderator.'}
                </p>
              </div>
            ) : viewMode === 'grid' ? (
              /* Grid View */
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredModerators.map(mod => {
                  const level = getPermissionLevel(mod.permissions);

                  return (
                    <div
                      key={mod.id}
                      className="bg-white dark:bg-slate-900 rounded-[32px] border shadow-sm hover:shadow-xl transition-all group overflow-hidden"
                    >
                      {/* Card Header with Color Accent */}
                      <div className={`h-2 bg-gradient-to-r from-${level.color}-500 to-${level.color}-600`}></div>

                      <div className="p-6">
                        {/* Avatar and Actions */}
                        <div className="flex justify-between items-start mb-4">
                          <div className={`w-16 h-16 rounded-2xl bg-gradient-to-br from-${level.color}-500 to-${level.color}-600 flex items-center justify-center text-white shadow-lg`}>
                            <UserCheck size={32} />
                          </div>
                          <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                            <button
                              onClick={() => viewModerator(mod)}
                              className="p-2.5 bg-slate-100 text-slate-600 rounded-xl hover:bg-slate-200 transition-all"
                              title="View Details"
                            >
                              <Eye size={16} />
                            </button>
                            <button
                              onClick={() => editModerator(mod)}
                              className="p-2.5 bg-blue-50 text-blue-600 rounded-xl hover:bg-blue-100 transition-all"
                              title="Edit"
                            >
                              <Edit2 size={16} />
                            </button>
                            <button
                              onClick={() => deleteModerator(mod.id, mod.email)}
                              className="p-2.5 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all"
                              title="Delete"
                            >
                              <Trash2 size={16} />
                            </button>
                          </div>
                        </div>

                        {/* User Info */}
                        <div className="mb-4">
                          <h3 className="text-xl font-black mb-1">{mod.name || 'Unnamed'}</h3>
                          <p className="text-slate-400 text-sm flex items-center gap-1">
                            <Mail size={12} />
                            {mod.email}
                          </p>
                        </div>

                        {/* Permission Level Badge */}
                        <div className={`inline-flex items-center gap-1 px-3 py-1.5 bg-${level.color}-50 text-${level.color}-700 rounded-full text-xs font-black mb-4`}>
                          <Shield size={12} />
                          {level.label}
                        </div>

                        {/* Permission Summary */}
                        <div className="pt-4 border-t border-slate-100 dark:border-slate-800">
                          <div className="flex justify-between text-sm mb-3">
                            <span className="text-slate-400">Access</span>
                            <span className="font-black">
                              {Object.values(mod.permissions).filter((p: Permission) => p?.canView).length} / {PERMISSION_SECTIONS.length}
                            </span>
                          </div>

                          {/* Permission Dots */}
                          <div className="flex gap-1">
                            {PERMISSION_SECTIONS.slice(0, 8).map(section => {
                              const perm = mod.permissions[section.id];
                              return (
                                <div
                                  key={section.id}
                                  className={`w-6 h-6 rounded-full ${perm?.canView
                                      ? perm?.canEdit
                                        ? perm?.canDelete
                                          ? 'bg-purple-500'
                                          : 'bg-blue-500'
                                        : 'bg-green-500'
                                      : 'bg-slate-200'
                                    }`}
                                  title={`${section.label}: ${perm?.canView ? 'View' : 'No'}${perm?.canEdit ? ' + Edit' : ''}${perm?.canDelete ? ' + Delete' : ''}`}
                                />
                              );
                            })}
                            {PERMISSION_SECTIONS.length > 8 && (
                              <div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center text-[10px] font-black">
                                +{PERMISSION_SECTIONS.length - 8}
                              </div>
                            )}
                          </div>
                        </div>

                        {/* Footer */}
                        <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800 flex justify-between items-center text-xs text-slate-400">
                          <span className="flex items-center gap-1">
                            <Calendar size={12} />
                            {new Date(mod.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock size={12} />
                            {new Date(mod.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
                          </span>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              /* List View */
              <div className="bg-white dark:bg-slate-900 rounded-[32px] border shadow-sm overflow-hidden">
                <table className="w-full">
                  <thead className="bg-slate-50 dark:bg-slate-800 text-xs font-black uppercase text-slate-400">
                    <tr>
                      <th className="px-6 py-4 text-left">Moderator</th>
                      <th className="px-6 py-4 text-left">Role</th>
                      <th className="px-6 py-4 text-left">Permissions</th>
                      <th className="px-6 py-4 text-left">Joined</th>
                      <th className="px-6 py-4 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredModerators.map(mod => {
                      const level = getPermissionLevel(mod.permissions);
                      const viewCount = Object.values(mod.permissions).filter((p: Permission) => p?.canView).length;
                      const editCount = Object.values(mod.permissions).filter((p: Permission) => p?.canEdit).length;

                      return (
                        <tr key={mod.id} className="border-t hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              <div className={`w-10 h-10 rounded-xl bg-gradient-to-br from-${level.color}-500 to-${level.color}-600 flex items-center justify-center text-white`}>
                                <UserCheck size={20} />
                              </div>
                              <div>
                                <p className="font-black">{mod.name || 'Unnamed'}</p>
                                <p className="text-sm text-slate-400">{mod.email}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`px-3 py-1.5 bg-${level.color}-50 text-${level.color}-700 rounded-full text-xs font-black`}>
                              {level.label}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-black">{viewCount}</span>
                              <span className="text-xs text-slate-400">sections</span>
                              {editCount > 0 && (
                                <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">
                                  {editCount} edit
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="px-6 py-4 text-sm text-slate-400">
                            {new Date(mod.created_at).toLocaleDateString('en-US', {
                              year: 'numeric',
                              month: 'short',
                              day: 'numeric'
                            })}
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex justify-end gap-2">
                              <button
                                onClick={() => viewModerator(mod)}
                                className="p-2 hover:bg-slate-100 rounded-lg transition-colors"
                                title="View Details"
                              >
                                <Eye size={18} className="text-slate-400" />
                              </button>
                              <button
                                onClick={() => editModerator(mod)}
                                className="p-2 hover:bg-blue-50 rounded-lg transition-colors"
                                title="Edit"
                              >
                                <Edit2 size={18} className="text-blue-600" />
                              </button>
                              <button
                                onClick={() => deleteModerator(mod.id, mod.email)}
                                className="p-2 hover:bg-red-50 rounded-lg transition-colors"
                                title="Delete"
                              >
                                <Trash2 size={18} className="text-red-600" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}

            {/* Moderator Details Modal */}
            {selectedModerator && (
              <div className="fixed inset-0 z-[1000] bg-black/50 backdrop-blur-sm flex items-center justify-center p-4">
                <div className="bg-white dark:bg-slate-900 rounded-[48px] max-w-2xl w-full p-8 shadow-2xl">
                  <div className="flex justify-between items-center mb-6">
                    <h3 className="text-2xl font-black flex items-center gap-2">
                      <UserCheck className="text-purple-600" size={24} />
                      Moderator Details
                    </h3>
                    <button
                      onClick={() => setSelectedModerator(null)}
                      className="p-2 hover:bg-slate-100 rounded-full"
                    >
                      <X size={20} />
                    </button>
                  </div>

                  <div className="space-y-6">
                    <div className="flex items-center gap-4 p-6 bg-purple-50 rounded-3xl">
                      <div className="w-20 h-20 bg-purple-600 rounded-2xl flex items-center justify-center text-white">
                        <UserCheck size={40} />
                      </div>
                      <div>
                        <h4 className="text-2xl font-black">{selectedModerator.name}</h4>
                        <p className="text-purple-600">{selectedModerator.email}</p>
                        <p className="text-sm text-slate-400 mt-1">
                          Joined: {new Date(selectedModerator.created_at).toLocaleString()}
                        </p>
                      </div>
                    </div>

                    <h5 className="font-black text-lg mb-3">Permissions</h5>
                    <div className="grid grid-cols-2 gap-3">
                      {PERMISSION_SECTIONS.map(section => {
                        const perm = selectedModerator.permissions[section.id];
                        if (!perm?.canView) return null;

                        return (
                          <div key={section.id} className="p-4 bg-slate-50 rounded-2xl border">
                            <div className="font-bold mb-2">{section.label}</div>
                            <div className="flex gap-2 text-xs">
                              {perm.canView && <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full">View</span>}
                              {perm.canEdit && <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded-full">Edit</span>}
                              {perm.canDelete && <span className="px-2 py-1 bg-red-100 text-red-700 rounded-full">Delete</span>}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  <div className="flex justify-end mt-8">
                    <button
                      onClick={() => setSelectedModerator(null)}
                      className="px-8 py-3 bg-purple-600 text-white rounded-2xl font-black hover:bg-purple-700"
                    >
                      Close
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        ) : (
          /* ==================== FULL PAGE EDITOR ==================== */
          <div className="animate-fade-in-up">
            {/* Editor Header */}
            <div className="sticky top-0 z-10 mb-8 bg-white/95 dark:bg-slate-900/95 backdrop-blur-xl p-6 rounded-[32px] border border-slate-200 flex justify-between items-center shadow-xl">
              <button
                onClick={cancelEdit}
                className="font-black text-sm uppercase flex items-center gap-2 px-6 py-3 bg-slate-100 dark:bg-slate-800 rounded-xl text-slate-500 hover:text-purple-600 transition-all"
              >
                <ArrowLeft size={18} />
                Back to Moderators
              </button>
              <div className="flex items-center gap-4">
                <h2 className="text-2xl font-black">
                  {editingModerator ? 'Edit Moderator' : 'Create New Moderator'}
                </h2>
              </div>
            </div>

            {/* Editor Content - Full Width */}
            <div className="space-y-8 pb-20">
              {/* Quick Presets */}
              {!editingModerator && (
                <div className="p-8 bg-gradient-to-r from-purple-50 to-blue-50 rounded-[40px]">
                  <h4 className="font-black mb-6 flex items-center gap-2 text-2xl">
                    <Sparkles size={24} className="text-purple-600" />
                    Quick Permission Presets
                  </h4>
                  <div className="flex gap-4 flex-wrap">
                    <button
                      onClick={setViewOnlyPreset}
                      className="flex-1 min-w-[200px] p-6 bg-white rounded-3xl shadow-sm hover:shadow-md transition-all text-left border-2 border-transparent hover:border-green-200"
                    >
                      <div className="w-12 h-12 bg-green-100 rounded-2xl flex items-center justify-center mb-4">
                        <Eye size={24} className="text-green-600" />
                      </div>
                      <div className="font-black text-lg text-green-600">👁️ View Only</div>
                      <div className="text-sm text-slate-400 mt-1">Can view all sections</div>
                    </button>
                    <button
                      onClick={setFullAccessPreset}
                      className="flex-1 min-w-[200px] p-6 bg-white rounded-3xl shadow-sm hover:shadow-md transition-all text-left border-2 border-transparent hover:border-blue-200"
                    >
                      <div className="w-12 h-12 bg-blue-100 rounded-2xl flex items-center justify-center mb-4">
                        <Edit2 size={24} className="text-blue-600" />
                      </div>
                      <div className="font-black text-lg text-blue-600">✏️ Full Access</div>
                      <div className="text-sm text-slate-400 mt-1">View + Edit (No delete)</div>
                    </button>
                    <button
                      onClick={setSuperAccessPreset}
                      className="flex-1 min-w-[200px] p-6 bg-white rounded-3xl shadow-sm hover:shadow-md transition-all text-left border-2 border-transparent hover:border-purple-200"
                    >
                      <div className="w-12 h-12 bg-purple-100 rounded-2xl flex items-center justify-center mb-4">
                        <Shield size={24} className="text-purple-600" />
                      </div>
                      <div className="font-black text-lg text-purple-600">⚡ Super Access</div>
                      <div className="text-sm text-slate-400 mt-1">View + Edit + Delete</div>
                    </button>
                  </div>
                </div>
              )}

              {/* Basic Info Cards */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-white dark:bg-slate-900 p-8 rounded-[40px] border shadow-sm col-span-2">
                  <h3 className="text-2xl font-black mb-6 flex items-center gap-2">
                    <User size={24} className="text-purple-600" />
                    Basic Information
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                        Full Name *
                      </label>
                      <input
                        type="text"
                        placeholder="e.g., Rahim Miah"
                        className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold text-lg transition-all"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      />
                    </div>
                    <div>
                      <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                        Email Address *
                      </label>
                      <input
                        type="email"
                        placeholder="moderator@shophyfast.com"
                        className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold text-lg transition-all"
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        disabled={!!editingModerator}
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="text-xs font-black uppercase text-slate-400 ml-2 mb-2 block">
                        <Lock size={14} className="inline mr-1" />
                        {editingModerator ? 'New Password (leave blank to keep current)' : 'Password *'}
                      </label>
                      <div className="relative">
                        <input
                          type={showPassword ? 'text' : 'password'}
                          placeholder={editingModerator ? 'Enter new password' : 'Enter password (min. 6 characters)'}
                          className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border-2 border-transparent focus:border-purple-600 font-bold text-lg pr-12 transition-all"
                          value={formData.password}
                          onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-purple-600"
                        >
                          {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Summary Card */}
                <div className={`p-8 rounded-[40px] border shadow-sm ${hasAnyPermission() ? 'bg-green-50 border-green-200' : 'bg-amber-50 border-amber-200'
                  }`}>
                  <div className="flex items-start gap-4">
                    {hasAnyPermission() ? (
                      <CheckCircle className="text-green-600 shrink-0" size={32} />
                    ) : (
                      <AlertCircle className="text-amber-600 shrink-0" size={32} />
                    )}
                    <div>
                      <h5 className="font-black text-lg mb-2">
                        {hasAnyPermission() ? 'Ready to Go!' : 'Action Required'}
                      </h5>
                      <p className="text-sm">
                        {hasAnyPermission() ? (
                          <>
                            <span className="block font-black text-purple-600 text-2xl my-2">
                              {Object.values(formData.permissions).filter((p: Permission) => p?.canView).length}
                            </span>
                            sections with access
                          </>
                        ) : (
                          'No permissions selected. Moderator will not be able to access any section.'
                        )}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Permissions Section */}
              <div className="bg-white dark:bg-slate-900 p-8 rounded-[40px] border shadow-sm">
                <div className="flex items-center justify-between mb-8">
                  <h3 className="text-2xl font-black flex items-center gap-2">
                    <Shield size={24} className="text-purple-600" />
                    Section Permissions
                  </h3>
                  <label className="flex items-center gap-3 cursor-pointer bg-purple-50 px-6 py-3 rounded-2xl hover:bg-purple-100 transition-all">
                    <input
                      type="checkbox"
                      className="w-5 h-5 text-purple-600 rounded focus:ring-purple-600"
                      onChange={(e) => handleSelectAllSections(e.target.checked)}
                      checked={Object.values(formData.permissions).every((p: Permission) => p?.canView && p?.canEdit && p?.canDelete)}
                    />
                    <span className="font-black">Select All (Full Access)</span>
                  </label>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                  {PERMISSION_SECTIONS.map(section => {
                    const sectionPerm = formData.permissions[section.id] || { canView: false, canEdit: false, canDelete: false };
                    const IconComponent = PERMISSION_ICONS[section.id] || Shield;

                    return (
                      <div
                        key={section.id}
                        className="p-6 bg-slate-50 dark:bg-slate-800 rounded-3xl border-2 border-transparent hover:border-purple-200 transition-all group"
                      >
                        <div className="flex items-center justify-between mb-4">
                          <div className="flex items-center gap-3">
                            <div className={`w-12 h-12 rounded-xl bg-${section.color}-100 text-${section.color}-600 flex items-center justify-center`}>
                              <IconComponent size={24} />
                            </div>
                            <div>
                              <h5 className="font-black text-lg">{section.label}</h5>
                              <p className="text-xs text-slate-400">{section.description}</p>
                            </div>
                          </div>
                          <label className="flex items-center gap-2 text-sm opacity-0 group-hover:opacity-100 transition-opacity">
                            <input
                              type="checkbox"
                              className="w-4 h-4 text-purple-600 rounded focus:ring-purple-600"
                              onChange={(e) => handleSelectAll(section.id, e.target.checked)}
                              checked={sectionPerm.canView && sectionPerm.canEdit && sectionPerm.canDelete}
                            />
                            <span className="font-bold">All</span>
                          </label>
                        </div>

                        <div className="grid grid-cols-3 gap-3">
                          <label className={`flex items-center justify-center gap-1 p-4 rounded-xl cursor-pointer transition-all ${sectionPerm.canView ? 'bg-green-100 text-green-700' : 'bg-white text-slate-400 hover:bg-green-50'
                            }`}>
                            <input
                              type="checkbox"
                              className="hidden"
                              checked={sectionPerm.canView}
                              onChange={(e) => handlePermissionChange(section.id, 'canView', e.target.checked)}
                            />
                            <Eye size={18} />
                            <span className="text-sm font-medium">View</span>
                          </label>
                          <label className={`flex items-center justify-center gap-1 p-4 rounded-xl cursor-pointer transition-all ${sectionPerm.canEdit ? 'bg-blue-100 text-blue-700' : 'bg-white text-slate-400 hover:bg-blue-50'
                            }`}>
                            <input
                              type="checkbox"
                              className="hidden"
                              checked={sectionPerm.canEdit}
                              onChange={(e) => handlePermissionChange(section.id, 'canEdit', e.target.checked)}
                            />
                            <Edit2 size={18} />
                            <span className="text-sm font-medium">Edit</span>
                          </label>
                          <label className={`flex items-center justify-center gap-1 p-4 rounded-xl cursor-pointer transition-all ${sectionPerm.canDelete ? 'bg-red-100 text-red-700' : 'bg-white text-slate-400 hover:bg-red-50'
                            }`}>
                            <input
                              type="checkbox"
                              className="hidden"
                              checked={sectionPerm.canDelete}
                              onChange={(e) => handlePermissionChange(section.id, 'canDelete', e.target.checked)}
                            />
                            <Trash2 size={18} />
                            <span className="text-sm font-medium">Delete</span>
                          </label>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Action Buttons - Sticky Footer */}
              <div className="sticky bottom-6 bg-white dark:bg-slate-900 p-6 rounded-[32px] border shadow-2xl flex gap-4">
                <button
                  onClick={editingModerator ? updateModerator : createModerator}
                  className="flex-1 py-5 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white rounded-2xl font-black text-lg flex items-center justify-center gap-3 shadow-xl shadow-purple-600/20 transition-all active:scale-95"
                >
                  <Save size={20} />
                  {editingModerator ? 'Update Moderator' : 'Create Moderator'}
                </button>
                <button
                  onClick={cancelEdit}
                  className="px-10 py-5 bg-slate-100 dark:bg-slate-800 text-slate-600 rounded-2xl font-black hover:bg-slate-200 transition-all"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes slide-in-right {
          0% { transform: translateX(100%); opacity: 0; }
          100% { transform: translateX(0); opacity: 1; }
        }
        .animate-slide-in-right {
          animation: slide-in-right 0.3s ease-out forwards;
        }
        
        @keyframes fade-in-up {
          0% { opacity: 0; transform: translateY(20px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.5s ease-out forwards;
        }
      `}</style>
    </div>
  );
};

export default ModeratorManagement;