'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { logoutCustomer } from '@/app/account/actions';

type AccountMenuProps = {
  customer: { name: string | null; email: string } | null;
};

export default function AccountMenu({ customer }: AccountMenuProps) {
  const [mounted, setMounted] = useState(false);
  const [open, setOpen] = useState(false);
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

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

  if (!customer) {
    return (
      <Link href="/account/login" className="tag-label hover:text-ink">
        Login
      </Link>
    );
  }

  if (!mounted) return null;

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((o) => !o)}
        aria-expanded={open}
        className="tag-label flex items-center gap-1 hover:text-ink"
      >
        {customer.name ?? 'Account'}
        <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">
          <Link href="/account" onClick={() => setOpen(false)} className="block px-4 py-3 text-sm hover:bg-surface">
            My account
          </Link>
          <button
            onClick={() => setShowLogoutConfirm(true)}
            className="block w-full px-4 py-3 text-left text-sm hover:bg-surface"
          >
            Log out
          </button>
        </div>
      )}

      {mounted && showLogoutConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-96 border border-line bg-paper p-6 shadow-lg">
            <h2 className="font-display text-lg">Log out?</h2>
            <p className="mt-3 text-sm text-muted">
              Your cart will be saved. You&apos;ll need to log in again to complete your order.
            </p>
            <div className="mt-6 flex gap-3">
              <button
                onClick={() => setShowLogoutConfirm(false)}
                className="flex-1 border border-line px-4 py-2 text-sm hover:bg-surface"
              >
                Cancel
              </button>
              <form action={logoutCustomer} className="flex-1">
                <button type="submit" className="w-full bg-clay px-4 py-2 text-sm font-medium text-paper hover:bg-clay-dark">
                  Log out
                </button>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
