'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { LogOut, Monitor, Moon, Settings, Sun, User, Users, Wallet } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useTheme } from 'next-themes';
import { useSyncExternalStore, type ReactNode } from 'react';

import { usePopover } from '@/components/layout/use-popover';
import { Avatar } from '@/components/ui/avatar';
import { useAuth } from '@/lib/auth';
import { cn } from '@/lib/utils';
import { usePermission } from '@/hooks/use-permission';

const subscribe = () => () => undefined;

const roleLabel = (role: string): string => role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();

function MenuItem({ href, icon, children, onSelect }: { href: string; icon: ReactNode; children: ReactNode; onSelect: () => void }) {
  return (
    <Link
      href={href}
      role="menuitem"
      onClick={onSelect}
      className="flex h-9 items-center gap-2.5 rounded-md px-2.5 text-small font-medium text-foreground transition-colors hover:bg-surface-muted focus-visible:bg-surface-muted [&>svg]:h-4 [&>svg]:w-4 [&>svg]:text-muted-foreground"
    >
      {icon}
      {children}
    </Link>
  );
}

function ThemeRow() {
  const { theme, setTheme } = useTheme();
  const mounted = useSyncExternalStore(subscribe, () => true, () => false);
  const options = [
    { value: 'light', label: 'Light theme', icon: Sun },
    { value: 'dark', label: 'Dark theme', icon: Moon },
    { value: 'system', label: 'System theme', icon: Monitor },
  ] as const;
  return (
    <div className="flex items-center justify-between px-2.5 py-1.5">
      <span className="text-small font-medium text-foreground">Theme</span>
      <div className="flex rounded-md bg-surface-muted p-0.5" role="group" aria-label="Theme">
        {options.map(({ value, label, icon: Icon }) => {
          const active = mounted && theme === value;
          return (
            <button
              key={value}
              type="button"
              aria-label={label}
              aria-pressed={active}
              onClick={() => setTheme(value)}
              className={cn(
                'grid h-7 w-8 place-items-center rounded-[6px] transition-colors',
                active ? 'bg-surface text-primary shadow-xs' : 'text-muted-foreground hover:text-foreground',
              )}
            >
              <Icon className="h-3.5 w-3.5" aria-hidden="true" />
            </button>
          );
        })}
      </div>
    </div>
  );
}

/** The user dropdown. Used by the top bar avatar and the sidebar footer three-dot button. */
export function UserMenu({
  trigger,
  placement = 'bottom-end',
  label = 'Account menu',
  workspaceLinks = true,
}: {
  /** Render prop for the trigger contents. */
  trigger: ReactNode;
  placement?: 'bottom-end' | 'top-start';
  label?: string;
  /** Hide Profile/Settings/Team/Wallet (used by the platform admin shell). */
  workspaceLinks?: boolean;
}) {
  const { user, logout } = useAuth();
  const router = useRouter();
  const reduce = useReducedMotion();
  const canTeam = usePermission('team:manage');
  const canWallet = usePermission('wallet:read');
  const { open, toggle, close, rootRef, triggerRef } = usePopover();
  if (user === null) return null;
  const select = () => close(false);

  return (
    <div ref={rootRef} className="relative">
      <button
        ref={triggerRef}
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={label}
        onClick={toggle}
        className="grid place-items-center rounded-full transition-shadow"
      >
        {trigger}
      </button>
      <AnimatePresence>
        {open ? (
          <motion.div
            role="menu"
            aria-label={label}
            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: placement === 'bottom-end' ? -4 : 4 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.97 }}
            transition={{ duration: 0.14, ease: [0.2, 0.8, 0.2, 1] }}
            className={cn(
              'absolute z-50 w-60 rounded-lg border border-border bg-surface p-1 shadow-md',
              placement === 'bottom-end' ? 'right-0 top-full mt-2 origin-top-right' : 'bottom-full left-0 mb-2 origin-bottom-left',
            )}
          >
            <div className="flex items-center gap-3 px-2.5 pb-3 pt-2">
              <Avatar name={user.name} size="md" />
              <div className="min-w-0 flex-1">
                <p className="truncate text-small font-semibold">{user.name}</p>
                <p className="truncate text-caption text-muted-foreground">{user.email}</p>
              </div>
            </div>
            <div className="px-2.5 pb-2">
              <span className="inline-flex rounded-pill bg-primary-soft px-2 py-0.5 text-[11px] font-semibold text-primary">
                {user.isSuperAdmin ? 'Platform admin' : roleLabel(user.role)}
              </span>
            </div>
            {workspaceLinks ? (
              <>
            <div className="my-1 h-px bg-border" />
            <MenuItem href="/settings/profile" icon={<User />} onSelect={select}>
              Profile
            </MenuItem>
            <MenuItem href="/settings/profile" icon={<Settings />} onSelect={select}>
              Settings
            </MenuItem>
            {canTeam ? (
              <MenuItem href="/settings/team" icon={<Users />} onSelect={select}>
                Team
              </MenuItem>
            ) : null}
            {canWallet ? (
              <MenuItem href="/wallet" icon={<Wallet />} onSelect={select}>
                Wallet
              </MenuItem>
            ) : null}
              </>
            ) : null}
            <div className="my-1 h-px bg-border" />
            <ThemeRow />
            <div className="my-1 h-px bg-border" />
            <button
              type="button"
              role="menuitem"
              className="flex h-9 w-full items-center gap-2.5 rounded-md px-2.5 text-small font-medium text-danger transition-colors hover:bg-danger-soft"
              onClick={() => {
                select();
                void logout().finally(() => router.push('/login'));
              }}
            >
              <LogOut className="h-4 w-4" aria-hidden="true" />
              Log out
            </button>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </div>
  );
}
