import React, { useState } from "react";
import {
  LayoutDashboard, CreditCard, PenLine, RefreshCw, LayoutTemplate, Package,
  BarChart2, Users, Smartphone, Globe2, Wallet, Bell, Link2, FileText,
  Settings, HelpCircle, Mail, Star, ShieldCheck, DoorClosed, Code, User,
  AlertTriangle, BookOpen, PhoneCall, UsersRound, BriefcaseBusiness,
  ClipboardList, MessageSquareWarning, ListCollapse, SaveAll, Layers,
  CheckCircle2, Search, SlidersHorizontal,
} from "lucide-react";

/* ---------------------------------------------------------------------- */
/*  DATA                                                                   */
/* ---------------------------------------------------------------------- */
const SECTIONS = [
  { group: "Main Menu", color: "red", items: [
    { label: "Dashboard", icon: LayoutDashboard },
  ]},
  { group: "NFC Management", color: "rose", items: [
    { label: "My NFC Cards",      icon: CreditCard      },
    { label: "Write NFC Card",    icon: PenLine         },
    { label: "Re-Write NFC Card", icon: RefreshCw       },
    { label: "All Templates",     icon: LayoutTemplate  },
    { label: "My Templates",      icon: LayoutTemplate  },
    { label: "Create Template",   icon: LayoutTemplate  },
    { label: "Import Template",   icon: LayoutTemplate  },
    { label: "Bulk Operations",   icon: Package         },
  ]},
  { group: "Analytics", color: "orange", items: [
    { label: "Scan & Analytics",   icon: BarChart2  },
    { label: "Leads & Users",      icon: Users      },
    { label: "Device Analytics",   icon: Smartphone },
    { label: "Geographic Reports", icon: Globe2     },
  ]},
  { group: "Account", color: "amber", items: [
    { label: "Wallet & Credits",        icon: Wallet   },
    { label: "Balance Overview",        icon: Wallet   },
    { label: "Top-Up Credits",          icon: Wallet   },
    { label: "Transaction History",     icon: FileText },
    { label: "Subscription",            icon: Bell     },
    { label: "Current Plan",            icon: Bell     },
    { label: "Upgrade Plan",            icon: Bell     },
    { label: "Billing History",         icon: FileText },
    { label: "API & Integrations",      icon: Link2    },
    { label: "API Keys",                icon: Link2    },
    { label: "Webhooks",                icon: Link2    },
    { label: "Third-party Integrations",icon: Link2    },
    { label: "Activity Logs",           icon: FileText },
    { label: "Card Activity",           icon: FileText },
    { label: "System Logs",             icon: FileText },
    { label: "Settings",                icon: Settings },
  ]},
  { group: "Support", color: "yellow", items: [
    { label: "Help & Support",    icon: HelpCircle },
    { label: "Contact Us",        icon: Mail       },
    { label: "Reviews & Feedback",icon: Star       },
  ]},
  { group: "Verification", color: "emerald", items: [
    { label: "User Management",            icon: Users          },
    { label: "Multi Verification",         icon: ShieldCheck    },
    { label: "Door Management",            icon: DoorClosed     },
    { label: "Entry & Exit Tracking",      icon: Layers         },
    { label: "Activity Tracking",          icon: User           },
    { label: "Audit Trail",                icon: AlertTriangle  },
    { label: "Tracking Code System",       icon: Code           },
    { label: "Alert Management",           icon: AlertTriangle  },
    { label: "Activity Exposure Dashboard",icon: BookOpen       },
    { label: "Court Hearing Management",   icon: ClipboardList  },
  ]},
  { group: "Bar Council", color: "blue", items: [
    { label: "Dashboard",                    icon: LayoutDashboard    },
    { label: "Smart Card",                   icon: CreditCard         },
    { label: "Member Management",            icon: BarChart2          },
    { label: "Advocate Directory",           icon: LayoutDashboard    },
    { label: "Chamber Hierarchy Management", icon: Layers             },
    { label: "Fee Collection & Defaulters",  icon: ListCollapse       },
    { label: "Welfare Scheme Management",    icon: SaveAll            },
    { label: "Insurance",                    icon: ShieldCheck        },
    { label: "Committee",                    icon: Users              },
    { label: "Notice Board",                 icon: ClipboardList      },
    { label: "Grievance",                    icon: MessageSquareWarning},
    { label: "Legal Aid Call",               icon: PhoneCall          },
    { label: "Staff Management",             icon: UsersRound         },
    { label: "Employment Exchange",          icon: BriefcaseBusiness  },
  ]},
  { group: "Admin", color: "purple", items: [
    { label: "Admin Settings",      icon: Settings  },
    { label: "Billing & Plans",     icon: CreditCard},
    { label: "Help & Support Admin",icon: HelpCircle},
    { label: "Core Management",     icon: Settings  },
  ]},
];

const GROUP_COLORS = {
  red:     { dot: "bg-red-500",     badge: "bg-red-50 text-red-600 border-red-200",     icon: "bg-red-100 text-red-600",     ring: "ring-red-200",    activeBg: "bg-red-50",    activeText: "text-red-700"    },
  rose:    { dot: "bg-rose-500",    badge: "bg-rose-50 text-rose-600 border-rose-200",   icon: "bg-rose-100 text-rose-600",   ring: "ring-rose-200",   activeBg: "bg-rose-50",   activeText: "text-rose-700"   },
  orange:  { dot: "bg-orange-500",  badge: "bg-orange-50 text-orange-600 border-orange-200", icon: "bg-orange-100 text-orange-600", ring: "ring-orange-200", activeBg: "bg-orange-50", activeText: "text-orange-700" },
  amber:   { dot: "bg-amber-500",   badge: "bg-amber-50 text-amber-600 border-amber-200",   icon: "bg-amber-100 text-amber-600",   ring: "ring-amber-200",  activeBg: "bg-amber-50",  activeText: "text-amber-700"  },
  yellow:  { dot: "bg-yellow-500",  badge: "bg-yellow-50 text-yellow-700 border-yellow-200", icon: "bg-yellow-100 text-yellow-700", ring: "ring-yellow-200", activeBg: "bg-yellow-50", activeText: "text-yellow-700" },
  emerald: { dot: "bg-emerald-500", badge: "bg-emerald-50 text-emerald-700 border-emerald-200", icon: "bg-emerald-100 text-emerald-600", ring: "ring-emerald-200", activeBg: "bg-emerald-50", activeText: "text-emerald-700" },
  blue:    { dot: "bg-blue-500",    badge: "bg-blue-50 text-blue-600 border-blue-200",     icon: "bg-blue-100 text-blue-600",     ring: "ring-blue-200",   activeBg: "bg-blue-50",   activeText: "text-blue-700"   },
  purple:  { dot: "bg-purple-500",  badge: "bg-purple-50 text-purple-600 border-purple-200", icon: "bg-purple-100 text-purple-600", ring: "ring-purple-200", activeBg: "bg-purple-50", activeText: "text-purple-700" },
};

function makeKey(group, label) { return `${group}::${label}`; }

/* ---------------------------------------------------------------------- */
/*  TOGGLE                                                                 */
/* ---------------------------------------------------------------------- */
function Toggle({ checked, color, onChange }) {
  const onColor = color === "red" ? "bg-red-600" : color === "blue" ? "bg-blue-600" : color === "emerald" ? "bg-emerald-600" : color === "purple" ? "bg-purple-600" : color === "amber" ? "bg-amber-500" : color === "orange" ? "bg-orange-500" : color === "rose" ? "bg-rose-500" : "bg-yellow-500";
  return (
    <button
      onClick={(e) => { e.stopPropagation(); onChange(); }}
      className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 transition-all duration-200 focus:outline-none ${checked ? `${onColor} border-transparent` : "bg-gray-100 border-gray-200"}`}
    >
      <span className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transform transition-transform duration-200 ${checked ? "translate-x-4" : "translate-x-0.5"}`} />
    </button>
  );
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function MenuToggles() {
  const [mode, setMode]     = useState("single");
  const [single, setSingle] = useState(null);
  const [multi, setMulti]   = useState({});
  const [search, setSearch] = useState("");

  const isOn = (key) => mode === "single" ? single === key : !!multi[key];

  const toggle = (key) => {
    if (mode === "single") setSingle((p) => (p === key ? null : key));
    else setMulti((p) => ({ ...p, [key]: !p[key] }));
  };

  const clearAll = () => { setSingle(null); setMulti({}); };

  const enableSection = (section) => {
    const updates = {};
    section.items.forEach((item) => { updates[makeKey(section.group, item.label)] = true; });
    setMulti((p) => ({ ...p, ...updates }));
  };

  const disableSection = (section) => {
    const updates = {};
    section.items.forEach((item) => { updates[makeKey(section.group, item.label)] = false; });
    setMulti((p) => ({ ...p, ...updates }));
  };

  const enableAll = () => {
    const updates = {};
    SECTIONS.forEach((s) => s.items.forEach((item) => { updates[makeKey(s.group, item.label)] = true; }));
    setMulti(updates);
  };

  const totalOn    = mode === "single" ? (single ? 1 : 0) : Object.values(multi).filter(Boolean).length;
  const totalCount = SECTIONS.reduce((s, sec) => s + sec.items.length, 0);
  const activeKeys = mode === "multiple" ? Object.entries(multi).filter(([, v]) => v).map(([k]) => k.split("::")[1]) : [];

  const filteredSections = SECTIONS.map((s) => ({
    ...s,
    items: s.items.filter((item) => item.label.toLowerCase().includes(search.toLowerCase())),
  })).filter((s) => s.items.length > 0);

  return (
    <div className="w-full min-h-screen bg-gray-50 text-gray-900" style={{ fontFamily: "'IBM Plex Sans', 'Inter', sans-serif" }}>
      <style>{`@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&display=swap');`}</style>

      {/* ── STICKY HEADER ── */}
      <div className="sticky top-0 z-20 bg-white border-b border-gray-100 shadow-sm">
        <div className="px-6 py-4 flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-red-600 flex items-center justify-center shrink-0">
              <SlidersHorizontal className="w-4 h-4 text-white" />
            </div>
            <div>
              <h1 className="text-sm font-bold text-gray-900 leading-none">Module Access Control</h1>
              <p className="text-[11px] text-gray-400 mt-0.5">
                {totalOn > 0 ? `${totalOn} module${totalOn > 1 ? "s" : ""} enabled` : "No modules enabled"}
                {mode === "multiple" && ` · ${totalCount} total`}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {/* Mode switcher */}
            <div className="flex items-center bg-gray-100 rounded-lg p-1 gap-1">
              {[{ id: "single", label: "Single" }, { id: "multiple", label: "Multi" }].map((m) => (
                <button key={m.id} onClick={() => { setMode(m.id); clearAll(); }}
                  className={`px-3 py-1.5 rounded-md text-xs font-semibold transition-all ${mode === m.id ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"}`}>
                  {m.label}
                </button>
              ))}
            </div>

            {mode === "multiple" && (
              <button onClick={enableAll}
                className="px-3 py-1.5 text-xs rounded-lg bg-red-600 text-white hover:bg-red-500 font-semibold transition-colors">
                Enable All
              </button>
            )}
            <button onClick={clearAll} disabled={totalOn === 0}
              className="px-3 py-1.5 text-xs rounded-lg border border-gray-200 bg-white text-gray-600 hover:bg-gray-50 font-semibold transition-colors disabled:opacity-40 disabled:cursor-not-allowed">
              Clear
            </button>
          </div>
        </div>

        {/* Search + active bar */}
        <div className="px-6 pb-3 flex items-center gap-3">
          <div className="relative flex-1 max-w-xs">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
            <input value={search} onChange={(e) => setSearch(e.target.value)}
              placeholder="Search modules..."
              className="w-full pl-9 pr-3 py-1.5 text-xs rounded-lg border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300 placeholder-gray-400" />
          </div>

          {/* Active banner inline */}
          {totalOn > 0 && (
            <div className="flex items-center gap-2 flex-wrap flex-1">
              <span className="w-2 h-2 rounded-full bg-red-500 animate-pulse shrink-0" />
              {mode === "single" && single && (
                <span className="text-xs text-gray-600">
                  <span className="font-semibold text-gray-900">{single.split("::")[1]}</span>
                  <span className="text-gray-400"> · {single.split("::")[0]}</span>
                </span>
              )}
              {mode === "multiple" && (
                <div className="flex items-center gap-1.5 flex-wrap">
                  {activeKeys.slice(0, 4).map((k) => (
                    <span key={k} className="text-[11px] bg-red-50 border border-red-200 text-red-700 px-2 py-0.5 rounded-full font-medium">{k}</span>
                  ))}
                  {activeKeys.length > 4 && <span className="text-[11px] text-gray-400 font-medium">+{activeKeys.length - 4} more</span>}
                </div>
              )}
            </div>
          )}

          {/* Progress bar for multi */}
          {mode === "multiple" && totalOn > 0 && (
            <div className="flex items-center gap-2 shrink-0">
              <div className="w-24 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                <div className="h-1.5 bg-red-500 rounded-full transition-all duration-300" style={{ width: `${(totalOn / totalCount) * 100}%` }} />
              </div>
              <span className="text-[11px] text-gray-400 font-medium">{Math.round((totalOn / totalCount) * 100)}%</span>
            </div>
          )}
        </div>
      </div>

      {/* ── SECTIONS GRID ── */}
      <div className="p-6 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
        {filteredSections.map((section) => {
          const c             = GROUP_COLORS[section.color];
          const sectionKeys   = section.items.map((item) => makeKey(section.group, item.label));
          const sectionOn     = sectionKeys.filter(isOn).length;
          const allSectionOn  = sectionOn === sectionKeys.length && sectionKeys.length > 0;
          const pct           = Math.round((sectionOn / section.items.length) * 100);

          return (
            <div key={section.group} className="bg-white border border-gray-100 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow">

              {/* Section header */}
              <div className="px-4 pt-4 pb-3">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className={`w-2 h-2 rounded-full ${c.dot}`} />
                    <p className="text-xs font-bold uppercase tracking-wider text-gray-700">{section.group}</p>
                  </div>
                  {mode === "multiple" && (
                    <button
                      onClick={() => allSectionOn ? disableSection(section) : enableSection(section)}
                      className={`text-[11px] font-semibold px-2.5 py-1 rounded-full border transition-colors ${allSectionOn ? `${c.badge} border` : "border-gray-200 text-gray-400 hover:bg-gray-50"}`}>
                      {allSectionOn ? "Disable all" : "Enable all"}
                    </button>
                  )}
                </div>

                {/* Mini progress */}
                <div className="flex items-center gap-2">
                  <div className="flex-1 h-1 bg-gray-100 rounded-full overflow-hidden">
                    <div className={`h-1 rounded-full transition-all duration-300 ${c.dot.replace("bg-", "bg-")}`}
                      style={{ width: `${pct}%` }} />
                  </div>
                  <span className="text-[10px] text-gray-400 font-medium shrink-0">{sectionOn}/{section.items.length}</span>
                </div>
              </div>

              {/* Items */}
              <div className="border-t border-gray-50">
                {section.items.map((item) => {
                  const key     = makeKey(section.group, item.label);
                  const checked = isOn(key);
                  const Icon    = item.icon;
                  return (
                    <div
                      key={key}
                      onClick={() => toggle(key)}
                      className={`flex items-center gap-3 px-4 py-2.5 cursor-pointer transition-colors border-b border-gray-50 last:border-0 select-none ${checked ? c.activeBg : "hover:bg-gray-50"}`}
                    >
                      <div className={`w-6 h-6 rounded-md flex items-center justify-center shrink-0 transition-colors ${checked ? c.icon : "bg-gray-100 text-gray-400"}`}>
                        <Icon className="w-3.5 h-3.5" />
                      </div>
                      <span className={`text-xs flex-1 truncate transition-colors ${checked ? `font-semibold ${c.activeText}` : "text-gray-500"}`}>
                        {item.label}
                      </span>
                      {checked && mode === "single" && (
                        <CheckCircle2 className="w-3.5 h-3.5 text-red-500 shrink-0" />
                      )}
                      <Toggle checked={checked} color={section.color} onChange={() => toggle(key)} />
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}

        {filteredSections.length === 0 && (
          <div className="col-span-full py-16 text-center">
            <Search className="w-8 h-8 text-gray-300 mx-auto mb-3" />
            <p className="text-sm text-gray-400">No modules match "<span className="font-medium text-gray-600">{search}</span>"</p>
            <button onClick={() => setSearch("")} className="mt-2 text-xs text-red-500 hover:text-red-600 font-medium">Clear search</button>
          </div>
        )}
      </div>
    </div>
  );
}