import { useState, useMemo } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "framer-motion";
import { X, Search, Music, Disc3 } from "lucide-react";

/**
 * 곡 검색 다이얼로그
 * - 앨범 목록에서 곡을 검색/선택
 * - 다중 선택 지원
 *
 * @param {Object} props
 * @param {boolean} props.isOpen
 * @param {Function} props.onClose
 * @param {Function} props.onSelect - 선택된 곡 배열 반환 [{ songName, albumName }]
 * @param {Array} props.albums - getAlbums() 결과
 */
function SongSearchDialog({ isOpen, onClose, onSelect, albums }) {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedTracks, setSelectedTracks] = useState([]);

  // 전체 트랙 목록 (앨범 정보 포함)
  const allTracks = useMemo(() => {
    if (!albums || albums.length === 0) return [];
    return albums.flatMap((album) =>
      (album.tracks || []).map((track) => ({
        id: `${album.id}-${track.id}`,
        songName: track.title,
        albumName: album.title,
        albumCover: album.cover_thumb_url,
        isTitleTrack: track.is_title_track,
        trackNumber: track.track_number,
      }))
    );
  }, [albums]);

  // 검색 필터링
  const filteredTracks = useMemo(() => {
    if (!searchQuery.trim()) return allTracks;
    const query = searchQuery.toLowerCase();
    return allTracks.filter(
      (track) =>
        track.songName.toLowerCase().includes(query) ||
        track.albumName.toLowerCase().includes(query)
    );
  }, [allTracks, searchQuery]);

  // 앨범별 그룹핑
  const groupedTracks = useMemo(() => {
    const groups = {};
    filteredTracks.forEach((track) => {
      if (!groups[track.albumName]) {
        groups[track.albumName] = {
          albumName: track.albumName,
          albumCover: track.albumCover,
          tracks: [],
        };
      }
      groups[track.albumName].tracks.push(track);
    });
    return Object.values(groups);
  }, [filteredTracks]);

  // 트랙 선택 토글
  const toggleTrack = (track) => {
    setSelectedTracks((prev) => {
      const exists = prev.find((t) => t.id === track.id);
      if (exists) {
        return prev.filter((t) => t.id !== track.id);
      }
      return [...prev, track];
    });
  };

  // 선택 순서 매핑 (trackId → 순번)
  const selectionOrder = useMemo(() => {
    const m = new Map();
    selectedTracks.forEach((t, i) => m.set(t.id, i + 1));
    return m;
  }, [selectedTracks]);

  const isSelected = (trackId) => selectionOrder.has(trackId);

  // 확인
  const handleConfirm = () => {
    onSelect(
      selectedTracks.map((t) => ({
        songName: t.songName,
        albumName: t.albumName,
      }))
    );
    handleClose();
  };

  // 닫기
  const handleClose = () => {
    setSearchQuery("");
    setSelectedTracks([]);
    onClose();
  };

  return createPortal(
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
          onClick={handleClose}
        >
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            className="bg-white rounded-2xl p-6 max-w-lg w-full mx-4 shadow-xl flex flex-col h-[60vh] min-h-[400px]"
            onClick={(e) => e.stopPropagation()}
          >
            {/* 헤더 */}
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900">곡 검색</h3>
              <button
                type="button"
                onClick={handleClose}
                className="text-gray-400 hover:text-gray-600"
              >
                <X size={20} />
              </button>
            </div>

            {/* 검색 입력 */}
            <div className="relative mb-4">
              <Search
                size={18}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
              />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="곡명 또는 앨범명으로 검색"
                className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                autoFocus
              />
            </div>

            {/* 선택 카운트 */}
            {selectedTracks.length > 0 && (
              <div className="mb-3 text-sm text-primary font-medium">
                {selectedTracks.length}곡 선택됨
              </div>
            )}

            {/* 결과 목록 */}
            <div className="flex-1 overflow-y-auto min-h-0">
              {groupedTracks.length > 0 ? (
                <div className="space-y-4">
                  {groupedTracks.map((group) => (
                    <div key={group.albumName}>
                      {/* 앨범 헤더 */}
                      <div className="flex items-center gap-2 mb-2 sticky top-0 bg-white py-1">
                        {group.albumCover ? (
                          <img
                            src={group.albumCover}
                            alt={group.albumName}
                            className="w-8 h-8 rounded-md object-cover"
                          />
                        ) : (
                          <div className="w-8 h-8 rounded-md bg-gray-100 flex items-center justify-center">
                            <Disc3 size={16} className="text-gray-400" />
                          </div>
                        )}
                        <span className="text-sm font-medium text-gray-700">
                          {group.albumName}
                        </span>
                      </div>

                      {/* 트랙 목록 */}
                      <div className="space-y-1">
                        {group.tracks.map((track) => {
                          const order = selectionOrder.get(track.id);
                          const selected = order !== undefined;
                          return (
                            <button
                              key={track.id}
                              type="button"
                              onClick={() => toggleTrack(track)}
                              className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors ${
                                selected ? "bg-primary/10" : "hover:bg-gray-50"
                              }`}
                            >
                              <div
                                className={`w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 text-[11px] font-bold leading-none transition-colors ${
                                  selected
                                    ? "bg-primary text-white"
                                    : "border border-gray-300 text-transparent"
                                }`}
                              >
                                <span className="translate-y-[0.5px]">{order ?? ""}</span>
                              </div>
                              <span className="text-sm text-gray-400 w-5 text-right flex-shrink-0">
                                {track.trackNumber}
                              </span>
                              <span className="text-sm text-gray-900 flex-1 truncate">
                                {track.songName}
                              </span>
                              {!!track.isTitleTrack && (
                                <span className="text-[10px] px-1.5 py-0.5 bg-primary/10 text-primary rounded font-medium flex-shrink-0">
                                  타이틀
                                </span>
                              )}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12 text-gray-500">
                  <Music size={32} className="mx-auto mb-2 text-gray-300" />
                  <p className="text-sm">
                    {searchQuery
                      ? "검색 결과가 없습니다"
                      : "등록된 곡이 없습니다"}
                  </p>
                </div>
              )}
            </div>

            {/* 하단 버튼 */}
            <div className="flex items-center justify-end gap-3 mt-4 pt-4 border-t border-gray-100">
              <button
                type="button"
                onClick={handleClose}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleConfirm}
                disabled={selectedTracks.length === 0}
                className="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors disabled:opacity-50"
              >
                {selectedTracks.length > 0
                  ? `${selectedTracks.length}곡 추가`
                  : "추가"}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>,
    document.body
  );
}

export default SongSearchDialog;
