import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { 
  Shield, Search, Save, Info, ChevronDown, ChevronRight, Users, Calendar, 
  Package, DollarSign, FileText, Settings as SettingsIcon, BarChart3, 
  MessageSquare, Briefcase, Building2, Layers, Lock, Unlock, Eye, 
  CheckCircle2, XCircle, AlertTriangle, Sparkles, UserCog, Plus, Trash2, Copy
} from "lucide-react";
import PageHeader from "../components/common/PageHeader";
import { useToast } from "@/components/ui/use-toast";
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger,
} from "@/components/ui/hover-card";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

// Layer hierarchy configuration
const LAYER_HIERARCHY = [
  { 
    id: "admin", 
    name: "KROW Admin", 
    icon: Shield,
    color: "from-red-500 to-red-700",
    bgColor: "bg-red-50",
    borderColor: "border-red-200",
    textColor: "text-red-700",
    description: "Full platform control and oversight",
    level: 1
  },
  { 
    id: "procurement", 
    name: "Procurement", 
    icon: Briefcase,
    color: "from-[#0A39DF] to-[#1C323E]",
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
    textColor: "text-blue-700",
    description: "Vendor management and rate control",
    level: 2
  },
  { 
    id: "operator", 
    name: "Operator", 
    icon: Building2,
    color: "from-emerald-500 to-emerald-700",
    bgColor: "bg-emerald-50",
    borderColor: "border-emerald-200",
    textColor: "text-emerald-700",
    description: "Enterprise-wide operations",
    level: 3
  },
  { 
    id: "sector", 
    name: "Sector", 
    icon: Layers,
    color: "from-purple-500 to-purple-700",
    bgColor: "bg-purple-50",
    borderColor: "border-purple-200",
    textColor: "text-purple-700",
    description: "Location-specific management",
    level: 4
  },
  { 
    id: "client", 
    name: "Client", 
    icon: Users,
    color: "from-green-500 to-green-700",
    bgColor: "bg-green-50",
    borderColor: "border-green-200",
    textColor: "text-green-700",
    description: "Service ordering and review",
    level: 5
  },
  { 
    id: "vendor", 
    name: "Vendor", 
    icon: Package,
    color: "from-amber-500 to-amber-700",
    bgColor: "bg-amber-50",
    borderColor: "border-amber-200",
    textColor: "text-amber-700",
    description: "Workforce supply and management",
    level: 6
  },
  { 
    id: "workforce", 
    name: "Workforce", 
    icon: Users,
    color: "from-slate-500 to-slate-700",
    bgColor: "bg-slate-50",
    borderColor: "border-slate-200",
    textColor: "text-slate-700",
    description: "Shift work and earnings",
    level: 7
  }
];

// Permission modules for each layer
const PERMISSION_MODULES = {
  admin: [
    {
      id: "platform",
      name: "Platform Administration",
      icon: Shield,
      permissions: [
        { id: "platform.users", name: "Manage All Users", description: "Create, edit, delete users across all layers", critical: true },
        { id: "platform.settings", name: "System Settings", description: "Configure platform-wide settings", critical: true },
        { id: "platform.roles", name: "Role Management", description: "Define and modify role permissions", critical: true },
        { id: "platform.audit", name: "Audit Logs", description: "Access complete system audit trail" },
        { id: "platform.integrations", name: "Integrations", description: "Manage external system connections" },
      ]
    },
    {
      id: "hierarchy",
      name: "Hierarchy Control",
      icon: Layers,
      permissions: [
        { id: "hierarchy.enterprises", name: "Enterprise Management", description: "Create and manage enterprises" },
        { id: "hierarchy.sectors", name: "Sector Management", description: "Create and manage sectors" },
        { id: "hierarchy.partners", name: "Partner Management", description: "Manage partner relationships" },
        { id: "hierarchy.policies", name: "Global Policies", description: "Set enterprise-wide policies", critical: true },
      ]
    },
    {
      id: "financial",
      name: "Financial Control",
      icon: DollarSign,
      permissions: [
        { id: "financial.all", name: "All Financials", description: "Access all financial data", critical: true },
        { id: "financial.payments", name: "Process Payments", description: "Approve and process all payments" },
        { id: "financial.payroll", name: "Payroll Management", description: "Process workforce payroll" },
        { id: "financial.reports", name: "Financial Reports", description: "Generate P&L and analytics" },
      ]
    }
  ],
  
  procurement: [
    {
      id: "vendors",
      name: "Vendor Management",
      icon: Package,
      permissions: [
        { id: "vendors.view", name: "View Vendors", description: "Access vendor directory" },
        { id: "vendors.onboard", name: "Onboard Vendors", description: "Add new vendors to platform" },
        { id: "vendors.edit", name: "Edit Vendors", description: "Modify vendor information" },
        { id: "vendors.compliance", name: "Compliance Review", description: "Review COI, W9, certifications" },
        { id: "vendors.approve", name: "Approve/Suspend", description: "Change vendor approval status", critical: true },
        { id: "vendors.performance", name: "Performance Data", description: "Access scorecards and KPIs" },
      ]
    },
    {
      id: "rates",
      name: "Rate Management",
      icon: DollarSign,
      permissions: [
        { id: "rates.view", name: "View Rates", description: "See all vendor pricing" },
        { id: "rates.create", name: "Create Rate Cards", description: "Set up new rate cards" },
        { id: "rates.edit", name: "Edit Rates", description: "Modify existing rates" },
        { id: "rates.approve", name: "Approve Rates", description: "Approve vendor rate submissions", critical: true },
        { id: "rates.markup", name: "Markup Rules", description: "Define markup percentages" },
      ]
    },
    {
      id: "orders",
      name: "Order Oversight",
      icon: Calendar,
      permissions: [
        { id: "orders.viewAll", name: "View All Orders", description: "Access orders across sectors" },
        { id: "orders.assign", name: "Assign Vendors", description: "Match vendors with orders" },
        { id: "orders.monitor", name: "Monitor Fulfillment", description: "Track order completion" },
      ]
    }
  ],

  operator: [
    {
      id: "events",
      name: "Event Management",
      icon: Calendar,
      permissions: [
        { id: "events.view", name: "View Events", description: "See events in my enterprise" },
        { id: "events.create", name: "Create Events", description: "Create new event orders" },
        { id: "events.edit", name: "Edit Events", description: "Modify event details" },
        { id: "events.cancel", name: "Cancel Events", description: "Cancel event orders" },
        { id: "events.approve", name: "Approve Events", description: "Approve sector event requests" },
        { id: "events.financials", name: "Event Financials", description: "View event costs and billing" },
      ]
    },
    {
      id: "sectors",
      name: "Sector Oversight",
      icon: Building2,
      permissions: [
        { id: "sectors.view", name: "View Sectors", description: "See sectors under my enterprise" },
        { id: "sectors.settings", name: "Sector Settings", description: "Configure sector policies" },
        { id: "sectors.vendors", name: "Assign Vendors", description: "Approve vendors for sectors" },
      ]
    },
    {
      id: "workforce",
      name: "Workforce Management",
      icon: Users,
      permissions: [
        { id: "workforce.view", name: "View Workforce", description: "See staff across enterprise" },
        { id: "workforce.assign", name: "Assign Staff", description: "Schedule staff for events" },
        { id: "workforce.timesheets", name: "Approve Timesheets", description: "Review and approve hours" },
        { id: "workforce.performance", name: "Staff Performance", description: "Access ratings and reviews" },
      ]
    }
  ],

  sector: [
    {
      id: "events",
      name: "Location Events",
      icon: Calendar,
      permissions: [
        { id: "events.viewMy", name: "View My Events", description: "See events at my location" },
        { id: "events.request", name: "Request Events", description: "Submit new event requests" },
        { id: "events.editMy", name: "Edit My Events", description: "Modify my event details" },
        { id: "events.costs", name: "View Costs", description: "See event billing information" },
      ]
    },
    {
      id: "staff",
      name: "Staff Management",
      icon: Users,
      permissions: [
        { id: "staff.view", name: "View Staff", description: "See staff at my sector" },
        { id: "staff.schedule", name: "Schedule Staff", description: "Assign staff to shifts" },
        { id: "staff.timesheets", name: "Approve Timesheets", description: "Review hours worked" },
        { id: "staff.rate", name: "Rate Performance", description: "Provide staff feedback" },
      ]
    },
    {
      id: "vendors",
      name: "Vendor Access",
      icon: Package,
      permissions: [
        { id: "vendors.viewApproved", name: "View Vendors", description: "See approved vendors" },
        { id: "vendors.rates", name: "View Rates", description: "Access rate cards" },
        { id: "vendors.request", name: "Request Services", description: "Submit staffing requests" },
      ]
    }
  ],

  client: [
    {
      id: "orders",
      name: "My Orders",
      icon: Calendar,
      permissions: [
        { id: "orders.view", name: "View Orders", description: "See my event orders" },
        { id: "orders.create", name: "Create Orders", description: "Request staffing for events" },
        { id: "orders.edit", name: "Edit Orders", description: "Modify orders before confirmation" },
        { id: "orders.cancel", name: "Cancel Orders", description: "Cancel pending orders" },
        { id: "orders.status", name: "Track Status", description: "Monitor order fulfillment" },
      ]
    },
    {
      id: "vendors",
      name: "Vendor Selection",
      icon: Package,
      permissions: [
        { id: "vendors.browse", name: "Browse Vendors", description: "View available vendors" },
        { id: "vendors.rates", name: "View Rates", description: "See service pricing" },
        { id: "vendors.prefer", name: "Preferred Vendors", description: "Request specific vendors" },
      ]
    },
    {
      id: "billing",
      name: "Billing",
      icon: DollarSign,
      permissions: [
        { id: "billing.invoices", name: "View Invoices", description: "Access my invoices" },
        { id: "billing.download", name: "Download Invoices", description: "Export invoice PDFs" },
        { id: "billing.analytics", name: "Spend Analytics", description: "View spending trends" },
      ]
    }
  ],

  vendor: [
    {
      id: "orders",
      name: "Order Fulfillment",
      icon: Calendar,
      permissions: [
        { id: "orders.viewAssigned", name: "View Orders", description: "See assigned orders" },
        { id: "orders.respond", name: "Accept/Decline", description: "Respond to order requests" },
        { id: "orders.update", name: "Update Status", description: "Mark order progress" },
        { id: "orders.details", name: "Order Details", description: "Access requirements" },
      ]
    },
    {
      id: "workforce",
      name: "My Workforce",
      icon: Users,
      permissions: [
        { id: "workforce.view", name: "View Staff", description: "See my workforce" },
        { id: "workforce.add", name: "Add Staff", description: "Onboard new workers" },
        { id: "workforce.edit", name: "Edit Staff", description: "Update staff info" },
        { id: "workforce.assign", name: "Assign Staff", description: "Schedule for orders" },
        { id: "workforce.compliance", name: "Manage Compliance", description: "Track certifications" },
      ]
    },
    {
      id: "rates",
      name: "My Rates",
      icon: DollarSign,
      permissions: [
        { id: "rates.viewMy", name: "View Rates", description: "See my approved rates" },
        { id: "rates.propose", name: "Propose Rates", description: "Submit rate proposals" },
        { id: "rates.history", name: "Rate History", description: "Track rate changes" },
      ]
    },
    {
      id: "invoices",
      name: "Invoicing",
      icon: FileText,
      permissions: [
        { id: "invoices.view", name: "View Invoices", description: "Access my invoices" },
        { id: "invoices.create", name: "Create Invoices", description: "Generate invoices" },
        { id: "invoices.track", name: "Track Payments", description: "Monitor payment status" },
      ]
    }
  ],

  workforce: [
    {
      id: "shifts",
      name: "My Shifts",
      icon: Calendar,
      permissions: [
        { id: "shifts.view", name: "View Schedule", description: "See upcoming shifts" },
        { id: "shifts.clock", name: "Clock In/Out", description: "Record shift times" },
        { id: "shifts.timeoff", name: "Request Time Off", description: "Submit time off requests" },
        { id: "shifts.history", name: "Shift History", description: "See past shifts" },
      ]
    },
    {
      id: "profile",
      name: "My Profile",
      icon: Users,
      permissions: [
        { id: "profile.view", name: "View Profile", description: "See my worker profile" },
        { id: "profile.edit", name: "Edit Contact", description: "Update phone/email" },
        { id: "profile.availability", name: "Update Availability", description: "Set available times" },
        { id: "profile.certs", name: "Upload Certs", description: "Add certifications" },
      ]
    },
    {
      id: "earnings",
      name: "Earnings",
      icon: DollarSign,
      permissions: [
        { id: "earnings.view", name: "View Earnings", description: "See pay and hours" },
        { id: "earnings.timesheets", name: "View Timesheets", description: "Access timesheet records" },
        { id: "earnings.history", name: "Payment History", description: "See past payments" },
        { id: "earnings.download", name: "Download Stubs", description: "Export pay stubs" },
      ]
    }
  ]
};

// Default position templates
const DEFAULT_POSITION_TEMPLATES = [
  { id: "manager", position: "Manager", layer: "operator", description: "Full operational access", permissions: ["events.view", "events.create", "events.edit", "events.approve", "sectors.view", "workforce.view", "workforce.assign"] },
  { id: "supervisor", position: "Supervisor", layer: "sector", description: "Location-level management", permissions: ["events.viewMy", "events.request", "staff.view", "staff.schedule", "staff.timesheets"] },
  { id: "coordinator", position: "Coordinator", layer: "client", description: "Order coordination", permissions: ["orders.view", "orders.create", "orders.status", "vendors.browse"] },
  { id: "team_lead", position: "Team Lead", layer: "vendor", description: "Workforce team management", permissions: ["orders.viewAssigned", "workforce.view", "workforce.assign", "rates.viewMy"] },
  { id: "staff", position: "Staff Member", layer: "workforce", description: "Basic shift access", permissions: ["shifts.view", "shifts.clock", "profile.view", "earnings.view"] },
];

export default function Permissions() {
  const [activeTab, setActiveTab] = useState("layers");
  const [selectedLayer, setSelectedLayer] = useState("operator");
  const [searchTerm, setSearchTerm] = useState("");
  const [expandedModules, setExpandedModules] = useState({});
  const [permissions, setPermissions] = useState({});
  const [positionTemplates, setPositionTemplates] = useState(DEFAULT_POSITION_TEMPLATES);
  const [showAddPosition, setShowAddPosition] = useState(false);
  const [newPosition, setNewPosition] = useState({ position: "", description: "" });
  const [editingPosition, setEditingPosition] = useState(null);
  const { toast } = useToast();

  const { data: user } = useQuery({
    queryKey: ['current-user-permissions'],
    queryFn: () => base44.auth.me(),
  });

  const userRole = user?.user_role || user?.role || "admin";

  // Non-admin users can only see their own layer
  const effectiveLayer = userRole === "admin" ? selectedLayer : userRole;
  const selectedLayerConfig = LAYER_HIERARCHY.find(l => l.id === effectiveLayer);
  const modules = PERMISSION_MODULES[effectiveLayer] || [];

  // Filter layer hierarchy for non-admin users
  const visibleLayers = userRole === "admin" ? LAYER_HIERARCHY : LAYER_HIERARCHY.filter(l => l.id === userRole);

  // Initialize permissions with all enabled for demo
  React.useEffect(() => {
    const newPermissions = {};
    modules.forEach(module => {
      module.permissions.forEach(perm => {
        newPermissions[perm.id] = true;
      });
    });
    setPermissions(newPermissions);
    // Expand all modules by default
    const expanded = {};
    modules.forEach(m => expanded[m.id] = true);
    setExpandedModules(expanded);
  }, [selectedLayer]);

  const toggleModule = (moduleId) => {
    setExpandedModules(prev => ({
      ...prev,
      [moduleId]: !prev[moduleId]
    }));
  };

  const togglePermission = (permId) => {
    setPermissions(prev => ({
      ...prev,
      [permId]: !prev[permId]
    }));
  };

  const toggleAllInModule = (module, value) => {
    const newPerms = { ...permissions };
    module.permissions.forEach(p => {
      newPerms[p.id] = value;
    });
    setPermissions(newPerms);
  };

  const handleSave = () => {
    toast({
      title: "Permissions Saved",
      description: `${selectedLayerConfig.name} layer permissions updated successfully.`,
    });
  };

  const handleAddPosition = () => {
    if (!newPosition.position) return;
    const id = newPosition.position.toLowerCase().replace(/\s+/g, '_');
    setPositionTemplates([...positionTemplates, { ...newPosition, id, layer: effectiveLayer, permissions: [] }]);
    setNewPosition({ position: "", description: "" });
    setShowAddPosition(false);
    toast({ title: "Position Added", description: `${newPosition.position} template created.` });
  };

  const handleDeletePosition = (id) => {
    setPositionTemplates(positionTemplates.filter(p => p.id !== id));
    toast({ title: "Position Deleted", description: "Position template removed." });
  };

  const handleEditPositionPermissions = (position) => {
    setEditingPosition(position);
    setSelectedLayer(position.layer);
    // Load position's permissions
    const newPerms = {};
    position.permissions.forEach(p => newPerms[p] = true);
    setPermissions(newPerms);
  };

  const handleSavePositionPermissions = () => {
    if (!editingPosition) return;
    const enabledPerms = Object.entries(permissions).filter(([_, v]) => v).map(([k]) => k);
    setPositionTemplates(positionTemplates.map(p => 
      p.id === editingPosition.id ? { ...p, permissions: enabledPerms } : p
    ));
    setEditingPosition(null);
    toast({ title: "Position Updated", description: `${editingPosition.position} permissions saved.` });
  };

  const filteredModules = modules.map(module => ({
    ...module,
    permissions: module.permissions.filter(perm =>
      perm.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      perm.description.toLowerCase().includes(searchTerm.toLowerCase())
    )
  })).filter(module => module.permissions.length > 0);

  const enabledCount = Object.values(permissions).filter(Boolean).length;
  const totalCount = modules.reduce((sum, m) => sum + m.permissions.length, 0);



  return (
    <TooltipProvider>
      <div className="p-4 md:p-8 bg-slate-50 min-h-screen overflow-hidden">
        <div className="max-w-7xl mx-auto">
          <PageHeader 
            title="Permissions Management"
            subtitle="Configure access control for each layer in the KROW ecosystem"
          />

          {/* Tab Navigation */}
          <div className="bg-white rounded-xl border border-slate-200 p-1.5 inline-flex gap-1 mb-6 shadow-sm">
            <button
              onClick={() => { setActiveTab("layers"); setEditingPosition(null); }}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-medium transition-all ${
                activeTab === "layers" 
                  ? "bg-gradient-to-r from-[#0A39DF] to-[#1C323E] text-white shadow-md" 
                  : "text-slate-600 hover:bg-slate-100"
              }`}
            >
              <Layers className="w-4 h-4" />
              Layer Permissions
            </button>
            <button
              onClick={() => setActiveTab("positions")}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-medium transition-all ${
                activeTab === "positions" 
                  ? "bg-gradient-to-r from-[#0A39DF] to-[#1C323E] text-white shadow-md" 
                  : "text-slate-600 hover:bg-slate-100"
              }`}
            >
              <UserCog className="w-4 h-4" />
              Position Templates
            </button>
          </div>

          {activeTab === "positions" && !editingPosition && (
            <>
              {/* Position Templates */}
              <Card className="mb-4 border-slate-200 shadow-lg">
                <CardHeader className="bg-white border-b border-slate-200 py-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-[#0A39DF] flex items-center justify-center">
                        <UserCog className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <CardTitle className="text-slate-900 text-lg">Position Templates</CardTitle>
                        <p className="text-sm text-slate-500">Define default permissions for job positions</p>
                      </div>
                    </div>
                    <Button size="sm" onClick={() => setShowAddPosition(true)} className="bg-[#0A39DF] hover:bg-[#0831b8]">
                      <Plus className="w-4 h-4 mr-1" /> Add Position
                    </Button>
                  </div>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {positionTemplates.map((template) => {
                      const layerConfig = LAYER_HIERARCHY.find(l => l.id === template.layer);
                      const layerModules = PERMISSION_MODULES[template.layer] || [];
                      
                      // Get permission names for display
                      const permissionNames = template.permissions.map(permId => {
                        for (const module of layerModules) {
                          const found = module.permissions.find(p => p.id === permId);
                          if (found) return found.name;
                        }
                        return permId;
                      });
                      
                      return (
                        <div key={template.id} className={`p-4 rounded-xl border-2 ${layerConfig?.borderColor || 'border-slate-200'} bg-white`}>
                          <div className="flex items-start justify-between mb-2">
                            <div>
                              <h4 className="font-bold text-slate-900">{template.position}</h4>
                              <Badge className={`text-[10px] mt-1 ${layerConfig?.textColor || ''} bg-white border`}>
                                {layerConfig?.name || template.layer}
                              </Badge>
                            </div>
                            <div className="flex gap-1">
                              <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleEditPositionPermissions(template)}>
                                <Shield className="w-3.5 h-3.5 text-blue-600" />
                              </Button>
                              <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleDeletePosition(template.id)}>
                                <Trash2 className="w-3.5 h-3.5 text-red-500" />
                              </Button>
                            </div>
                          </div>
                          <p className="text-xs text-slate-600 mb-2">{template.description}</p>
                          <div className="mt-3 space-y-3">
                          {layerModules.map((module) => {
                            const ModuleIcon = module.icon;
                            const moduleEnabledCount = module.permissions.filter(p => template.permissions.includes(p.id)).length;
                            const allModuleEnabled = moduleEnabledCount === module.permissions.length;

                            return (
                              <div key={module.id} className="bg-white rounded-xl border border-slate-200 overflow-hidden">
                                {/* Module Header */}
                                <div className="flex items-center justify-between px-4 py-3 bg-slate-50 border-b border-slate-100">
                                  <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center">
                                      <ModuleIcon className="w-4 h-4 text-emerald-600" />
                                    </div>
                                    <div>
                                      <p className="text-sm font-semibold text-slate-900">{module.name}</p>
                                      <p className="text-[10px] text-slate-500">{moduleEnabledCount} of {module.permissions.length} enabled</p>
                                    </div>
                                  </div>
                                  <button
                                    className="flex items-center gap-1 text-[10px] text-slate-500 hover:text-slate-700"
                                    onClick={() => {
                                      const modulePermIds = module.permissions.map(p => p.id);
                                      let newPerms;
                                      if (allModuleEnabled) {
                                        newPerms = template.permissions.filter(p => !modulePermIds.includes(p));
                                      } else {
                                        newPerms = [...new Set([...template.permissions, ...modulePermIds])];
                                      }
                                      setPositionTemplates(positionTemplates.map(p => 
                                        p.id === template.id ? { ...p, permissions: newPerms } : p
                                      ));
                                      toast({ title: allModuleEnabled ? "Module Disabled" : "Module Enabled", description: `${module.name} permissions updated` });
                                    }}
                                  >
                                    <XCircle className="w-3 h-3" />
                                    {allModuleEnabled ? 'Disable All' : 'Enable All'}
                                  </button>
                                </div>

                                {/* Permissions List */}
                                <div className="divide-y divide-slate-100">
                                  {module.permissions.map((perm) => {
                                    const isEnabled = template.permissions.includes(perm.id);
                                    return (
                                      <div 
                                        key={perm.id} 
                                        className="flex items-center justify-between px-4 py-2.5 hover:bg-slate-50 cursor-pointer transition-colors"
                                        onClick={() => {
                                          const newPerms = isEnabled 
                                            ? template.permissions.filter(p => p !== perm.id)
                                            : [...template.permissions, perm.id];
                                          setPositionTemplates(positionTemplates.map(p => 
                                            p.id === template.id ? { ...p, permissions: newPerms } : p
                                          ));
                                          toast({ title: isEnabled ? "Permission Disabled" : "Permission Enabled", description: `${perm.name} ${isEnabled ? 'removed from' : 'added to'} ${template.position}` });
                                        }}
                                      >
                                        <div className="flex items-center gap-3">
                                          <div className="w-6 h-6 rounded-md bg-slate-100 flex items-center justify-center">
                                            <Unlock className="w-3 h-3 text-slate-400" />
                                          </div>
                                          <div>
                                            <p className="text-xs font-medium text-slate-900">{perm.name}</p>
                                            <p className="text-[10px] text-slate-500">{perm.description}</p>
                                          </div>
                                        </div>
                                        <div className={`w-10 h-5 rounded-full p-0.5 transition-colors ${isEnabled ? 'bg-emerald-500' : 'bg-slate-300'}`}>
                                          <div className={`w-4 h-4 rounded-full bg-white shadow transition-transform ${isEnabled ? 'translate-x-5' : 'translate-x-0'}`} />
                                        </div>
                                      </div>
                                    );
                                  })}
                                </div>
                              </div>
                            );
                          })}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </CardContent>
              </Card>

              {/* Add Position Dialog */}
              <Dialog open={showAddPosition} onOpenChange={setShowAddPosition}>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Add Position Template</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4 py-4">
                    <div>
                      <label className="text-sm font-medium">Position Title</label>
                      <Input
                        value={newPosition.position}
                        onChange={(e) => setNewPosition({ ...newPosition, position: e.target.value })}
                        placeholder="e.g., Regional Manager"
                        className="mt-1"
                      />
                    </div>

                    <div>
                      <label className="text-sm font-medium">Description</label>
                      <Input
                        value={newPosition.description}
                        onChange={(e) => setNewPosition({ ...newPosition, description: e.target.value })}
                        placeholder="Brief description of access level"
                        className="mt-1"
                      />
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowAddPosition(false)}>Cancel</Button>
                    <Button onClick={handleAddPosition} className="bg-[#0A39DF]">Create Position</Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </>
          )}

          {editingPosition && (
            <div className="mb-4 p-3 bg-purple-50 border border-purple-200 rounded-xl flex items-center justify-between">
              <div className="flex items-center gap-3">
                <UserCog className="w-5 h-5 text-purple-600" />
                <div>
                  <p className="font-bold text-purple-900">Editing: {editingPosition.position}</p>
                  <p className="text-xs text-purple-700">Configure permissions for this position template</p>
                </div>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => setEditingPosition(null)}>Cancel</Button>
                <Button size="sm" onClick={handleSavePositionPermissions} className="bg-purple-600 hover:bg-purple-700">
                  <Save className="w-4 h-4 mr-1" /> Save Position
                </Button>
              </div>
            </div>
          )}

          {(activeTab === "layers" || editingPosition) && (
          <>
          {/* Layer Hierarchy Visual */}
          <Card className="mb-4 border-slate-200 shadow-lg overflow-hidden">
            <CardHeader className="bg-slate-800 text-white">
              <div className="flex items-center gap-3">
                <Layers className="w-6 h-6" />
                <div>
                  <CardTitle className="text-white">KROW Ecosystem Layers</CardTitle>
                  <p className="text-slate-300 text-sm mt-1">Select a layer to configure its permissions</p>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-6 bg-gradient-to-b from-slate-100 to-white">
              {/* Horizontal Layer Flow */}
                  <div className="flex items-center justify-center gap-2 pb-2 flex-wrap">
                    {visibleLayers.map((layer, index) => {
                  const Icon = layer.icon;
                  const isSelected = effectiveLayer === layer.id;
                  
                  return (
                    <React.Fragment key={layer.id}>
                      <button
                        onClick={() => setSelectedLayer(layer.id)}
                        className={`flex-shrink-0 relative group transition-all duration-200 ${
                            isSelected ? 'scale-105 z-10' : 'hover:scale-102'
                          } ${userRole !== "admin" ? 'cursor-default' : ''}`}
                          disabled={userRole !== "admin"}
                        >
                          <div className={`
                            w-16 h-16 md:w-20 md:h-20 rounded-xl flex flex-col items-center justify-center gap-1 
                            transition-all duration-200 border-2
                            ${isSelected 
                              ? `bg-[#0A39DF] text-white shadow-lg border-transparent` 
                              : `${layer.bgColor} ${layer.borderColor} ${layer.textColor} hover:shadow-sm`
                            }
                          `}>
                          <Icon className={`w-5 h-5 md:w-6 md:h-6 ${isSelected ? 'text-white' : ''}`} />
                          <span className="text-[10px] md:text-xs font-bold text-center px-1 leading-tight">{layer.name}</span>
                        </div>
                      </button>
                      {index < visibleLayers.length - 1 && (
                        <div className="flex-shrink-0 w-4 md:w-6 h-0.5 bg-slate-300"></div>
                      )}
                    </React.Fragment>
                  );
                })}
              </div>

              {/* Selected Layer Info */}
              {selectedLayerConfig && (
                <div className={`mt-4 p-3 rounded-lg ${selectedLayerConfig.bgColor} ${selectedLayerConfig.borderColor} border`}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className={`w-8 h-8 rounded-lg bg-[#0A39DF] flex items-center justify-center`}>
                        <selectedLayerConfig.icon className="w-4 h-4 text-white" />
                      </div>
                      <div>
                        <h3 className={`font-bold text-sm ${selectedLayerConfig.textColor}`}>
                          {selectedLayerConfig.name} Layer
                        </h3>
                        <p className="text-xs text-slate-600">{selectedLayerConfig.description}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-lg font-bold text-slate-900">{enabledCount}/{totalCount}</p>
                      <p className="text-[10px] text-slate-500">enabled</p>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Search */}
          <div className="mb-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="Search permissions..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 h-10 bg-white border-slate-300 shadow-sm"
              />
            </div>
          </div>

          {/* Permission Modules */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 max-h-[calc(100vh-480px)] overflow-y-auto pb-4">
            {filteredModules.map((module) => {
              const Icon = module.icon;
              const isExpanded = expandedModules[module.id] !== false;
              const moduleEnabled = module.permissions.filter(p => permissions[p.id]).length;
              const moduleTotal = module.permissions.length;
              const allEnabled = moduleEnabled === moduleTotal;

              return (
                <Card key={module.id} className="border-slate-200 shadow-md overflow-hidden">
                  <CardHeader 
                    className={`cursor-pointer transition-colors ${
                      isExpanded ? 'bg-slate-100' : 'bg-white hover:bg-slate-50'
                    }`}
                    onClick={() => toggleModule(module.id)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        {isExpanded ? (
                          <ChevronDown className="w-5 h-5 text-slate-400" />
                        ) : (
                          <ChevronRight className="w-5 h-5 text-slate-400" />
                        )}
                        <div className={`w-10 h-10 rounded-xl bg-[#0A39DF] flex items-center justify-center`}>
                                  <Icon className="w-5 h-5 text-white" />
                                </div>
                        <div>
                          <CardTitle className="text-base">{module.name}</CardTitle>
                          <p className="text-xs text-slate-500 mt-0.5">
                            {moduleEnabled} of {moduleTotal} enabled
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => toggleAllInModule(module, !allEnabled)}
                              className="text-xs"
                            >
                              {allEnabled ? (
                                <><XCircle className="w-4 h-4 mr-1" /> Disable All</>
                              ) : (
                                <><CheckCircle2 className="w-4 h-4 mr-1" /> Enable All</>
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Toggle all permissions in this module</TooltipContent>
                        </Tooltip>
                      </div>
                    </div>
                  </CardHeader>

                  {isExpanded && (
                    <CardContent className="p-0 divide-y divide-slate-100">
                      {module.permissions.map((perm) => {
                        const isEnabled = permissions[perm.id];

                        return (
                          <div 
                            key={perm.id} 
                            className={`flex items-center justify-between p-4 transition-colors ${
                              isEnabled ? 'bg-white' : 'bg-slate-50'
                            }`}
                          >
                            <div className="flex items-center gap-3 flex-1">
                              <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
                                isEnabled ? 'bg-green-100' : 'bg-slate-200'
                              }`}>
                                {isEnabled ? (
                                  <Unlock className="w-4 h-4 text-green-600" />
                                ) : (
                                  <Lock className="w-4 h-4 text-slate-400" />
                                )}
                              </div>
                              <div className="flex-1">
                                <div className="flex items-center gap-2">
                                  <span className={`text-sm font-medium ${isEnabled ? 'text-slate-900' : 'text-slate-500'}`}>
                                    {perm.name}
                                  </span>
                                  {perm.critical && (
                                    <Tooltip>
                                      <TooltipTrigger>
                                        <AlertTriangle className="w-4 h-4 text-amber-500" />
                                      </TooltipTrigger>
                                      <TooltipContent>Critical permission - use with caution</TooltipContent>
                                    </Tooltip>
                                  )}
                                </div>
                                <p className="text-xs text-slate-500">{perm.description}</p>
                              </div>
                            </div>

                            <Switch
                              checked={isEnabled}
                              onCheckedChange={() => togglePermission(perm.id)}
                              className="data-[state=checked]:bg-green-600"
                            />
                          </div>
                        );
                      })}
                    </CardContent>
                  )}
                </Card>
              );
            })}
          </div>

          {/* Save Footer */}
          {!editingPosition && (
          <div className="mt-4 p-4 bg-white rounded-xl border border-slate-200 shadow-lg">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className={`w-10 h-10 rounded-xl bg-[#0A39DF] flex items-center justify-center`}>
                  <selectedLayerConfig.icon className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="font-bold text-slate-900 text-sm">{selectedLayerConfig.name} Layer</p>
                  <p className="text-xs text-slate-500">
                    {enabledCount} enabled • {totalCount - enabledCount} disabled
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm" className="border-slate-300">
                  Reset
                </Button>
                <Button size="sm" onClick={handleSave} className="bg-[#0A39DF] hover:bg-[#0831b8]">
                  <Save className="w-4 h-4 mr-1" />
                  Save
                </Button>
              </div>
            </div>
          </div>
          )}
          </>
          )}
        </div>
      </div>
    </TooltipProvider>
  );
}