'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  Home,
  FileText,
  Briefcase,
  GraduationCap,
  CalendarCheck,
  Landmark,
  Image as ImageIcon,
  CreditCard,
  Gift,
  Star,
  Award,
  Coins,
  Lock,
  Navigation2,
  Settings,
  Info,
  Building2,
  Phone,
  Shield,
  ShoppingBag,
  CalendarDays,
  Package2,
  ChevronDown,
  ChevronRight,
  X,
  LayoutList,
  LucideIcon,
} from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';

interface NavItem {
  href: string;
  label: string;
  icon: LucideIcon;
  roles: string[];
}

interface NavGroup {
  id: string;
  label: string;
  children: NavItem[];
}

type SidebarEntry =
  | { type: 'item'; item: NavItem }
  | { type: 'group'; group: NavGroup };

const sidebarStructure: SidebarEntry[] = [
  {
    type: 'group',
    group: {
      id: 'homepage',
      label: 'Homepage',
      children: [
        { href: '/homepage', label: 'Homepage', icon: Home, roles: ['admin', 'editor'] },
        { href: '/sidebar-content', label: 'Sidebar Ads', icon: LayoutList, roles: ['admin', 'editor'] },
        { href: '/packages', label: 'Packages', icon: Package2, roles: ['admin', 'editor'] },
      ],
    },
  },
  {
    type: 'group',
    group: {
      id: 'about',
      label: 'About Us',
      children: [
        { href: '/about', label: 'About Us', icon: Info, roles: ['admin', 'editor'] },
        { href: '/posts', label: 'News', icon: FileText, roles: ['admin', 'editor', 'author'] },
        { href: '/partners', label: 'Partners', icon: Building2, roles: ['admin', 'editor'] },
        { href: '/contact', label: 'Contact Us', icon: Phone, roles: ['admin', 'editor'] },
        { href: '/privacy', label: 'Privacy Statement', icon: Shield, roles: ['admin', 'editor'] },
      ],
    },
  },
  {
    type: 'group',
    group: {
      id: 'services',
      label: 'Our Services',
      children: [
        { href: '/services', label: 'Golf Services', icon: Briefcase, roles: ['admin', 'editor'] },
        { href: '/golf-academy', label: 'Golf Academy', icon: GraduationCap, roles: ['admin', 'editor'] },
        { href: '/book-lessons', label: 'Book Lessons', icon: CalendarCheck, roles: ['admin', 'editor'] },
        { href: '/eshop', label: 'ESHOP', icon: ShoppingBag, roles: ['admin', 'editor'] },
        { href: '/events', label: 'Events', icon: CalendarDays, roles: ['admin', 'editor'] },
        { href: '/gdf', label: 'Golf Dev Fund', icon: Landmark, roles: ['admin', 'editor'] },
      ],
    },
  },
  {
    type: 'group',
    group: {
      id: 'event-gallery',
      label: 'Event Gallery',
      children: [
        { href: '/event-gallery', label: 'Event Gallery', icon: ImageIcon, roles: ['admin', 'editor'] },
      ],
    },
  },
  {
    type: 'group',
    group: {
      id: 'golf-id',
      label: 'Golf ID',
      children: [
        { href: '/golf-id', label: 'Golf ID', icon: CreditCard, roles: ['admin', 'editor'] },
        { href: '/membership-offers', label: 'Membership Offers', icon: Gift, roles: ['admin', 'editor'] },
        { href: '/upgrade-offers', label: 'Upgrade Offers', icon: Star, roles: ['admin', 'editor'] },
        { href: '/member-rewards', label: 'Member Rewards', icon: Award, roles: ['admin', 'editor'] },
        { href: '/bonus-points', label: 'Bonus Points', icon: Coins, roles: ['admin', 'editor'] },
      ],
    },
  },
  {
    type: 'group',
    group: {
      id: 'system',
      label: 'System',
      children: [
        { href: '/navigation', label: 'Navigation', icon: Navigation2, roles: ['admin'] },
        { href: '/users', label: 'Password', icon: Lock, roles: ['admin'] },
        { href: '/settings', label: 'Settings', icon: Settings, roles: ['admin'] },
      ],
    },
  },
];

interface SidebarProps {
  onClose?: () => void;
}

export default function Sidebar({ onClose }: SidebarProps) {
  const pathname = usePathname();
  const { user } = useAuth();
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());

  useEffect(() => {
    const activeGroups = new Set<string>();
    for (const entry of sidebarStructure) {
      if (entry.type === 'group') {
        const hasActive = entry.group.children.some(
          (child) => pathname === child.href || pathname.startsWith(child.href + '/')
        );
        if (hasActive) activeGroups.add(entry.group.id);
      }
    }
    setExpandedGroups((prev) => {
      const merged = new Set(prev);
      activeGroups.forEach((id) => merged.add(id));
      return merged;
    });
  }, [pathname]);

  const toggleGroup = (id: string) => {
    setExpandedGroups((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const isVisible = (item: NavItem) => user && item.roles.includes(user.role);

  const isActive = (href: string) => pathname === href || pathname.startsWith(href + '/');

  const renderNavLink = (item: NavItem, indented = false) => {
    const Icon = item.icon;
    const active = isActive(item.href);
    return (
      <Link
        key={item.href}
        href={item.href}
        onClick={onClose}
        className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
          indented ? 'ml-3' : ''
        } ${
          active
            ? 'bg-blue-600 text-white'
            : 'text-gray-300 hover:bg-gray-800 hover:text-white'
        }`}
      >
        <Icon size={16} />
        {item.label}
      </Link>
    );
  };

  return (
    <div className="flex flex-col h-full bg-gray-900 text-white w-64">
      <div className="flex items-center justify-between px-6 py-5 border-b border-gray-700">
        <div className="flex items-center gap-2.5">
          <img src={`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/images/logo.png`} alt="GLG" className="h-7 w-auto" />
          <div className="border-l border-gray-600 pl-2.5">
            <span className="text-xs font-semibold text-gray-300 uppercase tracking-wider">Admin</span>
          </div>
        </div>
        {onClose && (
          <button onClick={onClose} className="text-gray-400 hover:text-white lg:hidden">
            <X size={20} />
          </button>
        )}
      </div>

      <nav className="flex-1 px-3 py-4 space-y-0.5 overflow-y-auto">
        {sidebarStructure.map((entry) => {
          if (entry.type === 'item') {
            if (!isVisible(entry.item)) return null;
            return renderNavLink(entry.item);
          }

          const { group } = entry;
          const visibleChildren = group.children.filter(isVisible);
          if (visibleChildren.length === 0) return null;

          const isExpanded = expandedGroups.has(group.id);
          const groupHasActive = visibleChildren.some((c) => isActive(c.href));

          return (
            <div key={group.id} className="pt-3">
              <button
                type="button"
                onClick={() => toggleGroup(group.id)}
                className={`flex items-center justify-between w-full px-3 py-2 rounded-lg text-xs font-semibold uppercase tracking-wider transition-colors ${
                  groupHasActive
                    ? 'text-blue-400'
                    : 'text-gray-500 hover:text-gray-300'
                }`}
              >
                <span>{group.label}</span>
                {isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
              </button>
              {isExpanded && (
                <div className="mt-0.5 space-y-0.5">
                  {visibleChildren.map((child) => renderNavLink(child, true))}
                </div>
              )}
            </div>
          );
        })}
      </nav>

      {user && (
        <div className="px-4 py-4 border-t border-gray-700">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-sm font-semibold flex-shrink-0">
              {user.name.charAt(0).toUpperCase()}
            </div>
            <div className="min-w-0">
              <p className="text-sm font-medium text-white truncate">{user.name}</p>
              <p className="text-xs text-gray-400 capitalize">{user.role}</p>
            </div>
          </div>
          <a
            href="https://www.naton.io/"
            target="_blank"
            rel="noopener noreferrer"
            className="naton-credit-dark block mt-3 text-[10px] tracking-wide"
          >
            Built by Naton Lab Limited
          </a>
        </div>
      )}
    </div>
  );
}
