import { useState, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Trash2, Users, Search } from "lucide-react";

import ConfirmDialog from "@/components/pc/admin/common/ConfirmDialog";
import SongSearchDialog from "./SongSearchDialog";

/**
 * 세트리스트 섹션
 * - 곡 추가/삭제
 * - 곡명, 앨범명, 참여 멤버
 * - 순서 자동 부여
 */
function SetlistSection({ setlist, setSetlist, members, selectedMemberIds, albums }) {
  const containerRef = useRef(null);
  const [nextId, setNextId] = useState(() => {
    const maxId = setlist.reduce((max, s) => Math.max(max, s.id || 0), 0);
    return maxId + 1;
  });

  // 삭제 확인 다이얼로그
  const [deleteConfirm, setDeleteConfirm] = useState({
    isOpen: false,
    songId: null,
    songName: null,
  });

  // 곡 검색 다이얼로그
  const [songSearchOpen, setSongSearchOpen] = useState(false);

  // 직접 입력 곡 추가
  const addSong = () => {
    const newSong = {
      id: nextId,
      songName: "",
      albumName: "",
      memberIds: [...selectedMemberIds],
    };
    setSetlist((prev) => [...prev, newSong]);
    setNextId(nextId + 1);

    setTimeout(() => {
      if (containerRef.current) {
        const lastChild = containerRef.current.lastElementChild;
        if (lastChild) {
          lastChild.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    }, 100);
  };

  // 검색에서 선택한 곡 추가
  const addSongsFromSearch = (songs) => {
    let id = nextId;
    const newSongs = songs.map((song) => ({
      id: id++,
      songName: song.songName,
      albumName: song.albumName,
      memberIds: [...selectedMemberIds],
    }));
    setSetlist((prev) => [...prev, ...newSongs]);
    setNextId(id);

    setTimeout(() => {
      if (containerRef.current) {
        const lastChild = containerRef.current.lastElementChild;
        if (lastChild) {
          lastChild.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    }, 100);
  };

  // 곡 삭제 시도
  const handleRemoveSong = (id) => {
    if (setlist.length <= 1) return;

    const song = setlist.find((s) => s.id === id);

    if (song && (song.songName || song.albumName)) {
      setDeleteConfirm({
        isOpen: true,
        songId: id,
        songName: song.songName || "제목 없음",
      });
    } else {
      removeSong(id);
    }
  };

  // 곡 삭제 실행
  const removeSong = (id) => {
    setSetlist((prev) => prev.filter((s) => s.id !== id));
  };

  // 삭제 확인
  const handleConfirmDelete = () => {
    if (deleteConfirm.songId !== null) {
      removeSong(deleteConfirm.songId);
    }
    setDeleteConfirm({ isOpen: false, songId: null, songName: null });
  };

  // 곡 필드 업데이트
  const updateSong = (id, field, value) => {
    setSetlist((prev) =>
      prev.map((s) => (s.id === id ? { ...s, [field]: value } : s))
    );
  };

  // 곡별 멤버 토글
  const toggleSongMember = (songId, memberId) => {
    setSetlist((prev) =>
      prev.map((s) => {
        if (s.id !== songId) return s;
        const has = s.memberIds.includes(memberId);
        return {
          ...s,
          memberIds: has
            ? s.memberIds.filter((id) => id !== memberId)
            : [...s.memberIds, memberId],
        };
      })
    );
  };

  // 곡별 멤버 전체 선택/해제
  const toggleAllSongMembers = (songId) => {
    setSetlist((prev) =>
      prev.map((s) => {
        if (s.id !== songId) return s;
        const allSelected = members.every((m) => s.memberIds.includes(m.id));
        return {
          ...s,
          memberIds: allSelected ? [] : members.map((m) => m.id),
        };
      })
    );
  };

  return (
    <>
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() =>
          setDeleteConfirm({ isOpen: false, songId: null, songName: null })
        }
        onConfirm={handleConfirmDelete}
        title="곡 삭제"
        message={
          <p>
            <span className="font-medium">{deleteConfirm.songName}</span>
            을(를) 삭제하시겠습니까?
          </p>
        }
        confirmText="삭제"
        cancelText="취소"
      />

      <SongSearchDialog
        isOpen={songSearchOpen}
        onClose={() => setSongSearchOpen(false)}
        onSelect={addSongsFromSearch}
        albums={albums}
      />

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
        <h2 className="text-lg font-bold text-gray-900 mb-6">세트리스트</h2>

        <div ref={containerRef} className="flex flex-col gap-4">
          <AnimatePresence initial={false}>
            {setlist.map((song, index) => (
              <motion.div
                key={song.id}
                initial={{ opacity: 0, scale: 0.98, y: -8 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.98, y: -8 }}
                transition={{ duration: 0.15, ease: "easeOut" }}
              >
                <div className="p-4 bg-gray-50 rounded-xl space-y-3">
                  {/* 헤더 */}
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700">
                      {index + 1}번 곡
                    </span>
                    {setlist.length > 1 && (
                      <button
                        type="button"
                        onClick={() => handleRemoveSong(song.id)}
                        className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                      >
                        <Trash2 size={16} />
                      </button>
                    )}
                  </div>

                  {/* 곡명 & 앨범명 */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs text-gray-500 mb-1">
                        곡명 *
                      </label>
                      <input
                        type="text"
                        value={song.songName}
                        onChange={(e) =>
                          updateSong(song.id, "songName", e.target.value)
                        }
                        placeholder="예: Feel Good"
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-500 mb-1">
                        앨범명 (선택)
                      </label>
                      <input
                        type="text"
                        value={song.albumName}
                        onChange={(e) =>
                          updateSong(song.id, "albumName", e.target.value)
                        }
                        placeholder="예: Unlock My World"
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                      />
                    </div>
                  </div>

                  {/* 참여 멤버 */}
                  <div>
                    <label className="flex items-center gap-2 text-xs text-gray-500 mb-2">
                      <Users size={14} />
                      참여 멤버
                    </label>
                    <div className="flex flex-wrap gap-2">
                      {/* 전체 선택 버튼 */}
                      <button
                        type="button"
                        onClick={() => toggleAllSongMembers(song.id)}
                        className={`flex items-center justify-center px-4 py-1.5 rounded-full border text-sm transition-colors ${
                          members.every((m) =>
                            song.memberIds.includes(m.id)
                          )
                            ? "border-primary bg-primary text-white"
                            : "border-gray-200 text-gray-500 hover:border-gray-300"
                        }`}
                      >
                        {members.every((m) =>
                          song.memberIds.includes(m.id)
                        )
                          ? "전체 해제"
                          : "전체 선택"}
                      </button>

                      {members.map((member) => {
                        const isSelected = song.memberIds.includes(member.id);
                        return (
                          <button
                            key={member.id}
                            type="button"
                            onClick={() =>
                              toggleSongMember(song.id, member.id)
                            }
                            className={`flex items-center gap-2 pr-3.5 pl-1.5 py-1.5 rounded-full border transition-colors ${
                              isSelected
                                ? "border-primary"
                                : "border-gray-200"
                            }`}
                          >
                            <div className="w-9 h-9 rounded-full overflow-hidden bg-gray-200 flex-shrink-0">
                              {member.image_url ? (
                                <img
                                  src={member.image_url}
                                  alt={member.name}
                                  className="w-full h-full object-cover"
                                />
                              ) : (
                                <div className="w-full h-full bg-gray-300" />
                              )}
                            </div>
                            <span className="text-sm text-gray-700">
                              {member.name}
                            </span>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>

        <div className="flex gap-2 mt-4">
          <button
            type="button"
            onClick={() => setSongSearchOpen(true)}
            className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-primary/10 rounded-lg text-sm text-primary hover:bg-primary/20 transition-colors"
          >
            <Search size={14} />
            곡 검색
          </button>
          <button
            type="button"
            onClick={addSong}
            className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-gray-100 rounded-lg text-sm text-gray-600 hover:bg-gray-200 transition-colors"
          >
            <Plus size={14} />
            직접 입력
          </button>
        </div>

        <p className="text-xs text-gray-400 mt-3">
          곡 추가 시 콘서트 참여 멤버가 자동으로 선택됩니다. 솔로/유닛 곡은
          개별 조정하세요.
        </p>
      </div>
    </>
  );
}

export default SetlistSection;
