'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { ChevronDown, FileText, Gift, Home, LayoutDashboard, LogOut, UserRound } from 'lucide-react';
import { logout } from '@/app/actions/auth';
import { isAdmin, type Role } from '@/lib/auth/roles';
import { useMessages } from '@/i18n/client';
import { LanguageSwitcher } from './LanguageSwitcher';
import { cn } from '@/lib/cn';
import { initials } from '@/lib/initials';
import { PAYMENTS_ENABLED } from '@/lib/features';

export interface SessionUser {
  name: string;
  email: string;
  role: Role;
}

export { initials };

export function UserMenu({ user, tone = 'light' }: { user: SessionUser; tone?: 'light' | 'dark' }) {
  const m = useMessages();
  const t = m.layout;
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => !ref.current?.contains(e.target as Node) && setOpen(false);
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const item = 'flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-[13px] text-ink-soft transition-colors hover:bg-canvas hover:text-ink';

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="menu"
        className={cn(
          'flex items-center gap-2 rounded-full py-1 pr-2.5 pl-1 text-[13px] font-medium transition-colors',
          tone === 'light' ? 'text-white/85 hover:bg-white/10' : 'text-ink-soft hover:bg-surface',
        )}
      >
        <span
          className={cn(
            'inline-flex size-8 items-center justify-center rounded-full text-[12px] font-semibold',
            tone === 'light' ? 'bg-white/15 text-white' : 'bg-ink text-white',
          )}
        >
          {initials(user.name)}
        </span>
        <span className="hidden max-w-[120px] truncate sm:inline">{user.name.split(' ')[0]}</span>
        <ChevronDown className="size-3.5 opacity-60" aria-hidden />
      </button>

      {open && (
        <div
          role="menu"
          className="absolute right-0 z-50 mt-2 w-64 rounded-[20px] bg-surface p-1.5 shadow-float ring-1 ring-line"
        >
          <div className="px-3 pt-2.5 pb-3">
            <p className="truncate text-sm font-semibold text-ink">{user.name}</p>
            <p className="truncate text-xs text-muted">{user.email}</p>
            {user.role !== 'USER' && (
              <span className="mt-2 inline-block rounded-full bg-accent-soft px-2 py-0.5 text-[11px] font-semibold text-accent">
                {t.roles[user.role]}
              </span>
            )}
          </div>
          <div className="h-px bg-line" />
          <div className="py-1">
            {[
              { href: '/akun', icon: Home, label: m.dash.userNav.overview },
              { href: '/akun/laporan', icon: FileText, label: m.dash.userNav.reports },
              ...(PAYMENTS_ENABLED ? [{ href: '/akun/afiliasi', icon: Gift, label: m.dash.userNav.affiliate }] : []),
              { href: '/akun/profil', icon: UserRound, label: m.dash.userNav.profile },
            ].map(({ href, icon: Icon, label }) => (
              <Link key={href} role="menuitem" href={href} className={item} onClick={() => setOpen(false)}>
                <Icon className="size-4" aria-hidden />
                {label}
              </Link>
            ))}
            {isAdmin(user.role) && (
              <Link role="menuitem" href="/admin" className={item} onClick={() => setOpen(false)}>
                <LayoutDashboard className="size-4" aria-hidden />
                {t.nav.adminPanel}
              </Link>
            )}
          </div>
          <div className="h-px bg-line" />
          <div className="px-2 py-2 sm:hidden">
            <LanguageSwitcher tone="dark" />
          </div>
          <form action={logout} className="pt-1">
            <button role="menuitem" type="submit" className={item}>
              <LogOut className="size-4" aria-hidden />
              {t.nav.signOut}
            </button>
          </form>
        </div>
      )}
    </div>
  );
}
