import { useState } from 'react';
import { createPortal } from 'react-dom';
import { User, LogOut, X } from 'lucide-react';
import { comms } from '@/communication';

interface UserInfoButtonProps {
  userName?: string;
  userDept?: string;
}

export function UserInfoButton({ userName, userDept }: UserInfoButtonProps) {
  const [showLogoutDialog, setShowLogoutDialog] = useState(false);
  const [processing, setProcessing] = useState(false);

  const handleLogout = async () => {
    setProcessing(true);
    try {
      const result = await comms.logout();
      if (result.Success) {
        // 로그아웃 성공 - 페이지 새로고침으로 로그인 화면 표시
        window.location.reload();
      } else {
        alert(result.Message || '로그아웃에 실패했습니다.');
      }
    } catch (error) {
      console.error('로그아웃 오류:', error);
      alert('서버 연결에 실패했습니다.');
    } finally {
      setProcessing(false);
      setShowLogoutDialog(false);
    }
  };

  if (!userName) return null;

  return (
    <>
      {/* 사용자 정보 버튼 */}
      <button
        onClick={() => setShowLogoutDialog(true)}
        className="flex items-center space-x-2 text-white/70 hover:text-white transition-colors cursor-pointer"
      >
        <User className="w-4 h-4" />
        <span>{userName}</span>
        {userDept && <span className="text-white/50">({userDept})</span>}
      </button>

      {/* 로그아웃 다이얼로그 - Portal로 body에 직접 렌더링 */}
      {showLogoutDialog && createPortal(
        <div
          className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 backdrop-blur-sm"
          onClick={() => setShowLogoutDialog(false)}
        >
          <div
            className="glass-effect rounded-2xl w-full max-w-sm animate-slide-up mx-4"
            onClick={(e) => e.stopPropagation()}
          >
            {/* 헤더 */}
            <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-white flex items-center">
                <LogOut className="w-5 h-5 mr-2" />
                로그아웃
              </h2>
              <button
                onClick={() => setShowLogoutDialog(false)}
                className="text-white/70 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* 내용 */}
            <div className="p-6">
              <div className="text-center mb-6">
                <div className="w-16 h-16 bg-white/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <User className="w-8 h-8 text-white/70" />
                </div>
                <p className="text-white font-medium">{userName}</p>
                {userDept && <p className="text-white/50 text-sm">{userDept}</p>}
              </div>
              <p className="text-white/70 text-center text-sm">
                로그아웃 하시겠습니까?
              </p>
            </div>

            {/* 푸터 */}
            <div className="px-6 py-4 border-t border-white/10 flex justify-center">
              <button
                onClick={handleLogout}
                disabled={processing}
                className="bg-danger-500 hover:bg-danger-600 text-white px-6 py-2 rounded-lg transition-colors flex items-center disabled:opacity-50"
              >
                {processing ? (
                  <span className="animate-spin mr-2">⏳</span>
                ) : (
                  <LogOut className="w-4 h-4 mr-2" />
                )}
                로그아웃
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}
    </>
  );
}
