'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Globe, LogIn, LogOut, User } from 'lucide-react';
import { useTranslations } from 'next-intl';

import { useAuth } from '@/components/auth/AuthProvider';
import { useAuthStore } from '@/lib/store/auth';
import { authApi, clearToken } from '@/lib/auth';

/**
 * Feature 054 — US12 (C5). Account parity inside the mobile burger drawer:
 * profile link, language switch, and logout (or a login link when signed out).
 */
export function DrawerAccountSection({ locale, onNavigate }: { locale: string; onNavigate?: () => void }) {
  const t = useTranslations('account.menu');
  const tNav = useTranslations('nav');
  const { user, status } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const reset = useAuthStore((s) => s.reset);
  const [logoutLoading, setLogoutLoading] = useState(false);

  const otherLocale = locale === 'ar' ? 'en' : 'ar';
  const switchLang = () => {
    const switched = pathname.replace(/^\/[a-z]{2}(\/|$)/, `/${otherLocale}$1`);
    onNavigate?.();
    router.push(switched + (typeof window !== 'undefined' ? window.location.search : ''));
  };

  const onLogout = async () => {
    if (logoutLoading) return;
    setLogoutLoading(true);
    try {
      await authApi.logout();
    } catch {
      // clear local state even if the network call fails
    }
    await clearToken();
    reset();
    onNavigate?.();
    router.push(`/${locale}`);
    router.refresh();
  };

  return (
    <div className="mt-auto border-t border-neutral-200 pt-3">
      {status === 'authenticated' && user ? (
        <div className="px-3 py-2">
          <p className="flex items-center gap-2 text-sm font-medium text-neutral-900">
            <User aria-hidden="true" className="h-4 w-4" />
            {user.name}
          </p>
          {user.phone_e164 ? <p className="ms-6 text-xs text-neutral-500">{user.phone_e164}</p> : null}
        </div>
      ) : null}

      <nav className="flex flex-col gap-1">
        {status === 'authenticated' && user ? (
          <Link
            href={`/${locale}/me/profile`}
            onClick={onNavigate}
            className="rounded px-3 py-2 text-sm font-medium hover:bg-neutral-100"
          >
            {t('view_profile')}
          </Link>
        ) : (
          <Link
            href={`/${locale}/auth/login`}
            onClick={onNavigate}
            className="flex items-center gap-2 rounded px-3 py-2 text-sm font-medium hover:bg-neutral-100"
          >
            <LogIn aria-hidden="true" className="h-4 w-4" />
            {tNav('login')}
          </Link>
        )}

        <button
          type="button"
          onClick={switchLang}
          className="flex items-center gap-2 rounded px-3 py-2 text-start text-sm font-medium hover:bg-neutral-100"
        >
          <Globe aria-hidden="true" className="h-4 w-4" />
          {t('language_switch')}
        </button>

        {status === 'authenticated' && user ? (
          <button
            type="button"
            onClick={onLogout}
            disabled={logoutLoading}
            aria-busy={logoutLoading}
            className="flex items-center gap-2 rounded px-3 py-2 text-start text-sm font-medium text-danger hover:bg-danger/10 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <LogOut aria-hidden="true" className="h-4 w-4" />
            {logoutLoading ? '…' : t('logout')}
          </button>
        ) : null}
      </nav>
    </div>
  );
}
