import { 
  Home, 
  LayoutDashboard, 
  BookOpen, 
  ShieldAlert, 
  Database, 
  Users, 
  Key, 
  Sparkles, 
  Code, 
  Cloud, 
  Terminal, 
  LogOut, 
  LogIn, 
  User, 
  Circle,
  Menu,
  Activity,
  Workflow
} from 'lucide-react';
import { memo } from 'react';
import { User as UserType } from '../types';

interface SidebarProps {
  currentUser: UserType | null;
  activeTab: 'explore' | 'dashboard' | 'schema' | 'my-bookings' | 'users' | 'permissions' | 'profiling' | 'ci3-template' | 'operations' | 'ai-prediction' | 'superadmin' | 'cloud-storage' | 'menu-guide';
  setActiveTab: (tab: any) => void;
  devMode: boolean;
  setDevMode: (val: boolean) => void;
  onLogout: () => void;
  onOpenAuth: () => void;
  isOpen: boolean;
  setIsOpen: (val: boolean) => void;
  onChangePassword: () => void;
}

export default memo(function Sidebar({
  currentUser,
  activeTab,
  setActiveTab,
  devMode,
  setDevMode,
  onLogout,
  onOpenAuth,
  isOpen,
  setIsOpen,
  onChangePassword
}: SidebarProps) {
  
  const handleTabClick = (tab: any) => {
    setActiveTab(tab);
    setIsOpen(false);
  };

  const hasDashboardAccess = currentUser && (currentUser.permissions.includes('view_dashboard') || currentUser.role === 'superadmin');
  const hasOperationsAccess = currentUser && (currentUser.permissions.includes('view_operations') || currentUser.role === 'superadmin');
  const hasSuperadminAccess = currentUser && (currentUser.permissions.includes('view_superadmin') || currentUser.role === 'superadmin');

  // DevTools sub-menu dynamic access checks
  const hasSchemaAccess = currentUser && (currentUser.permissions.includes('view_schema') || currentUser.role === 'superadmin');
  const hasUsersAccess = currentUser && (currentUser.permissions.includes('view_users') || currentUser.role === 'superadmin');
  const hasPermissionsAccess = currentUser && (currentUser.permissions.includes('view_permissions') || currentUser.role === 'superadmin');
  const hasProfilingAccess = currentUser && (currentUser.permissions.includes('view_profiling') || currentUser.role === 'superadmin');
  const hasCi3Access = currentUser && (currentUser.permissions.includes('view_ci3_template') || currentUser.role === 'superadmin');
  const hasAiPredictionAccess = currentUser && (currentUser.permissions.includes('view_ai_prediction') || currentUser.role === 'superadmin');
  const hasCloudStorageAccess = currentUser && (currentUser.permissions.includes('view_cloud_storage') || currentUser.role === 'superadmin');

  return (
    <aside className={`bg-[#343a40] text-[#c2c6ca] w-64 flex flex-col h-screen fixed md:sticky top-0 z-40 transition-transform duration-300 select-none border-r border-[#4b545c]/30 ${
      isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
    }`}>
      {/* Brand Header */}
      <div className="h-14 px-4 border-b border-[#4b545c] flex items-center justify-between bg-[#3f474e] shrink-0">
        <div className="flex items-center space-x-2">
          <div className="bg-blue-600 text-white h-8 w-8 rounded-lg flex items-center justify-center font-black shadow-md tracking-tight">
            P
          </div>
          <span className="font-light text-white text-base tracking-wide">
            Property<b className="font-extrabold text-blue-400">Hub</b>
          </span>
        </div>
        <div className="bg-blue-950 text-blue-400 text-[10px] font-mono font-bold px-2 py-0.5 rounded border border-blue-900/50">
          v3.2.0
        </div>
      </div>

      {/* Profile/User Panel */}
      <div className="px-3.5 py-4 border-b border-[#4b545c] flex items-center space-x-3 shrink-0">
        <div className="h-9 w-9 rounded-full bg-[#495057] border border-[#6c757d] flex items-center justify-center text-white shrink-0 font-bold uppercase overflow-hidden">
          {currentUser ? (
            <span className="text-sm">{(currentUser.fullName || currentUser.username).charAt(0)}</span>
          ) : (
            <User className="h-5 w-5 text-gray-300" />
          )}
        </div>
        <div className="flex-1 min-w-0">
          {currentUser ? (
            <>
              <p className="text-white text-xs font-semibold truncate leading-none">
                {currentUser.fullName || currentUser.username}
              </p>
              <div className="flex items-center space-x-1.5 mt-1.5">
                <span className="h-2 w-2 rounded-full bg-emerald-500 inline-block"></span>
                <span className="text-[10px] text-emerald-400 font-bold uppercase tracking-wider">
                  {currentUser.role}
                </span>
              </div>
              <button
                onClick={onChangePassword}
                className="text-blue-400 hover:text-blue-300 text-[10px] font-bold mt-1.5 uppercase flex items-center space-x-0.5 cursor-pointer block hover:underline"
              >
                <Key className="h-3 w-3 inline" />
                <span>Ubah Sandi</span>
              </button>
            </>
          ) : (
            <>
              <p className="text-gray-400 text-xs truncate">Tamu / Guest</p>
              <button 
                onClick={onOpenAuth}
                className="text-blue-400 hover:text-blue-300 text-[10px] font-bold mt-1 uppercase flex items-center space-x-0.5 cursor-pointer"
              >
                <LogIn className="h-3 w-3" />
                <span>Masuk Akun</span>
              </button>
            </>
          )}
        </div>
      </div>

      {/* Menu Area */}
      <div className="flex-1 overflow-y-auto px-2 py-3 space-y-1 scrollbar-thin scrollbar-thumb-gray-700">
        
        {/* Navigation Section */}
        <div className="px-2.5 py-2 text-[10px] font-bold text-gray-500 uppercase tracking-wider">
          Menu Utama
        </div>

        <button
          onClick={() => handleTabClick('explore')}
          className={`w-full px-3 py-2.5 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
            activeTab === 'explore' 
              ? 'bg-[#007bff] text-white shadow-sm' 
              : 'hover:bg-[#495057] hover:text-white'
          }`}
        >
          <Home className="h-4 w-4 shrink-0" />
          <span>Jelajahi Unit Properti</span>
        </button>

        {currentUser && (
          <button
            onClick={() => handleTabClick('my-bookings')}
            className={`w-full px-3 py-2.5 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
              activeTab === 'my-bookings' 
                ? 'bg-[#007bff] text-white shadow-sm' 
                : 'hover:bg-[#495057] hover:text-white'
            }`}
          >
            <BookOpen className="h-4 w-4 shrink-0" />
            <span>Pemesanan Saya</span>
          </button>
        )}

        {hasDashboardAccess && (
          <button
            onClick={() => handleTabClick('dashboard')}
            className={`w-full px-3 py-2.5 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
              activeTab === 'dashboard' 
                ? 'bg-[#007bff] text-white shadow-sm' 
                : 'hover:bg-[#495057] hover:text-white'
            }`}
          >
            <LayoutDashboard className="h-4 w-4 shrink-0" />
            <span>Dashboard Analisis</span>
          </button>
        )}

        {hasOperationsAccess && (
          <button
            onClick={() => handleTabClick('operations')}
            className={`w-full px-3 py-2.5 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
              activeTab === 'operations' 
                ? 'bg-[#007bff] text-white shadow-sm' 
                : 'hover:bg-[#495057] hover:text-white'
            }`}
          >
            <ShieldAlert className="h-4 w-4 shrink-0" />
            <span>Operations Hub</span>
          </button>
        )}

        {hasSuperadminAccess && (
          <button
            onClick={() => handleTabClick('superadmin')}
            className={`w-full px-3 py-2.5 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
              activeTab === 'superadmin' 
                ? 'bg-[#007bff] text-white shadow-sm' 
                : 'hover:bg-[#495057] hover:text-white'
            }`}
          >
            <Terminal className="h-4 w-4 shrink-0" />
            <span>Superadmin Console</span>
          </button>
        )}

        {/* Developer and Architecture Section */}
        {devMode && (
          <div className="pt-4 space-y-1">
            <div className="px-2.5 py-2 text-[10px] font-bold text-gray-500 uppercase tracking-wider flex items-center justify-between">
              <span>Arsitektur & DevTools</span>
              <Workflow className="h-3 w-3 text-blue-500" />
            </div>

            {/* Sub-group: ALAT AKTIF */}
            <div className="px-2.5 py-1 text-[9px] font-extrabold text-blue-400 uppercase tracking-widest bg-blue-950/40 py-1 rounded">
              Alat Aktif / Utama
            </div>

            <button
              onClick={() => handleTabClick('menu-guide')}
              className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                activeTab === 'menu-guide' 
                  ? 'bg-[#007bff] text-white shadow-sm' 
                  : 'hover:bg-[#495057] hover:text-white'
              }`}
            >
              <BookOpen className="h-4 w-4 shrink-0 text-emerald-400" />
              <span className="truncate">Panduan & Kustomisasi Menu</span>
              <span className="text-[8px] bg-emerald-950 text-emerald-400 font-mono font-bold px-1.5 py-0.5 rounded ml-auto">BARU</span>
            </button>

            {hasProfilingAccess && (
              <button
                onClick={() => handleTabClick('profiling')}
                className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                  activeTab === 'profiling' 
                    ? 'bg-[#007bff] text-white shadow-sm' 
                    : 'hover:bg-[#495057] hover:text-white'
                }`}
              >
                <Activity className="h-4 w-4 shrink-0 text-indigo-400" />
                <span className="truncate">Profiling & Log Analisis</span>
              </button>
            )}

            {hasUsersAccess && (
              <button
                onClick={() => handleTabClick('users')}
                className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                  activeTab === 'users' 
                    ? 'bg-[#007bff] text-white shadow-sm' 
                    : 'hover:bg-[#495057] hover:text-white'
                }`}
              >
                <Users className="h-4 w-4 shrink-0 text-teal-400" />
                <span className="truncate">Master Pengguna (CRUD)</span>
              </button>
            )}

            {hasPermissionsAccess && (
              <button
                onClick={() => handleTabClick('permissions')}
                className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                  activeTab === 'permissions' 
                    ? 'bg-[#007bff] text-white shadow-sm' 
                    : 'hover:bg-[#495057] hover:text-white'
                }`}
              >
                <Key className="h-4 w-4 shrink-0 text-yellow-500" />
                <span className="truncate">Master Hak Izin</span>
              </button>
            )}

            {hasAiPredictionAccess && (
              <button
                onClick={() => handleTabClick('ai-prediction')}
                className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                  activeTab === 'ai-prediction' 
                    ? 'bg-[#007bff] text-white shadow-sm' 
                    : 'hover:bg-[#495057] hover:text-white'
                }`}
              >
                <Sparkles className="h-4 w-4 shrink-0 text-fuchsia-400" />
                <span className="truncate">Prediksi & Keputusan AI</span>
              </button>
            )}

            {hasCloudStorageAccess && (
              <button
                onClick={() => handleTabClick('cloud-storage')}
                className={`w-full px-3 py-2 rounded-lg text-xs font-semibold flex items-center space-x-3 transition-colors cursor-pointer ${
                  activeTab === 'cloud-storage' 
                    ? 'bg-[#007bff] text-white shadow-sm' 
                    : 'hover:bg-[#495057] hover:text-white'
                }`}
              >
                <Cloud className="h-4 w-4 shrink-0 text-sky-400" />
                <span className="truncate">Cloud Storage Hub</span>
              </button>
            )}

            {/* Sub-group: NON-AKTIF / ARSIP */}
            <div className="pt-2">
              <div className="px-2.5 py-1 text-[9px] font-extrabold text-gray-400 uppercase tracking-widest bg-gray-900/30 py-1 rounded">
                Non-Aktif / Diarsipkan
              </div>
            </div>

            {hasSchemaAccess && (
              <div
                title="Halaman ini dinonaktifkan atas permintaan pengembang"
                className="w-full px-3 py-2 rounded-lg text-xs font-medium flex items-center space-x-3 opacity-40 bg-gray-900/10 cursor-not-allowed select-none line-through"
              >
                <Database className="h-4 w-4 shrink-0 text-gray-500" />
                <span className="truncate text-gray-400">Master Skema MySQL</span>
                <span className="text-[8px] bg-red-950 text-red-400 font-mono font-bold px-1 rounded ml-auto">ARSIP</span>
              </div>
            )}

            {hasCi3Access && (
              <div
                title="Halaman ini dinonaktifkan atas permintaan pengembang"
                className="w-full px-3 py-2 rounded-lg text-xs font-medium flex items-center space-x-3 opacity-40 bg-gray-900/10 cursor-not-allowed select-none line-through"
              >
                <Code className="h-4 w-4 shrink-0 text-gray-500" />
                <span className="truncate text-gray-400">CI3 & AdminLTE Files</span>
                <span className="text-[8px] bg-red-950 text-red-400 font-mono font-bold px-1 rounded ml-auto">ARSIP</span>
              </div>
            )}


          </div>
        )}

      </div>

      {/* Footer / Account Actions */}
      <div className="p-3 border-t border-[#4b545c] bg-[#22252a] flex flex-col space-y-2 shrink-0">
        <div className="flex items-center justify-between text-[10px] text-gray-500">
          <span>Mode Developer</span>
          <button 
            onClick={() => {
              const val = !devMode;
              setDevMode(val);
              localStorage.setItem('devMode', String(val));
              if (!val && ['schema', 'users', 'permissions', 'profiling', 'ci3-template', 'ai-prediction', 'cloud-storage', 'menu-guide'].includes(activeTab)) {
                setActiveTab('explore');
              }
            }}
            className={`w-9 h-5 rounded-full p-0.5 transition-colors cursor-pointer duration-200 outline-none ${
              devMode ? 'bg-emerald-500' : 'bg-gray-600'
            }`}
          >
            <div className={`bg-white w-4 h-4 rounded-full shadow-md transform transition-transform duration-200 ${
              devMode ? 'translate-x-4' : 'translate-x-0'
            }`}></div>
          </button>
        </div>

        {currentUser && (
          <button
            onClick={onLogout}
            className="w-full bg-[#c82333]/15 border border-[#dc3545]/30 hover:bg-[#c82333]/25 text-[#f8d7da] py-1.5 rounded-lg text-xs font-bold transition-all flex items-center justify-center space-x-1.5 cursor-pointer"
          >
            <LogOut className="h-3.5 w-3.5" />
            <span>Keluar Sistem</span>
          </button>
        )}
      </div>
    </aside>
  );
});
