'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  LayoutDashboard,
  ShoppingCart,
  History,
  BookOpen,
  BarChart3,
  Package,
  Menu,
  X,
  ChevronsLeft,
  ChevronsRight,
  LogOut,
  User,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { allowedNavHrefs, roleLabel } from '@/lib/roles';
import { useSidebar } from './SidebarContext';
import { useAuth } from './AuthContext';
import NotificationBell from './NotificationBell';

const allNavItems = [
  { label: 'Dashboard', href: '/', icon: LayoutDashboard },
  { label: 'Kasir Ecer', href: '/transaksi', icon: ShoppingCart },
  { label: 'Riwayat', href: '/history', icon: History },
  { label: 'Laporan', href: '/laporan', icon: BarChart3 },
  { label: 'Pembukuan', href: '/pembukuan', icon: BookOpen },
];

// Map pathname to page title for mobile top bar
const pageTitles: Record<string, string> = {
  '/': 'Dashboard',
  '/transaksi': 'Kasir Ecer',
  '/history': 'Riwayat',
  '/laporan': 'Laporan',
  '/pembukuan': 'Pembukuan',
};

export default function Sidebar() {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const { collapsed, toggle, setCollapsed } = useSidebar();
  const { user, logout } = useAuth();
  const manualToggleRef = useRef(false);
  const [storeName, setStoreName] = useState('LasminiShop');
  const allowed = allowedNavHrefs(user);
  const navItems = allNavItems.filter((item) => allowed.includes(item.href));

  // Load store name from cached settings in localStorage
  useEffect(() => {
    const cached = localStorage.getItem('store_settings');
    if (cached) {
      try {
        const parsed = JSON.parse(cached);
        if (parsed.store_name) {
          setStoreName(parsed.store_name);
        }
      } catch {}
    }

    const handleStorageChange = () => {
      const updated = localStorage.getItem('store_settings');
      if (updated) {
        try {
          const parsed = JSON.parse(updated);
          if (parsed.store_name) {
            setStoreName(parsed.store_name);
          }
        } catch {}
      }
    };

    window.addEventListener('storage', handleStorageChange);
    const t1 = setTimeout(handleStorageChange, 2000);
    const t2 = setTimeout(handleStorageChange, 5000);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      clearTimeout(t1);
      clearTimeout(t2);
    };
  }, []);

  // Auto-collapse sidebar on /transaksi, auto-expand on other pages
  useEffect(() => {
    const isTransaksi = pathname === '/transaksi' || pathname.startsWith('/transaksi/');
    if (isTransaksi) {
      manualToggleRef.current = false;
      setCollapsed(true);
    } else {
      if (!manualToggleRef.current) {
        setCollapsed(false);
      }
    }
  }, [pathname, setCollapsed]);

  const handleManualToggle = () => {
    manualToggleRef.current = true;
    toggle();
  };

  const isActive = (href: string) => {
    if (href === '/') return pathname === '/';
    return pathname.startsWith(href);
  };

  const currentPageTitle = pageTitles[pathname] || storeName;

  // ==========================================
  // FULL SIDEBAR CONTENT (mobile + desktop expanded)
  // ==========================================
  const fullContent = (
    <>
      {/* Logo / Branding */}
      <div className="flex items-center gap-3 px-5 py-6 border-b border-white/10">
        <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-blue-400 to-blue-500 shadow-lg">
          <Package className="h-6 w-6 text-white" />
        </div>
        <div className="overflow-hidden">
          <h1 className="text-base font-bold text-white font-heading leading-tight truncate">
            {storeName}
          </h1>
          <p className="text-[10px] text-blue-200/60 font-medium tracking-wider uppercase">Kasir Ecer</p>
        </div>
      </div>

      {/* Navigation */}
      <nav className="mt-4 flex-1 space-y-1.5 px-4">
        {navItems.map((item) => {
          const active = isActive(item.href);
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setMobileOpen(false)}
              className={cn(
                'group relative flex items-center gap-3 rounded-xl pl-7 pr-4 py-3 text-sm font-semibold transition-all duration-200',
                active
                  ? 'bg-white/15 text-white shadow-sm'
                  : 'text-white/90 hover:bg-white/8 hover:text-white'
              )}
            >
              {/* Active indicator */}
              {active && (
                <span className="absolute left-0 top-1/2 -translate-y-1/2 h-8 w-1 rounded-r-full bg-blue-400 shadow-lg shadow-blue-400/50" />
              )}
              <item.icon className={cn('h-5 w-5 shrink-0 transition-colors', active ? 'text-blue-300' : 'text-white/80 group-hover:text-white')} />
              <span className="truncate">{item.label}</span>
            </Link>
          );
        })}
      </nav>

      {/* User Info + Logout */}
      <div className="border-t border-white/10 px-4 py-4 space-y-3">
        {user && (
          <div className="flex items-center gap-3 px-2 py-2 rounded-lg bg-white/5">
            <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-blue-400 to-blue-500 shadow-sm">
              <User className="h-4 w-4 text-white" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-sm font-semibold text-white truncate">{user.name}</p>
              <p className="text-[10px] text-blue-200/60 font-medium">{roleLabel(user.role)}</p>
            </div>
          </div>
        )}
        <button
          onClick={logout}
          className="flex w-full items-center gap-3 rounded-lg pl-7 pr-4 py-2.5 text-sm font-medium text-white/80 hover:bg-red-500/10 hover:text-red-400 transition-all cursor-pointer"
        >
          <LogOut className="h-4 w-4" />
          <span>Keluar</span>
        </button>
      </div>
    </>
  );

  return (
    <>
      {/* ============================================================
          MOBILE - Fixed top bar with hamburger + page title
          ============================================================ */}
      <div 
        className="fixed left-0 right-0 z-40 flex h-14 items-center justify-between bg-gradient-to-r from-blue-900 to-blue-800 px-4 lg:hidden shadow-lg"
        style={{ top: 0 }}
      >
        <div className="flex items-center gap-3">
          <button
            onClick={() => setMobileOpen(true)}
            className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-white/10 text-white hover:bg-white/20 active:scale-95 cursor-pointer transition-all"
            aria-label="Buka menu"
          >
            <Menu className="h-5 w-5" />
          </button>
          <div className="flex items-center gap-2.5 min-w-0">
            <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-blue-400 to-blue-500 shadow-sm">
              <Package className="h-3.5 w-3.5 text-white" />
            </div>
            <span className="text-sm font-bold text-white truncate">{currentPageTitle}</span>
          </div>
        </div>
        <NotificationBell />
      </div>

      {/* Mobile overlay */}
      {mobileOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/70 backdrop-blur-sm lg:hidden animate-fade-in"
          onClick={() => setMobileOpen(false)}
        />
      )}

      {/* Mobile sidebar drawer */}
      <aside
        className={cn(
          'fixed left-0 z-50 flex w-72 flex-col bg-gradient-to-b from-blue-900 to-blue-950 transition-transform duration-300 ease-out lg:hidden shadow-2xl',
          mobileOpen ? 'translate-x-0' : '-translate-x-full'
        )}
        style={{
          top: 0,
          bottom: 0,
        }}
      >
        <button
          onClick={() => setMobileOpen(false)}
          className="absolute top-4 right-4 flex h-8 w-8 items-center justify-center rounded-lg bg-white/10 text-white/60 hover:text-white hover:bg-white/20 active:scale-95 cursor-pointer transition-all"
          aria-label="Tutup menu"
        >
          <X className="h-4 w-4" />
        </button>
        {fullContent}
      </aside>

      {/* ============================================================
          DESKTOP - Collapsible sidebar
          ============================================================ */}
      <aside
        className={cn(
          'hidden lg:flex lg:flex-col lg:fixed bg-gradient-to-b from-blue-900 to-blue-950 transition-all duration-300 ease-in-out z-30 shadow-xl',
          collapsed ? 'lg:w-[68px]' : 'lg:w-64'
        )}
        style={{
          top: 0,
          bottom: 0,
        }}
      >
        {/* Collapsed: icon-only layout */}
        {collapsed ? (
          <>
            {/* Logo icon */}
            <div className="flex items-center justify-center py-6 border-b border-white/10">
              <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-blue-400 to-blue-500 shadow-lg">
                <Package className="h-6 w-6 text-white" />
              </div>
            </div>

            {/* Nav icons */}
            <nav className="mt-4 flex-1 space-y-1.5 px-2">
              {navItems.map((item) => {
                const active = isActive(item.href);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    title={item.label}
                    className={cn(
                      'relative flex h-11 w-full items-center justify-center rounded-xl transition-all duration-200',
                      active
                        ? 'bg-white/15 text-white shadow-sm'
                        : 'text-white/80 hover:bg-white/8 hover:text-white'
                    )}
                  >
                    {active && (
                      <span className="absolute left-0 top-1/2 -translate-y-1/2 h-7 w-1 rounded-r-full bg-blue-400 shadow-lg shadow-blue-400/50" />
                    )}
                    <item.icon className={cn('h-5 w-5', active ? 'text-blue-300' : '')} />
                  </Link>
                );
              })}
            </nav>

            {/* Expand + Logout buttons */}
            <div className="border-t border-white/10 p-2 space-y-1.5">
              <button
                onClick={logout}
                className="flex h-11 w-full items-center justify-center rounded-xl text-white/70 hover:bg-red-500/10 hover:text-red-400 transition-all cursor-pointer"
                aria-label="Keluar"
                title="Keluar"
              >
                <LogOut className="h-4 w-4" />
              </button>
              <button
                onClick={handleManualToggle}
                className="flex h-11 w-full items-center justify-center rounded-xl text-white/70 hover:bg-white/10 hover:text-white transition-all cursor-pointer"
                aria-label="Perluas sidebar"
                title="Perluas sidebar"
              >
                <ChevronsRight className="h-4 w-4" />
              </button>
            </div>
          </>
        ) : (
          <>
            {fullContent}

            {/* Collapse button */}
            <div className="absolute bottom-12 right-0 translate-x-1/2 z-40">
              <button
                onClick={handleManualToggle}
                className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-600 text-white border-2 border-background hover:bg-blue-500 active:scale-95 transition-all cursor-pointer shadow-lg"
                aria-label="Kecilkan sidebar"
                title="Kecilkan sidebar"
              >
                <ChevronsLeft className="h-4 w-4" />
              </button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}
