'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { logoutAdmin } from '@/app/admin/login/actions';

const ADMIN_LINKS = [
  { href: '/admin/orders', label: 'Orders' },
  { href: '/admin/accounts', label: 'Accounts' },
  { href: '/admin/products/new', label: 'Add product' },
  { href: '/admin/products', label: 'All products' },
  { href: '/admin/categories/new', label: 'Add category' },
  { href: '/admin/categories', label: 'All categories' },
  { href: '/admin/proofs/new', label: 'Upload new design' },
  { href: '/admin/proofs', label: 'All proofs' },
  { href: '/admin/inbox', label: 'Inbox' },
  { href: '/admin/custom-requests', label: 'Photo requests' },
  { href: '/admin/promotions', label: 'Promotions' },
  { href: '/admin/gallery', label: 'Gallery' },
  { href: '/admin/gallery/categories', label: 'Gallery categories' },
  { href: '/admin/collections/new', label: 'Add collection' },
  { href: '/admin/collections', label: 'All collections' },
  { href: '/admin/customers', label: 'Email customers' },
  { href: '/admin/maintenance', label: 'Maintenance' },
  { href: '/admin/login-logs', label: 'Login activity' },
];

export default function AdminMenu() {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const onClickOutside = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, []);

  return (
    <div ref={ref} className="relative hidden md:block">
      <button
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        className="tag-label flex items-center gap-1 hover:text-ink"
      >
        Admin
        <span className={`inline-block transition-transform ${open ? 'rotate-180' : ''}`}>▾</span>
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-48 border border-line bg-paper shadow-sm">
          {ADMIN_LINKS.map((link) => (
            <Link
              key={link.href}
              href={link.href}
              onClick={() => setOpen(false)}
              className="block px-4 py-3 text-sm hover:bg-surface"
            >
              {link.label}
            </Link>
          ))}
          <form action={logoutAdmin}>
            <button type="submit" className="block w-full px-4 py-3 text-left text-sm hover:bg-surface">
              Log out
            </button>
          </form>
        </div>
      )}
    </div>
  );
}
