import { Outlet, NavLink, useNavigate, Link, useLocation } from 'react-router-dom'
import { LayoutDashboard, Package, Settings, LogOut, FlaskConical, Activity, Library, Plus, SlidersHorizontal, Building2, GitBranch, Image, BellRing, Receipt, Server, Upload, Menu, X, MessageSquare } from 'lucide-react'
import { useAuthStore, isAdmin as checkIsAdmin, isPrivileged as checkIsPrivileged } from '../../store/auth'
import { clsx } from 'clsx'
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getWorkerActivity } from '../../api/worker'
import { listOrders } from '../../api/orders'
import NotificationCenter from './NotificationCenter'
import ChatPanel from '../chat/ChatPanel'

const nav = [
  { to: '/', icon: LayoutDashboard, label: 'Dashboard', end: true },
  { to: '/orders', icon: Package, label: 'Orders' },
  { to: '/products', icon: Library, label: 'Products' },
  { to: '/materials', icon: FlaskConical, label: 'Materials' },
  { to: '/activity', icon: Activity, label: 'Activity' },
  { to: '/preferences', icon: SlidersHorizontal, label: 'Preferences' },
  { to: '/upload', icon: Upload, label: 'Upload' },
]

const privilegedNav = [
  { to: '/admin', icon: Settings, label: 'Admin' },
  { to: '/billing', icon: Receipt, label: 'Billing' },
  { to: '/media', icon: Image, label: 'Media Browser' },
  { to: '/workers', icon: Server, label: 'Workers' },
  { to: '/workflows', icon: GitBranch, label: 'Workflows' },
  { to: '/asset-libraries', icon: Library, label: 'Asset Libraries' },
]

const adminOnlyNav = [
  { to: '/notification-settings', icon: BellRing, label: 'Notification Settings' },
  { to: '/tenants', icon: Building2, label: 'Tenants' },
]

export default function Layout() {
  const { user, logout } = useAuthStore()
  const navigate = useNavigate()
  const location = useLocation()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [chatOpen, setChatOpen] = useState(false)

  // Extract page context from URL for the chat agent
  const chatContext = (() => {
    const path = location.pathname
    const orderMatch = path.match(/^\/orders\/([0-9a-f-]{36})/)
    if (orderMatch) return { type: 'order', id: orderMatch[1] }
    const productMatch = path.match(/^\/products\/([0-9a-f-]{36})/)
    if (productMatch) return { type: 'product', id: productMatch[1] }
    return { type: undefined, id: undefined }
  })()

  const { data: activity } = useQuery({
    queryKey: ['worker-activity'],
    queryFn: getWorkerActivity,
    refetchInterval: 60_000,
    staleTime: 30_000,
  })

  const { data: draftOrders } = useQuery({
    queryKey: ['orders', 'draft-count'],
    queryFn: () => listOrders({ status: 'draft' }),
    staleTime: 10_000,
    refetchInterval: 30_000,
  })
  const draftCount = draftOrders?.length ?? 0

  function handleLogout() {
    logout()
    navigate('/login')
  }

  return (
    <div className="flex h-screen overflow-hidden bg-surface-alt">
      {/* Mobile top header bar */}
      <header className="fixed top-0 left-0 right-0 z-30 md:hidden bg-surface border-b border-border-default h-12 flex items-center px-4 gap-3">
        <button
          onClick={() => setSidebarOpen(true)}
          className="text-content-secondary hover:text-content transition-colors"
          aria-label="Open navigation"
        >
          <Menu size={20} />
        </button>
        <span className="flex-1 text-sm font-semibold text-content">Hart.O.Mat</span>
        <NotificationCenter />
      </header>

      {/* Overlay backdrop (mobile only) */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-30 md:hidden"
          style={{ backgroundColor: 'rgba(0,0,0,0.4)' }}
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={clsx(
          'fixed left-0 top-0 h-full z-40 w-60 bg-surface border-r border-border-default flex flex-col transform transition-transform duration-200',
          'md:relative md:translate-x-0 md:flex-shrink-0',
          sidebarOpen ? 'translate-x-0' : '-translate-x-full',
        )}
      >
        <div className="p-5 border-b border-border-default">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-accent rounded flex items-center justify-center">
              <span className="text-accent-text text-sm font-bold">H</span>
            </div>
            <div className="flex-1">
              <p className="font-semibold text-content text-sm">Hart.O.Mat</p>
              <p className="text-xs text-content-muted">Hartomatisierung</p>
            </div>
            {/* NotificationCenter in sidebar header (desktop); hidden on mobile (shown in top bar) */}
            <span className="hidden md:block">
              <NotificationCenter />
            </span>
            {/* Close button — mobile only */}
            <button
              onClick={() => setSidebarOpen(false)}
              className="md:hidden text-content-secondary hover:text-content transition-colors"
              aria-label="Close navigation"
            >
              <X size={20} />
            </button>
          </div>
        </div>

        <nav className="flex-1 p-3 space-y-1 overflow-y-auto">
          {/* New Order — primary CTA at the top */}
          <Link
            to="/orders/new"
            onClick={() => setSidebarOpen(false)}
            className="flex items-center gap-2 px-3 py-2.5 mb-3 rounded-md text-sm font-semibold bg-accent text-accent-text hover:bg-accent-hover transition-colors shadow-sm"
          >
            <Plus size={18} />
            New Order
          </Link>

          {nav.map(({ to, icon: Icon, label, end }) => {
            const isActivity = to === '/activity'
            const isOrders = to === '/orders'
            const showSpinner = isActivity && ((activity?.active_count ?? 0) + (activity?.render_active_count ?? 0)) > 0
            const showFailed = isActivity && !showSpinner && ((activity?.failed_count ?? 0) + (activity?.render_failed_count ?? 0)) > 0
            const showDraftBadge = isOrders && draftCount > 0
            return (
              <NavLink
                key={to}
                to={to}
                end={end}
                onClick={() => setSidebarOpen(false)}
                className={({ isActive }) =>
                  clsx(
                    'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                    isActive
                      ? 'bg-accent-light text-accent'
                      : 'text-content-secondary hover:bg-surface-hover',
                  )
                }
              >
                <Icon size={18} />
                {label}
                {showDraftBadge && (
                  <span className="ml-auto text-xs px-1.5 py-0.5 rounded-full bg-surface-muted text-content-muted font-semibold leading-none">
                    {draftCount}
                  </span>
                )}
                {showSpinner && (
                  <span className="ml-auto w-2 h-2 rounded-full bg-blue-500 animate-pulse" title="Processing…" />
                )}
                {showFailed && (
                  <span className="ml-auto w-2 h-2 rounded-full bg-red-500" title="Failed tasks" />
                )}
              </NavLink>
            )
          })}

          {checkIsPrivileged(user) && (
            <>
              <div className="pt-2 pb-1 px-3">
                <span className="text-[10px] font-semibold uppercase tracking-widest text-content-muted">
                  Management
                </span>
              </div>
              {privilegedNav.map(({ to, icon: Icon, label }) => (
                <NavLink
                  key={to}
                  to={to}
                  onClick={() => setSidebarOpen(false)}
                  className={({ isActive }) =>
                    clsx(
                      'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                      isActive
                        ? 'bg-accent-light text-accent'
                        : 'text-content-secondary hover:bg-surface-hover',
                    )
                  }
                >
                  <Icon size={18} />
                  {label}
                </NavLink>
              ))}
            </>
          )}

          {checkIsAdmin(user) && (
            <>
              <div className="pt-2 pb-1 px-3">
                <span className="text-[10px] font-semibold uppercase tracking-widest text-content-muted">
                  Admin Only
                </span>
              </div>
              {adminOnlyNav.map(({ to, icon: Icon, label }) => (
                <NavLink
                  key={to}
                  to={to}
                  onClick={() => setSidebarOpen(false)}
                  className={({ isActive }) =>
                    clsx(
                      'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                      isActive
                        ? 'bg-accent-light text-accent'
                        : 'text-content-secondary hover:bg-surface-hover',
                    )
                  }
                >
                  <Icon size={18} />
                  {label}
                </NavLink>
              ))}
            </>
          )}
        </nav>

        <div className="p-3 border-t border-border-default space-y-1">
          <div className="flex items-center gap-3 px-3 py-2">
            <div className="w-7 h-7 bg-accent rounded-full flex items-center justify-center shrink-0">
              <span className="text-accent-text text-xs font-bold">{user?.full_name?.[0] ?? 'U'}</span>
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-content truncate">{user?.full_name}</p>
              <p className="text-xs text-content-muted truncate">
                {user?.role === 'project_manager' ? 'Project Manager' : user?.role}
              </p>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="flex items-center gap-2 w-full px-3 py-2 text-sm text-content-secondary hover:bg-surface-hover rounded-md transition-colors"
          >
            <LogOut size={16} />
            Sign out
          </button>
        </div>
      </aside>

      {/* Main content — shrinks when chat panel is open */}
      <main className={`flex-1 overflow-auto min-w-0 pt-12 md:pt-0 transition-all duration-300 ${chatOpen ? 'mr-96' : ''}`}>
        <Outlet />
      </main>

      {/* Chat floating button */}
      {!chatOpen && (
        <button
          onClick={() => setChatOpen(true)}
          className="fixed bottom-6 right-6 z-30 w-12 h-12 rounded-full bg-accent text-accent-text shadow-lg hover:bg-accent-hover hover:scale-105 transition-all flex items-center justify-center"
          title="AI Assistant"
        >
          <MessageSquare size={22} />
        </button>
      )}

      {/* Chat panel */}
      {chatOpen && <ChatPanel open={chatOpen} onClose={() => setChatOpen(false)} contextType={chatContext.type} contextId={chatContext.id} />}
    </div>
  )
}
