import { NavLink } from 'react-router-dom';
import {
  MessageSquare, Search, BarChart3, Cloud,
  Brain, Plug, Database, Dna, Users, Lock, FileText,
  Sparkles, Sun, Moon, LogOut, FolderOpen, Languages
} from 'lucide-react';
import { useTheme } from '@/hooks/useTheme';
import { useAuthStore } from '@/stores/auth';
import { useI18n } from '@/i18n';

const LOGO = (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width={30} height={30} style={{ flexShrink: 0 }}>
    <rect x="2" y="5" width="32" height="26" rx="13" ry="13" fill="rgba(255,255,255,0.12)" stroke="#fff" strokeWidth="2" />
    <rect x="11" y="11" width="14" height="14" rx="4" fill="#fff" opacity="0.95" />
    <circle cx="15" cy="17" r="2" fill="#C74634" />
    <circle cx="21" cy="17" r="2" fill="#C74634" />
    <circle cx="15" cy="16.7" r="0.7" fill="#fff" />
    <circle cx="21" cy="16.7" r="0.7" fill="#fff" />
    <rect x="14" y="21" width="8" height="1.5" rx="0.75" fill="#C74634" opacity="0.6" />
    <line x1="18" y1="11" x2="18" y2="6" stroke="#fff" strokeWidth="1.2" strokeLinecap="round" />
    <circle cx="18" cy="5.5" r="1.5" fill="#fff" opacity="0.9" />
  </svg>
);

const SZ = 18;

const TerraformIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 64 64" fill="#7B42BC" style={{ flexShrink: 0 }}>
    <polygon points="22.4,0 41.6,11.1 41.6,33.2 22.4,22.1" />
    <polygon points="44,12.3 63.2,23.4 63.2,45.4 44,34.4" />
    <polygon points="0.8,12.3 20,23.4 20,45.4 0.8,34.4" />
    <polygon points="22.4,35.5 41.6,46.6 41.6,68.7 22.4,57.6" />
  </svg>
);

interface NavItem {
  to: string;
  icon: React.ReactNode;
  labelKey: string;
  adminOnly?: boolean;
  sub?: boolean;
}

const NAV_SECTIONS: { titleKey: string; items: NavItem[] }[] = [
  {
    titleKey: 'nav.principal',
    items: [
      { to: '/chat', icon: <MessageSquare size={SZ} />, labelKey: 'nav.chat' },
      { to: '/terraform', icon: <TerraformIcon size={SZ + 2} />, labelKey: 'nav.terraform' },
      { to: '/terraform/prompt', icon: <Sparkles size={SZ} />, labelKey: 'nav.promptGen', sub: true },
      { to: '/terraform/workspaces', icon: <FolderOpen size={SZ} />, labelKey: 'nav.workspaces', sub: true },
      { to: '/explorer', icon: <Search size={SZ} />, labelKey: 'nav.explorer' },
      { to: '/reports', icon: <BarChart3 size={SZ} />, labelKey: 'nav.reports' },
    ],
  },
  {
    titleKey: 'nav.config',
    items: [
      { to: '/config/oci', icon: <Cloud size={SZ} />, labelKey: 'nav.ociCreds' },
      { to: '/config/genai', icon: <Brain size={SZ} />, labelKey: 'nav.genai' },
      { to: '/config/mcp', icon: <Plug size={SZ} />, labelKey: 'nav.mcp' },
      { to: '/config/adb', icon: <Database size={SZ} />, labelKey: 'nav.adb' },
      { to: '/config/embeddings', icon: <Dna size={SZ} />, labelKey: 'nav.embeddings' },
      { to: '/config/embeddings/consult', icon: <MessageSquare size={SZ} />, labelKey: 'nav.embConsult', sub: true },
    ],
  },
  {
    titleKey: 'nav.admin',
    items: [
      { to: '/admin/users', icon: <Users size={SZ} />, labelKey: 'nav.users', adminOnly: true },
      { to: '/admin/mfa', icon: <Lock size={SZ} />, labelKey: 'nav.mfa' },
      { to: '/admin/audit', icon: <FileText size={SZ} />, labelKey: 'nav.audit', adminOnly: true },
    ],
  },
];

export default function Sidebar() {
  const { toggle, isDark } = useTheme();
  const { user, logout } = useAuthStore();
  const { t, lang, setLang } = useI18n();

  return (
    <aside className="fixed top-0 left-0 bottom-0 w-[260px] flex flex-col z-50"
      style={{ background: 'var(--bg1)', borderRight: '1px solid var(--bd)' }}>

      {/* Header */}
      <div className="px-5 py-5 relative overflow-hidden"
        style={{ background: 'linear-gradient(145deg, #c74634 0%, #a83428 50%, #8b2a20 100%)' }}>
        <div className="absolute top-[-30%] right-[-20%] w-[120px] h-[120px] rounded-full"
          style={{ background: 'radial-gradient(circle, rgba(255,255,255,.08) 0%, transparent 70%)' }} />
        <div className="flex items-center gap-3 relative z-10">
          {LOGO}
          <div>
            <h1 className="text-sm font-bold text-white tracking-tight">AI Agent</h1>
            <p className="text-[.65rem] text-white/60 mt-0.5" style={{ fontFamily: 'var(--fm)' }}>
              {t('sidebar.subtitle')}
            </p>
          </div>
        </div>
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto px-2.5 py-3">
        {NAV_SECTIONS.map((section) => (
          <div key={section.titleKey} className="mb-1">
            <div className="text-[.6rem] uppercase tracking-[.14em] font-bold px-3 pt-4 pb-2"
              style={{ color: 'var(--t4)' }}>
              {t(section.titleKey)}
            </div>
            {section.items
              .filter((item) => !item.adminOnly || user?.role === 'admin')
              .map((item) => (
                <NavLink
                  key={item.to}
                  to={item.to}
                  end={item.to === '/terraform' || item.to === '/config/embeddings'}
                  className={`flex items-center gap-3 rounded-xl font-medium transition-all duration-200 ${
                    item.sub
                      ? 'pl-9 pr-3 py-2 text-[.78rem] opacity-90'
                      : 'px-3 py-2.5 text-[.82rem]'
                  }`}
                  style={({ isActive }) => isActive ? {
                    background: 'var(--acl2)',
                    color: 'var(--ac)',
                    boxShadow: 'inset 3px 0 0 var(--ac)',
                  } : {
                    color: 'var(--t2)',
                  }}
                >
                  {item.icon}
                  {t(item.labelKey)}
                </NavLink>
              ))}
          </div>
        ))}
      </nav>

      {/* Footer */}
      <div className="px-3 py-3.5 flex items-center gap-2" style={{ borderTop: '1px solid var(--bd)' }}>
        <button
          onClick={toggle}
          className="p-2.5 rounded-xl transition-all duration-200"
          style={{ color: 'var(--t3)' }}
          title={isDark ? t('sidebar.lightMode') : t('sidebar.darkMode')}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg3)'; e.currentTarget.style.color = 'var(--t1)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = ''; e.currentTarget.style.color = 'var(--t3)'; }}
        >
          {isDark ? <Sun size={18} /> : <Moon size={18} />}
        </button>
        <button
          onClick={() => setLang(lang === 'pt' ? 'en' : 'pt')}
          className="p-2.5 rounded-xl transition-all duration-200 flex items-center gap-1"
          style={{ color: 'var(--t3)' }}
          title={lang === 'pt' ? 'English' : 'Português'}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg3)'; e.currentTarget.style.color = 'var(--t1)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = ''; e.currentTarget.style.color = 'var(--t3)'; }}
        >
          <Languages size={18} />
          <span className="text-[.65rem] font-bold uppercase">{lang}</span>
        </button>
        <div className="flex-1 flex items-center gap-2 min-w-0">
          <div className="w-7 h-7 rounded-lg flex items-center justify-center text-[.7rem] font-bold text-white flex-shrink-0"
            style={{ background: 'var(--ac)' }}>
            {user?.username?.charAt(0).toUpperCase()}
          </div>
          <div className="min-w-0">
            <p className="text-[.75rem] font-medium truncate" style={{ color: 'var(--t1)' }}>{user?.username}</p>
            <p className="text-[.6rem] truncate" style={{ color: 'var(--t4)' }}>
              {user?.role === 'admin' ? t('sidebar.roleAdmin') : t('sidebar.roleUser')}
            </p>
          </div>
        </div>
        <button
          onClick={logout}
          className="p-2.5 rounded-xl transition-all duration-200"
          style={{ color: 'var(--t3)' }}
          title={t('sidebar.logout')}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--rdl)'; e.currentTarget.style.color = 'var(--rd)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = ''; e.currentTarget.style.color = 'var(--t3)'; }}
        >
          <LogOut size={18} />
        </button>
      </div>
    </aside>
  );
}
