import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
} from 'react';
import { Link } from 'react-router-dom';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { PanelLeft } from 'lucide-react';
import { cn } from '../../utils/helpers';

// ─── Constants ────────────────────────────────────────────────────────────────

const SIDEBAR_WIDTH = '216px';
const SIDEBAR_COLLAPSED_WIDTH = '64px';

// ─── Context ──────────────────────────────────────────────────────────────────

type SidebarState = 'expanded' | 'collapsed';

interface SidebarContextValue {
  state: SidebarState;
  open: boolean;
  setOpen: (v: boolean) => void;
  isMobile: boolean;
  openMobile: boolean;
  setOpenMobile: (v: boolean) => void;
  toggleSidebar: () => void;
}

const SidebarCtx = createContext<SidebarContextValue | null>(null);

export function useIsMac() {
  const [isMac, setIsMac] = useState(false);

  useEffect(() => {
    // Check if the platform string contains 'Mac'
    const platform = (window.navigator as any)?.userAgentData?.platform || window.navigator?.platform || '';
    setIsMac(/Mac|iPhone|iPod|iPad/i.test(platform));
  }, []);

  return isMac;
}

export function useSidebar() {
  const ctx = useContext(SidebarCtx);
  if (!ctx) throw new Error('useSidebar must be used within <SidebarProvider>');
  return ctx;
}

function useIsMobile() {
  const [isMobile, setIsMobile] = useState(
    () => typeof window !== 'undefined' && window.innerWidth < 768
  );
  useEffect(() => {
    const mq = window.matchMedia('(max-width: 767px)');
    const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches);
    mq.addEventListener('change', handler);
    setIsMobile(mq.matches);
    return () => mq.removeEventListener('change', handler);
  }, []);
  return isMobile;
}

// ─── SidebarProvider ──────────────────────────────────────────────────────────

export function SidebarProvider({
  defaultOpen = true,
  open: controlledOpen,
  onOpenChange,
  children,
  className,
  style,
  ...props
}: React.ComponentProps<'div'> & {
  defaultOpen?: boolean;
  open?: boolean;
  onOpenChange?: (v: boolean) => void;
}) {
  const isMobile = useIsMobile();
  const [open, _setOpen] = useState(defaultOpen);
  const [openMobile, setOpenMobile] = useState(false);

  const effectiveOpen = controlledOpen ?? open;

  const setOpen = useCallback(
    (v: boolean) => {
      _setOpen(v);
      onOpenChange?.(v);
    },
    [onOpenChange]
  );

  const toggleSidebar = useCallback(() => {
    if (isMobile) setOpenMobile((v) => !v);
    else setOpen(!effectiveOpen);
  }, [isMobile, effectiveOpen, setOpen]);

  // ⌘B / Ctrl+B
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'b' && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        toggleSidebar();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [toggleSidebar]);

  const state: SidebarState = effectiveOpen ? 'expanded' : 'collapsed';

  return (
    <SidebarCtx.Provider
      value={{
        state,
        open: effectiveOpen,
        setOpen,
        isMobile,
        openMobile,
        setOpenMobile,
        toggleSidebar,
      }}
    >
      <TooltipPrimitive.Provider delayDuration={400}>
        <div
          style={
            {
              '--sidebar-width': SIDEBAR_WIDTH,
              '--sidebar-collapsed-width': SIDEBAR_COLLAPSED_WIDTH,
              ...style,
            } as React.CSSProperties
          }
          className={cn('flex h-screen w-full overflow-hidden', className)}
          {...props}
        >
          {children}
        </div>
      </TooltipPrimitive.Provider>
    </SidebarCtx.Provider>
  );
}

// ─── Sidebar ──────────────────────────────────────────────────────────────────

export function Sidebar({
  collapsible = 'icon',
  className,
  children,
  ...props
}: React.ComponentProps<'aside'> & {
  collapsible?: 'icon' | 'offcanvas' | 'none';
}) {
  const { state, openMobile, setOpenMobile, isMobile } = useSidebar();

  if (isMobile) {
    return (
      <>
        {openMobile && (
          <div
            className="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
            onClick={() => setOpenMobile(false)}
          />
        )}
        <aside
          className={cn(
            'fixed inset-y-0 left-0 z-50 flex h-full w-[var(--sidebar-width)] flex-col bg-white shadow-2xl transition-transform duration-300 ease-out',
            openMobile ? 'translate-x-0' : '-translate-x-full',
            className
          )}
          {...props}
        >
          {children}
        </aside>
      </>
    );
  }

  if (collapsible === 'none') {
    return (
      <aside
        className={cn(
          'hidden md:flex sidebar-frame flex-col w-[var(--sidebar-width)] flex-shrink-0',
          className
        )}
        {...props}
      >
        {children}
      </aside>
    );
  }

  return (
    <aside
      data-state={state}
      data-collapsible={collapsible}
      className={cn(
        'hidden md:flex sidebar-frame flex-col flex-shrink-0 transition-[width] duration-300 ease-in-out',
        state === 'expanded'
          ? 'w-[var(--sidebar-width)]'
          : 'w-[var(--sidebar-collapsed-width)]',
        className
      )}
      {...props}
    >
      {children}
    </aside>
  );
}

// ─── SidebarInset (main content area) ─────────────────────────────────────────

export function SidebarInset({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  return (
    <div
      className={cn(
        'relative flex flex-1 flex-col overflow-hidden',
        className
      )}
      {...props}
    />
  );
}

// ─── Layout slots ─────────────────────────────────────────────────────────────

export function SidebarHeader({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  return (
    <div
      className={cn('flex flex-shrink-0 px-3 py-4', className)}
      {...props}
    />
  );
}

export function SidebarFooter({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  return (
    <div
      className={cn(
        'flex flex-shrink-0 flex-col border-t border-gray-100 px-3 py-3',
        className
      )}
      {...props}
    />
  );
}

export function SidebarContent({
  className,
  ...props
}: React.ComponentProps<'nav'>) {
  return (
    <nav
      className={cn(
        'flex flex-1 flex-col overflow-y-auto overflow-x-hidden px-3 py-2',
        className
      )}
      {...props}
    />
  );
}

export function SidebarGroup({
  className,
  ...props
}: React.ComponentProps<'div'>) {
  return (
    <div className={cn('flex flex-col gap-0.5', className)} {...props} />
  );
}

// ─── SidebarTrigger ───────────────────────────────────────────────────────────

export function SidebarTrigger({
  className,
  onClick,
  ...props
}: React.ComponentProps<'button'>) {
  const { toggleSidebar, state } = useSidebar();
  const isMac = useIsMac(); // Get the OS info

  // Define the shortcut label based on the OS
  const shortcutLabel = isMac ? '⌘B' : 'Ctrl+B';

  return (
    <button
      onClick={(e) => {
        onClick?.(e);
        toggleSidebar();
      }}
      className={cn(
        'inline-flex flex-shrink-0 items-center justify-center rounded-md h-8 w-8 text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-all duration-150',
        className
      )}
      aria-label="Toggle sidebar"
      // Use the dynamic label here
      title={`Toggle sidebar (${shortcutLabel})`}
      {...props}
    >
      <PanelLeft
        className={cn(
          'h-4 w-4 transition-transform duration-300',
          state === 'collapsed' && 'rotate-180'
        )}
      />
    </button>
  );
}

// ─── SidebarMenuButton ────────────────────────────────────────────────────────

export function SidebarMenuButton({
  icon,
  label,
  href,
  active = false,
  onClick,
  className,
}: {
  icon: React.ReactNode;
  label: string;
  href: string;
  active?: boolean;
  onClick?: () => void;
  className?: string;
}) {
  const { state } = useSidebar();
  const collapsed = state === 'collapsed';
  const isAction = href === '#' || !href;

  const baseClass = cn(
    'group/item relative flex w-full items-center rounded-lg h-10 text-sm font-medium select-none cursor-pointer overflow-hidden gap-3 px-3 transition-[background-color,color] duration-300 ease-in-out',
    active
      ? 'bg-primary/[0.08] text-primary'
      : 'text-gray-500 hover:bg-gray-50 hover:text-gray-800',
    className
  );

  const content = (
    <>
      {/* Left accent bar */}
      <span
        className={cn(
          'absolute left-0 top-1/2 -translate-y-1/2 w-0.5 rounded-full bg-primary transition-[height,opacity] duration-300 ease-in-out',
          active && !collapsed ? 'h-5 opacity-100' : 'h-0 opacity-0'
        )}
      />

      {/* Icon */}
      <span
        className={cn(
          'flex flex-shrink-0 items-center justify-center',
          !active && 'group-hover/item:text-gray-600',
          active ? 'text-primary' : 'text-gray-400'
        )}
      >
        {icon}
      </span>

      {/* Label — always rendered, animated via width + opacity */}
      <span
        className={cn(
          'truncate whitespace-nowrap transition-[opacity,max-width] duration-300 ease-in-out',
          collapsed ? 'max-w-0 opacity-0' : 'max-w-[180px] opacity-100'
        )}
      >
        {label}
      </span>
    </>
  );

  const element = isAction ? (
    <button type="button" onClick={onClick} className={baseClass}>
      {content}
    </button>
  ) : (
    <Link to={href} onClick={onClick} className={baseClass}>
      {content}
    </Link>
  );

  if (!collapsed) return element;

  return (
    <TooltipPrimitive.Root>
      <TooltipPrimitive.Trigger asChild>{element}</TooltipPrimitive.Trigger>
      <TooltipPrimitive.Portal>
        <TooltipPrimitive.Content
          side="right"
          sideOffset={10}
          className="z-50 rounded-md bg-gray-900 px-2.5 py-1.5 text-xs font-medium text-white shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95"
        >
          {label}
          <TooltipPrimitive.Arrow className="fill-gray-900" />
        </TooltipPrimitive.Content>
      </TooltipPrimitive.Portal>
    </TooltipPrimitive.Root>
  );
}

// ─── MobileSidebarTrigger ─────────────────────────────────────────────────────

export function MobileSidebarTrigger({
  className,
}: {
  className?: string;
}) {
  const { setOpenMobile, isMobile } = useSidebar();
  if (!isMobile) return null;
  return (
    <div
      className={cn(
        'flex items-center h-14 px-4 border-b border-gray-100 bg-white flex-shrink-0',
        className
      )}
    >
      <button
        onClick={() => setOpenMobile(true)}
        className="inline-flex items-center justify-center rounded-md h-9 w-9 text-gray-500 hover:bg-gray-100 transition-colors"
        aria-label="Open menu"
      >
        <PanelLeft className="h-5 w-5" />
      </button>
    </div>
  );
}
