import { useNavigate, Link } from '@tanstack/react-router';
import { LogOut, UserCircle, Building, Sparkles, ChevronUp, FileText } from 'lucide-react';
import { useProfile } from '../../profile/hooks/useProfile';
import { tokenStorage } from '@/infrastructure/storage/LocalTokenStorage';
import { authApi } from '@/infrastructure/http/api/auth';
import { useState, useRef, useEffect } from 'react';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useAuthenticatedUser } from '@/features/auth/hooks/useAuthenticatedUser';
import { AuthOrigin } from '@archer/domain';

/**
 * DashboardUserProfile Component
 *
 * Displays authenticated user's profile in the sidebar bottom.
 * Click opens a popover menu above with Profile, Company, and Logout.
 */
export function DashboardUserProfile() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { data: profile, isLoading } = useProfile();
  // Shopify-authenticated users are billed by Shopify, not by TWWIM, so profile
  // + company edit screens don't apply. Hide the edit surface for them; every
  // other origin (TWWIM / WP / future channels) retains the full menu.
  const authed = useAuthenticatedUser();
  const canEditAccount = authed?.authOrigin !== AuthOrigin.SHOPIFY;
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleLogout = async (): Promise<void> => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('Logout API call failed:', error);
    } finally {
      tokenStorage.removeTokens();
      navigate({ to: '/login' });
    }
  };

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

  if (isLoading || !profile) {
    return (
      <div className="flex items-center gap-3 p-3 animate-pulse">
        <div className="w-10 h-10 rounded-full bg-slate-700"></div>
        <div className="flex-1 min-w-0">
          <div className="h-4 bg-slate-700 rounded w-24 mb-2"></div>
          <div className="h-3 bg-slate-700 rounded w-32"></div>
        </div>
      </div>
    );
  }

  return (
    <div ref={containerRef} className="relative">
      {open && (
        <div className="absolute bottom-full left-0 right-0 mb-2 bg-slate-800 border border-sidebar-border rounded-lg shadow-lg overflow-hidden">
          {canEditAccount && (
            <>
              <Link
                to="/dashboard/profile"
                onClick={() => setOpen(false)}
                className="flex items-center gap-3 px-4 py-3 text-slate-50 hover:bg-primary/20 hover:text-primary transition-colors"
                activeProps={{ className: 'bg-primary/20 text-primary font-medium' }}
              >
                <UserCircle className="h-5 w-5" />
                <span className="text-sm font-medium">{t('nav.profile')}</span>
              </Link>
              <Link
                to="/dashboard/company"
                onClick={() => setOpen(false)}
                data-testid="sidebar-link-company"
                className="flex items-center gap-3 px-4 py-3 text-slate-50 hover:bg-primary/20 hover:text-primary transition-colors"
                activeProps={{ className: 'bg-primary/20 text-primary font-medium' }}
              >
                {profile.isPersonal ? <Sparkles className="h-5 w-5" /> : <Building className="h-5 w-5" />}
                <span className="text-sm font-medium">
                  {profile.isPersonal ? t('nav.convertToBusiness') : t('nav.company')}
                </span>
              </Link>
              <Link
                to="/dashboard/documents"
                onClick={() => setOpen(false)}
                className="flex items-center gap-3 px-4 py-3 text-slate-50 hover:bg-primary/20 hover:text-primary transition-colors"
                activeProps={{ className: 'bg-primary/20 text-primary font-medium' }}
              >
                <FileText className="h-5 w-5" />
                <span className="text-sm font-medium">{t('nav.documents')}</span>
              </Link>
              <div className="border-t border-sidebar-border" />
            </>
          )}
          <button
            onClick={handleLogout}
            className="w-full flex items-center gap-3 px-4 py-3 text-slate-400 hover:bg-red-500/10 hover:text-red-400 transition-colors"
          >
            <LogOut className="h-5 w-5" />
            <span className="text-sm font-medium">{t('nav.logout')}</span>
          </button>
        </div>
      )}

      <button
        type="button"
        data-testid="sidebar-user-profile"
        onClick={() => setOpen(!open)}
        className="w-full flex items-center gap-3 p-3 hover:bg-slate-700/50 rounded-lg transition-colors text-left"
      >
        <div className="w-10 h-10 rounded-full bg-primary text-white flex items-center justify-center font-semibold text-sm flex-shrink-0">
          {profile.initials}
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-slate-50 truncate">{profile.displayName}</p>
          <p className="text-xs text-slate-400 truncate">{profile.email}</p>
        </div>
        <ChevronUp className={`w-4 h-4 text-slate-400 transition-transform ${open ? '' : 'rotate-180'}`} />
      </button>
    </div>
  );
}
