import { NavLink } from 'react-router';
import { motion } from 'framer-motion';
import {
  LayoutDashboard,
  AppWindow,
  Search,
  CircleHelp,
} from 'lucide-react';
import { cn } from '@/lib/utils';

function getGreeting(): string {
  const hour = new Date().getHours();
  if (hour < 12) return 'Good Morning';
  if (hour < 18) return 'Good Afternoon';
  return 'Good Evening';
}

interface SidebarProps {
  userName?: string;
  botName?: string;
  backendStatus?: 'healthy' | 'restarting';
  onNavigate?: () => void;
}

export default function Sidebar({ userName, botName = 'Bloby', backendStatus = 'healthy', onNavigate }: SidebarProps) {
  const firstName = userName?.split(/\s+/)[0] || 'Human';
  return (
    <aside className="flex flex-col h-full w-64 bg-transparent p-5 pt-8">
      {/* Logo */}
      <div className="flex items-center gap-2.5 mb-8 shrink-0">
        <img src="/morphy.png" alt={botName} className="h-7 w-auto" />
        <span className="font-bold text-lg" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>{botName}</span>
      </div>

      {/* Greeting */}
      <div className="mb-10 shrink-0">
        <h1 className="text-4xl font-bold leading-[1.1]">
          {getGreeting()}{firstName ? ',' : ''}
        </h1>
        {firstName && (
          <h2
            className="text-4xl font-bold mt-0.5 tracking-tight leading-[1.08] w-fit"
            style={{
              backgroundImage: 'linear-gradient(to right, #0166FF, #009AFE, #4AEEFF)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              backgroundClip: 'text',
            }}
          >
            {firstName}.
          </h2>
        )}
      </div>

      {/* Navigation — min-h-0 lets this flex child shrink below its content height
          (flex items default to min-height:auto), so the list scrolls instead of
          pushing the status pill past the card's clipped bottom edge. */}
      <nav className="flex-1 min-h-0 overflow-y-auto space-y-0.5">
        <NavItem to="/" icon={LayoutDashboard} label="Dashboard" onNavigate={onNavigate} />
        <NavItem to="/app1" icon={AppWindow} label="App 1" onNavigate={onNavigate} />
        <NavItem to="/research" icon={Search} label="Research" onNavigate={onNavigate} />
        <NavItem to="/whatelse" icon={CircleHelp} label="What Else?" onNavigate={onNavigate} />
      </nav>

      {/* Backend status — shrink-0 + mt keeps it pinned and visible below the
          scrollable nav, never clipped by the sidebar card's rounded edge. */}
      <div className="rounded-xl bg-[#282828] px-3.5 py-2.5 flex items-center gap-2 shrink-0 mt-3">
        <span
          className={`h-2 w-2 rounded-full shrink-0 ${
            backendStatus === 'healthy' ? 'bg-emerald-500' : 'bg-orange-400 animate-pulse'
          }`}
        />
        <span className="text-xs text-muted-foreground">
          Workspace: {backendStatus === 'healthy' ? 'Live' : 'Restarting'}
        </span>
      </div>
    </aside>
  );
}

// Shared-layout spring — the active decoration slides between items on nav change.
const activeSpring = { type: 'spring' as const, stiffness: 420, damping: 34 };

/**
 * The active-item decoration — a single clean recessed dark fill (no stroke, no
 * border, no color). The shared `layoutId` makes it glide from the
 * previously-active item to the new one.
 */
function ActiveDecoration() {
  return (
    <motion.span
      layoutId="nav-active"
      className="absolute inset-0 rounded-[12px]"
      style={{
        background: '#0a0a0c',
        boxShadow: 'inset 0 1px 4px rgba(0,0,0,0.6)',
      }}
      transition={activeSpring}
    />
  );
}

function NavItem({
  to,
  icon: Icon,
  label,
  onNavigate,
}: {
  to: string;
  icon: React.ComponentType<{ className?: string; strokeWidth?: number }>;
  label: string;
  onNavigate?: () => void;
}) {
  return (
    <NavLink to={to} end onClick={onNavigate} className="block">
      {({ isActive }) => (
        <div
          className={cn(
            'relative flex items-center gap-3 w-full px-3 py-2.5 rounded-[12px] text-sm transition-colors',
            // cult-ui dark-theme text colors: active white, inactive #6b6b6d
            isActive
              ? 'text-white font-medium'
              : 'text-[#6b6b6d] hover:text-zinc-400 hover:bg-white/[0.03]',
          )}
        >
          {isActive && <ActiveDecoration />}
          <Icon className="relative z-10 h-[19px] w-[19px] shrink-0" strokeWidth={1.5} />
          <span className="relative z-10">{label}</span>
        </div>
      )}
    </NavLink>
  );
}
