'use client';

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

interface MenuItem {
  href?: string;
  label: string;
  submenu?: MenuItem[];
}

const ADMIN_LINKS: MenuItem[] = [
  { href: '/admin/orders', label: 'Orders' },
  {
    label: '💰 Financial',
    submenu: [
      { href: '/admin/accounts', label: 'Accounts' },
      { href: '/admin/accounts/reports', label: 'Reports & Analysis' },
      { href: '/admin/accounts/reconciliation', label: 'Bank Reconciliation' },
      { href: '/admin/financial-audit', label: 'Audit Trail' },
    ],
  },
  { href: '/admin/login-logs', label: 'Admin login activity' },
  { href: '/admin/customer-login-logs', label: 'Customer login activity' },
  { 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' },
];

export default function AdminMenu() {
  const [open, setOpen] = useState(false);
  const [expandedSubmenu, setExpandedSubmenu] = useState<string | null>(null);
  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);
  }, []);

  const handleSubmenuToggle = (label: string) => {
    setExpandedSubmenu(expandedSubmenu === label ? null : label);
  };

  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-56 border border-line bg-paper shadow-sm max-h-96 overflow-y-auto">
          {ADMIN_LINKS.map((item) => (
            <div key={item.label}>
              {item.submenu ? (
                <>
                  <button
                    onClick={() => handleSubmenuToggle(item.label)}
                    className="w-full flex items-center justify-between px-4 py-3 text-sm hover:bg-surface text-left font-medium"
                  >
                    {item.label}
                    <span className={`inline-block transition-transform text-xs ${expandedSubmenu === item.label ? 'rotate-180' : ''}`}>
                      ▾
                    </span>
                  </button>
                  {expandedSubmenu === item.label && (
                    <div className="bg-surface/50">
                      {item.submenu.map((subitem) => (
                        <Link
                          key={subitem.href}
                          href={subitem.href!}
                          onClick={() => setOpen(false)}
                          className="block px-6 py-2 text-xs text-muted hover:text-ink hover:bg-surface"
                        >
                          {subitem.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </>
              ) : (
                <Link
                  href={item.href!}
                  onClick={() => setOpen(false)}
                  className="block px-4 py-3 text-sm hover:bg-surface"
                >
                  {item.label}
                </Link>
              )}
            </div>
          ))}
          <form action={logoutAdmin}>
            <button type="submit" className="w-full block px-4 py-3 text-left text-sm hover:bg-surface border-t border-line">
              Log out
            </button>
          </form>
        </div>
      )}
    </div>
  );
}
