"use client";

import React from "react";
import { useSession, signOut } from "next-auth/react";
import { Button } from "@/components/ui/Button";
import Image from "next/image";

export function UserProfile() {
  const { data: session, status } = useSession();

  if (status === "loading") {
    return (
      <div className="flex items-center space-x-2">
        <div className="animate-pulse">
          <div className="h-8 w-8 bg-gray-300 rounded-full"></div>
        </div>
        <div className="animate-pulse">
          <div className="h-4 w-20 bg-gray-300 rounded"></div>
        </div>
      </div>
    );
  }

  if (status === "unauthenticated") {
    return (
      <div className="flex items-center space-x-2">
        <Button
          onClick={() => (window.location.href = "/auth/signin")}
          variant="outline"
          size="sm"
        >
          로그인
        </Button>
      </div>
    );
  }

  if (!session?.user) {
    return null;
  }

  const handleSignOut = () => {
    signOut({
      callbackUrl: "/",
      redirect: true,
    });
  };

  return (
    <div className="flex items-center space-x-3">
      {/* 사용자 아바타 */}
      <div className="flex-shrink-0">
        {session.user.image ? (
          <Image
            src={session.user.image}
            alt={session.user.name || "사용자"}
            width={32}
            height={32}
            className="rounded-full"
            onError={(e) => {
              // 이미지 로드 실패시 기본 아바타로 변경
              const target = e.target as HTMLImageElement;
              target.style.display = "none";
            }}
          />
        ) : (
          <div className="h-8 w-8 bg-blue-500 rounded-full flex items-center justify-center">
            <span className="text-white text-sm font-medium">
              {session.user.name?.charAt(0) ||
                session.user.email?.charAt(0) ||
                "U"}
            </span>
          </div>
        )}
      </div>

      {/* 사용자 정보 */}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-gray-900 truncate">
          {session.user.name || session.user.email}
        </p>
        {session.user.name && session.user.email && (
          <p className="text-xs text-gray-500 truncate">{session.user.email}</p>
        )}
      </div>

      {/* 로그아웃 버튼 */}
      <Button
        onClick={handleSignOut}
        variant="ghost"
        size="sm"
        className="text-gray-600 hover:text-gray-900"
      >
        로그아웃
      </Button>
    </div>
  );
}
