import {
  Home, Clock, BarChart3, Calendar, Pill,
  Activity, Beaker, ImageIcon, Watch, LogOut, Settings, Syringe, Undo2
} from 'lucide-react';
import { useLocation } from 'react-router-dom';
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarMenuButton,
} from './ui/sidebar';
import { useAuthStore } from '../store/useAuthStore';

const navItems = [
  { icon: Home,      label: 'Dashboard',     	path: '/' },
  { icon: Clock,     label: 'Timeline',      	path: '/timeline' },
  { icon: BarChart3, label: 'Plots',         	path: '/plots' },
  { icon: Calendar,  label: 'Hospital Visits',  path: '/visits' },
  { icon: Pill,      label: 'Prescriptions',    path: '/prescriptions' },
  { icon: Activity,  label: 'Diagnoses',        path: '/diagnoses' },
  { icon: Beaker,    label: 'Lab Tests',        path: '/tests' },
  { icon: ImageIcon, label: 'Imaging',          path: '/images' },
  { icon: Syringe,   label: 'Vaccinations',     path: '/vaccinations' },
  { icon: Watch,     label: 'Wearable Devices', path: '/devices' },
];

type AppSidebarProps = {
  basePath?: string;
  showReturnToDashboard?: boolean;
  returnToDashboardPath?: string;
  hideSettings?: boolean;
  hideDevices?: boolean;
  onReturnToDashboard?: () => void;
};

function normalizeBasePath(basePath?: string) {
  if (!basePath) return '';
  return basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
}

function withBase(path: string, basePath?: string) {
  const cleanBase = normalizeBasePath(basePath);
  if (!cleanBase) return path;
  return path === '/' ? cleanBase : `${cleanBase}${path}`;
}

export function AppSidebar({
  basePath,
  showReturnToDashboard = false,
  returnToDashboardPath = '/patients',
  hideSettings = false,
  hideDevices = false,
  onReturnToDashboard,
}: AppSidebarProps) {
  const location = useLocation();
  const logout = useAuthStore((s) => s.logout);
  const cleanBase = normalizeBasePath(basePath);

  return (
    <Sidebar collapsible="none">
      {/* ── Header ── */}
      <SidebarHeader className="justify-center px-4 pb-5 pt-6">
        <div className="flex min-w-0 flex-col items-center gap-2 text-center">
          <img
            src="/images/logo.png"
            alt="Hipograf"
            className="h-12 w-12 flex-shrink-0 object-contain"
          />
          <span className="block max-w-full truncate font-display text-[18px] font-semibold tracking-tight text-gray-900">
            Hipograf
          </span>
        </div>
      </SidebarHeader>

      {/* ── Nav ── */}
      <SidebarContent>
        <SidebarGroup>
          {navItems.filter((item) => !(hideDevices && item.path === '/devices')).map((item) => {
            const itemPath = withBase(item.path, cleanBase);
            const isActive =
              item.path === '/'
                ? location.pathname === itemPath || location.pathname === `${itemPath}/`
                : location.pathname.startsWith(itemPath);
            return (
              <SidebarMenuButton
                key={item.path}
                icon={<item.icon className="w-[18px] h-[18px]" />}
                label={item.label}
                href={itemPath}
                active={isActive}
              />
            );
          })}
        </SidebarGroup>
      </SidebarContent>

      {/* ── Footer ── */}
      <SidebarFooter>
        {showReturnToDashboard && (
          <SidebarMenuButton
            icon={<Undo2 className="w-[18px] h-[18px]" />}
            label="Return To Dashboard"
            href={returnToDashboardPath}
            onClick={onReturnToDashboard}
            className="text-gray-600 hover:text-gray-900 hover:bg-gray-100"
          />
        )}
        {!hideSettings && (
          <SidebarMenuButton
            icon={<Settings className="w-[18px] h-[18px]" />}
            label="Settings"
            href={withBase('/settings', cleanBase)}
            active={location.pathname === withBase('/settings', cleanBase)}
          />
        )}
        <SidebarMenuButton
          icon={<LogOut className="w-[18px] h-[18px]" />}
          label="Logout"
          href="#"
          onClick={logout}
          className="text-gray-400 hover:text-red-500 hover:bg-red-50"
        />
      </SidebarFooter>
    </Sidebar>
  );
}
