import { useState, useRef, useEffect } from "react";
import { Reorder } from "framer-motion";
import { Plus, Trash2, Users, Search, Copy, ChevronDown, GripVertical } from "lucide-react";

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

/**
 * 세트리스트 섹션 (회차별 탭)
 * - 회차별로 독립적인 세트리스트
 * - 다른 회차에서 복사 기능
 */
function SetlistSection({ rounds, setlists, setSetlists, members, selectedMemberIds, albums }) {
  const containerRef = useRef(null);
  const [activeRoundId, setActiveRoundId] = useState(rounds[0]?.id || 1);

  // 현재 활성 회차의 세트리스트
  const setlist = setlists[activeRoundId] || [];

  // 활성 회차가 삭제되면 첫 번째 회차로 전환
  useEffect(() => {
    if (!rounds.find((r) => r.id === activeRoundId) && rounds.length > 0) {
      setActiveRoundId(rounds[0].id);
    }
  }, [rounds, activeRoundId]);

  // 다음 ID 계산
  const getNextId = () => {
    return Object.values(setlists).flat().reduce((max, s) => Math.max(max, s.id || 0), 0) + 1;
  };

  // 현재 회차의 세트리스트 업데이트
  const updateCurrentSetlist = (updater) => {
    setSetlists((prev) => ({
      ...prev,
      [activeRoundId]: typeof updater === 'function' ? updater(prev[activeRoundId] || []) : updater,
    }));
  };


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

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

  // 복사 소스 선택
  const [copyFrom, setCopyFrom] = useState(null);

  // 회차 드롭다운 열림 상태
  const [roundDropdownOpen, setRoundDropdownOpen] = useState(false);
  const roundDropdownRef = useRef(null);

  // 드롭다운 외부 클릭 닫기
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (roundDropdownRef.current && !roundDropdownRef.current.contains(e.target)) {
        setRoundDropdownOpen(false);
      }
    };
    if (roundDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [roundDropdownOpen]);

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

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

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

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

  // 다른 회차에서 복사
  const copyFromRound = (sourceRoundId) => {
    const source = setlists[sourceRoundId] || [];
    let id = getNextId();
    const copied = source.map((s) => ({
      ...s,
      id: id++,
      memberIds: [...s.memberIds],
    }));
    updateCurrentSetlist(copied);
    setCopyFrom(null);
  };

  // 곡 삭제 시도
  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) => {
    updateCurrentSetlist((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) => {
    updateCurrentSetlist((prev) =>
      prev.map((s) => (s.id === id ? { ...s, [field]: value } : s))
    );
  };

  // 곡별 멤버 토글
  const toggleSongMember = (songId, memberId) => {
    updateCurrentSetlist((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) => {
    updateCurrentSetlist((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),
        };
      })
    );
  };

  // 현재 활성 회차의 인덱스
  const activeRoundIndex = rounds.findIndex((r) => r.id === activeRoundId);

  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">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-bold text-gray-900">세트리스트</h2>
          {/* 다른 회차에서 복사 */}
          {rounds.length > 1 && (
            <div className="relative">
              <button
                type="button"
                onClick={() => setCopyFrom(copyFrom ? null : true)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <Copy size={12} />
                다른 회차에서 복사
              </button>
              {copyFrom && (
                <div className="absolute right-0 top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-10 py-1 min-w-[120px]">
                  {rounds
                    .filter((r) => r.id !== activeRoundId)
                    .map((r, i) => {
                      const roundIdx = rounds.indexOf(r);
                      return (
                        <button
                          key={r.id}
                          type="button"
                          onClick={() => copyFromRound(r.id)}
                          className="w-full px-4 py-2 text-sm text-left hover:bg-gray-50 transition-colors"
                        >
                          {roundIdx + 1}회차
                        </button>
                      );
                    })}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 회차 선택 커스텀 드롭다운 (2개 이상일 때만) */}
        {rounds.length > 1 && (
          <div className="relative mb-4" ref={roundDropdownRef}>
            <button
              type="button"
              onClick={() => setRoundDropdownOpen(!roundDropdownOpen)}
              className="flex items-center justify-between gap-2 w-48 px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white hover:border-gray-300 transition-colors"
            >
              <span className="truncate">
                {activeRoundIndex + 1}회차
                {rounds[activeRoundIndex]?.date ? ` (${rounds[activeRoundIndex].date})` : ''}
              </span>
              <ChevronDown size={14} className={`text-gray-400 transition-transform ${roundDropdownOpen ? 'rotate-180' : ''}`} />
            </button>
            {roundDropdownOpen && (
              <div className="absolute left-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded-lg shadow-lg z-10 py-1">
                {rounds.map((round, index) => (
                  <button
                    key={round.id}
                    type="button"
                    onClick={() => {
                      setActiveRoundId(round.id);
                      setRoundDropdownOpen(false);
                    }}
                    className={`w-full px-3 py-2 text-sm text-left transition-colors ${
                      round.id === activeRoundId
                        ? 'bg-primary/10 text-primary font-medium'
                        : 'hover:bg-gray-50 text-gray-700'
                    }`}
                  >
                    {index + 1}회차{round.date ? ` (${round.date})` : ''}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        <Reorder.Group
          axis="y"
          values={setlist}
          onReorder={(next) => updateCurrentSetlist(next)}
          ref={containerRef}
          className="flex flex-col gap-4"
        >
          {setlist.map((song, index) => (
            <Reorder.Item
              key={song.id}
              value={song}
              className="flex items-stretch bg-gray-50 rounded-xl overflow-hidden cursor-grab active:cursor-grabbing"
            >
              {/* 드래그 핸들 (시각적 표시용, 카드 전체가 드래그 가능) */}
              <div className="flex items-center px-2 text-gray-300">
                <GripVertical size={18} />
              </div>
              <div className="flex-1 p-4 space-y-3 min-w-0">
                  {/* 헤더 */}
                  <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>
            </Reorder.Item>
          ))}
        </Reorder.Group>

        <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">
          {rounds.length > 1
            ? "회차별로 세트리스트를 다르게 입력할 수 있습니다. '다른 회차에서 복사'로 빠르게 시작하세요."
            : "곡 추가 시 콘서트 참여 멤버가 자동으로 선택됩니다. 솔로/유닛 곡은 개별 조정하세요."}
        </p>
      </div>
    </>
  );
}

export default SetlistSection;
