import { useState, useEffect } from 'react';
import { NavLink, Link, useNavigate } from 'react-router-dom';
import {
  LayoutDashboard, Users, Briefcase, CheckCircle2, Calendar, Mail,
  FolderKanban, Clock, Receipt, Wallet, BarChart3,
  Server, Share2, Network, Radar, Sparkles, Settings,
  Search, Bell, LogOut, Menu, X, ExternalLink, ShieldCheck, PenTool, FileSearch
} from 'lucide-react';
import { useAuth } from '../auth';
import { api } from '../api';

const NAV = [
  {
    label: 'CRM',
    items: [
      { to: '/', icon: LayoutDashboard, label: 'Dashboard', end: true },
      { to: '/clients', icon: Users, label: 'Cliënten' },
      { to: '/engagements', icon: Briefcase, label: 'Engagements' },
      { to: '/tasks', icon: CheckCircle2, label: 'Taken' },
      { to: '/calendar', icon: Calendar, label: 'Agenda' },
      { to: '/email', icon: Mail, label: 'Email' }
    ]
  },
  {
    label: 'Delivery',
    items: [
      { to: '/projects', icon: FolderKanban, label: 'Projecten' },
      { to: '/time', icon: Clock, label: 'Uren' },
      { to: '/invoices', icon: Receipt, label: 'Facturen' },
      { to: '/finance', icon: Wallet, label: 'Finance' },
      { to: '/reports', icon: BarChart3, label: 'Rapporten' }
    ]
  },
  {
    label: 'Data & Infra',
    items: [
      { to: '/racks', icon: Server, label: 'Racks' },
      { to: '/networking', icon: Share2, label: 'Netwerk' },
      { to: '/diagrams', icon: Network, label: 'Diagrammen' },
      { to: '/market', icon: Radar, label: 'Market Intel' },
      { to: '/ai', icon: Sparkles, label: 'AI Studio' }
    ]
  },
  {
    label: 'Platform',
    items: [
      { to: '/settings', icon: Settings, label: 'Instellingen' }
    ]
  }
];

const LEGACY_LINKS = [
  { href: '/quality', icon: ShieldCheck, label: 'Data Quality' },
  { href: '/architecture/designer', icon: PenTool, label: 'Pro Designer' },
  { href: '/assess', icon: FileSearch, label: 'Assessments' }
];

export default function Layout({ children }) {
  const { user, logout } = useAuth();
  const navigate = useNavigate();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [unread, setUnread] = useState(0);
  const [query, setQuery] = useState('');

  useEffect(() => {
    api.get('/notifications').then(d => setUnread(d.unread || 0)).catch(() => {});
  }, []);

  const doSearch = (e) => {
    e.preventDefault();
    if (query.trim()) {
      navigate(`/search?q=${encodeURIComponent(query.trim())}`);
      setQuery('');
      setMobileOpen(false);
    }
  };

  const sidebar = (
    <div className="flex flex-col h-full">
      <div className="px-5 py-5 flex items-center gap-3 border-b border-border-soft">
        <div className="w-9 h-9 rounded-lg bg-accent-soft flex items-center justify-center glow-accent">
          <Network className="w-5 h-5 text-accent" />
        </div>
        <div>
          <div className="font-bold text-[15px] tracking-tight">Mek-Tech</div>
          <div className="text-[11px] text-muted">Consultancy Platform</div>
        </div>
      </div>

      <nav className="flex-1 overflow-y-auto py-4 px-3 space-y-5">
        {NAV.map(section => (
          <div key={section.label}>
            <div className="px-2 mb-1.5 text-[10px] font-semibold uppercase tracking-widest text-muted">
              {section.label}
            </div>
            <div className="space-y-0.5">
              {section.items.map(item => (
                <NavLink
                  key={item.to}
                  to={item.to}
                  end={item.end}
                  onClick={() => setMobileOpen(false)}
                  className={({ isActive }) =>
                    `flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] transition-colors ${
                      isActive
                        ? 'bg-accent-soft text-accent font-medium'
                        : 'text-muted hover:text-text hover:bg-card'
                    }`
                  }
                >
                  <item.icon className="w-4 h-4 shrink-0" />
                  {item.label}
                </NavLink>
              ))}
            </div>
          </div>
        ))}

        <div>
          <div className="px-2 mb-1.5 text-[10px] font-semibold uppercase tracking-widest text-muted">
            Klassiek
          </div>
          <div className="space-y-0.5">
            {LEGACY_LINKS.map(item => (
              <a
                key={item.href}
                href={item.href}
                className="flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] text-muted hover:text-text hover:bg-card transition-colors"
              >
                <item.icon className="w-4 h-4 shrink-0" />
                {item.label}
                <ExternalLink className="w-3 h-3 ml-auto opacity-50" />
              </a>
            ))}
          </div>
        </div>
      </nav>

      <div className="p-3 border-t border-border-soft">
        <div className="flex items-center gap-2.5 px-2 py-1.5">
          <div className="w-8 h-8 rounded-full bg-accent-soft flex items-center justify-center text-accent text-xs font-bold uppercase">
            {(user?.username || '?').slice(0, 2)}
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-[13px] font-medium truncate">{user?.username}</div>
            <div className="text-[11px] text-muted">{user?.role}</div>
          </div>
          <button
            onClick={logout}
            title="Uitloggen"
            className="p-1.5 rounded-md text-muted hover:text-red hover:bg-card transition-colors"
          >
            <LogOut className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="h-full flex">
      {/* Desktop sidebar */}
      <aside className="hidden lg:block w-60 shrink-0 bg-bg-soft border-r border-border-soft">
        {sidebar}
      </aside>

      {/* Mobile sidebar */}
      {mobileOpen && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div className="absolute inset-0 bg-black/60" onClick={() => setMobileOpen(false)} />
          <aside className="absolute left-0 top-0 bottom-0 w-64 bg-bg-soft border-r border-border z-50">
            {sidebar}
          </aside>
        </div>
      )}

      <div className="flex-1 flex flex-col min-w-0">
        {/* Topbar */}
        <header className="h-14 shrink-0 bg-bg-soft border-b border-border-soft flex items-center gap-3 px-4">
          <button
            className="lg:hidden p-2 rounded-md text-muted hover:text-text hover:bg-card"
            onClick={() => setMobileOpen(!mobileOpen)}
          >
            {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>

          <form onSubmit={doSearch} className="flex-1 max-w-md">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
              <input
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="Zoeken in cliënten, taken, engagements..."
                className="w-full bg-card border border-border rounded-lg pl-9 pr-3 py-1.5 text-[13px] placeholder:text-muted focus:outline-none focus:border-accent/50"
              />
            </div>
          </form>

          <div className="ml-auto flex items-center gap-1">
            <Link
              to="/notifications"
              className="relative p-2 rounded-md text-muted hover:text-text hover:bg-card transition-colors"
              title="Notificaties"
            >
              <Bell className="w-5 h-5" />
              {unread > 0 && (
                <span className="absolute top-1 right-1 w-4 h-4 rounded-full bg-red text-[10px] font-bold flex items-center justify-center pulse-dot">
                  {unread > 9 ? '9+' : unread}
                </span>
              )}
            </Link>
          </div>
        </header>

        {/* Content */}
        <main className="flex-1 overflow-y-auto p-4 lg:p-6">
          {children}
        </main>
      </div>
    </div>
  );
}
