"use client";
import { Search, ListMusic, LogIn, LogOut, Home } from "lucide-react";
import { signIn, signOut, useSession } from "next-auth/react";
import { useState } from "react";

interface TopNavProps {
  onSearch: (query: string) => void;
  onHome: () => void;
  selectedServer: any; // 🌟 추가: 선택된 서버 정보
}

export default function TopNav({ onSearch, onHome, selectedServer }: TopNavProps) {
  const { data: session, status } = useSession();
  const [term, setTerm] = useState("");

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && term.trim()) {
      onSearch(term);
    }
  };

  // 🌟 홈 버튼 클릭 시 검색어 초기화 로직 추가
  const handleHomeClick = () => {
    setTerm(""); // 검색창 비우기
    onHome();    // 원래 홈 기능 실행
  };

  return (
    <nav className="h-16 flex-shrink-0 bg-black border-b border-neutral-800 flex items-center justify-between px-6 z-20">
      {/* 1. 왼쪽: 로고 */}
      <div className="flex items-center gap-2 text-xl font-bold text-white w-52">
        <ListMusic className="text-green-500" />
        <span>MusicBot</span>
      </div>

      {/* 2. 가운데: 검색창 & 홈 버튼 */}
      <div className="flex-1 max-w-2xl px-4 flex items-center gap-4">
        <button 
          onClick={handleHomeClick} // 🌟 수정된 핸들러 연결
          className="p-2 hover:bg-neutral-800 rounded-full transition-colors cursor-pointer text-neutral-400 hover:text-white"
          title="홈으로"
        >
          <Home size={22} />
        </button>

        <div className="relative w-full">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" size={18} />
          <input 
            type="text" 
            value={term}
            onChange={(e) => setTerm(e.target.value)}
            onKeyDown={handleKeyDown}
            disabled={!selectedServer} // 🌟 서버 미선택 시 입력창 비활성화 (선택 사항)
            placeholder={selectedServer ? "노래 검색 후 엔터를 누르세요" : "서버를 먼저 선택해주세요"} 
            className={`w-full h-10 pl-10 pr-4 rounded-full bg-neutral-800 border border-neutral-700 text-sm text-white focus:outline-none focus:ring-2 focus:ring-white/30 transition-all ${!selectedServer ? 'opacity-50 cursor-not-allowed' : 'opacity-100'}`}
          />
        </div>
      </div>

      {/* 3. 오른쪽: 유저 프로필 영역 (기존과 동일) */}
      <div className="flex items-center justify-end w-auto min-w-[13rem]">
        {status === "loading" ? (
          <div className="text-sm text-neutral-400">로딩 중...</div>
        ) : status === "authenticated" && session?.user ? (
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 bg-neutral-800/80 pr-4 pl-1 py-1 rounded-full border border-neutral-700 shadow-sm cursor-default">
              <img src={session.user.image || ""} alt="Profile" className="w-7 h-7 rounded-full" />
              <span className="text-sm font-medium text-white whitespace-nowrap">{session.user.name}</span>
            </div>
            <button onClick={() => signOut()} className="cursor-pointer text-neutral-400 hover:text-red-400 p-2 rounded-full hover:bg-neutral-800 transition-colors">
              <LogOut size={18} />
            </button>
          </div>
        ) : (
          <button onClick={() => signIn("discord")} className="cursor-pointer flex items-center gap-2 bg-[#5865F2] hover:bg-[#4752C4] text-white px-5 py-2 rounded-full font-medium transition-colors text-sm shadow-md">
            <LogIn size={16} /> Discord 로그인
          </button>
        )}
      </div>
    </nav>
  );
}