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

import DatePicker from "@/components/pc/admin/common/DatePicker";
import TimePicker from "@/components/pc/admin/common/TimePicker";
import ConfirmDialog from "@/components/pc/admin/common/ConfirmDialog";
import VenueSearchDialog from "@/components/pc/admin/common/VenueSearchDialog";

/**
 * 공연 일정 섹션
 * - 다회차 지원 (날짜, 시간, 장소)
 */
function ScheduleSection({ rounds, setRounds }) {
  const containerRef = useRef(null);
  const [nextId, setNextId] = useState(() => {
    const maxId = rounds.reduce((max, r) => Math.max(max, r.id || 0), 0);
    return maxId + 1;
  });

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

  // 장소 검색 다이얼로그
  const [locationSearch, setLocationSearch] = useState({
    isOpen: false,
    roundId: null,
  });

  // 장소 삭제 확인 다이얼로그
  const [venueDeleteConfirm, setVenueDeleteConfirm] = useState({
    isOpen: false,
    roundId: null,
    venueName: null,
  });

  // 회차 추가
  const addRound = () => {
    const newRound = {
      id: nextId,
      date: "",
      time: "",
      venue: null, // { name, address, lat, lng }
    };
    setRounds([...rounds, newRound]);
    setNextId(nextId + 1);

    // 새 회차로 스크롤
    setTimeout(() => {
      if (containerRef.current) {
        const lastChild = containerRef.current.lastElementChild;
        if (lastChild) {
          lastChild.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    }, 100);
  };

  // 회차 삭제 시도
  const handleRemoveRound = (id) => {
    if (rounds.length <= 1) return;

    const round = rounds.find((r) => r.id === id);
    const roundIndex = rounds.findIndex((r) => r.id === id);

    // 입력값이 있으면 확인 다이얼로그 표시
    if (round && (round.date || round.time || round.venue)) {
      setDeleteConfirm({
        isOpen: true,
        roundId: id,
        roundIndex: roundIndex + 1,
      });
    } else {
      removeRound(id);
    }
  };

  // 회차 삭제 실행
  const removeRound = (id) => {
    setRounds(rounds.filter((round) => round.id !== id));
  };

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

  // 회차 업데이트
  const updateRound = (id, field, value) => {
    setRounds(
      rounds.map((round) =>
        round.id === id ? { ...round, [field]: value } : round
      )
    );
  };

  // 장소 검색 열기
  const openLocationSearch = (roundId) => {
    setLocationSearch({ isOpen: true, roundId });
  };

  // 장소 선택
  const handleLocationSelect = (place) => {
    if (locationSearch.roundId !== null) {
      updateRound(locationSearch.roundId, "venue", place);
    }
    setLocationSearch({ isOpen: false, roundId: null });
  };

  // 장소 삭제 시도
  const handleRemoveVenue = (roundId) => {
    const round = rounds.find((r) => r.id === roundId);
    if (round?.venue) {
      setVenueDeleteConfirm({
        isOpen: true,
        roundId,
        venueName: round.venue.name,
      });
    }
  };

  // 장소 삭제 확인
  const handleConfirmVenueDelete = () => {
    if (venueDeleteConfirm.roundId !== null) {
      updateRound(venueDeleteConfirm.roundId, "venue", null);
    }
    setVenueDeleteConfirm({ isOpen: false, roundId: null, venueName: null });
  };

  return (
    <>
      {/* 삭제 확인 다이얼로그 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() =>
          setDeleteConfirm({ isOpen: false, roundId: null, roundIndex: null })
        }
        onConfirm={handleConfirmDelete}
        title="회차 삭제"
        message={
          <p>
            <span className="font-medium">{deleteConfirm.roundIndex}회차</span>에
            입력된 정보가 있습니다.
            <br />
            정말 삭제하시겠습니까?
          </p>
        }
        confirmText="삭제"
        cancelText="취소"
      />

      {/* 장소 검색 다이얼로그 */}
      <VenueSearchDialog
        isOpen={locationSearch.isOpen}
        onClose={() => setLocationSearch({ isOpen: false, roundId: null })}
        onSelect={handleLocationSelect}
      />

      {/* 장소 삭제 확인 다이얼로그 */}
      <ConfirmDialog
        isOpen={venueDeleteConfirm.isOpen}
        onClose={() =>
          setVenueDeleteConfirm({ isOpen: false, roundId: null, venueName: null })
        }
        onConfirm={handleConfirmVenueDelete}
        title="장소 삭제"
        message={
          <p>
            <span className="font-medium">{venueDeleteConfirm.venueName}</span>
            을(를) 삭제하시겠습니까?
          </p>
        }
        confirmText="삭제"
        cancelText="취소"
      />

      <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}>
            {rounds.map((round, index) => (
              <motion.div
                key={round.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>
                    {rounds.length > 1 && (
                      <button
                        type="button"
                        onClick={() => handleRemoveRound(round.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>
                      <DatePicker
                        value={round.date}
                        onChange={(val) => updateRound(round.id, "date", val)}
                        placeholder="날짜 선택"
                        minYear={2017}
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-500 mb-1">
                        시간 (선택)
                      </label>
                      <TimePicker
                        value={round.time}
                        onChange={(val) => updateRound(round.id, "time", val)}
                        placeholder="시간 선택"
                      />
                    </div>
                  </div>

                  {/* 장소 */}
                  <div>
                    <label className="block text-xs text-gray-500 mb-1">
                      장소 (선택)
                    </label>
                    {round.venue ? (
                      <div className="flex items-center gap-2 p-3 bg-white border border-gray-200 rounded-lg">
                        <MapPin size={16} className="text-primary flex-shrink-0" />
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-medium text-gray-900 truncate">
                              {round.venue.name}
                            </p>
                            {round.venue.country && (
                              <span className="text-xs text-gray-400 flex-shrink-0">
                                {round.venue.country}
                              </span>
                            )}
                          </div>
                          <p className="text-xs text-gray-500 truncate">
                            {round.venue.address}
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={() => handleRemoveVenue(round.id)}
                          className="p-1 text-gray-400 hover:text-red-500 transition-colors"
                        >
                          <Trash2 size={14} />
                        </button>
                      </div>
                    ) : (
                      <button
                        type="button"
                        onClick={() => openLocationSearch(round.id)}
                        className="w-full flex items-center justify-center gap-2 px-4 py-2.5 border border-gray-200 rounded-lg text-gray-500 hover:border-primary hover:text-primary hover:bg-primary/5 transition-colors"
                      >
                        <Search size={16} />
                        <span className="text-sm">장소 검색</span>
                      </button>
                    )}
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>

        <button
          type="button"
          onClick={addRound}
          className="w-full mt-4 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"
        >
          <Plus size={14} />
          회차 추가
        </button>

        <p className="text-xs text-gray-400 mt-3">
          시간과 장소는 선택사항입니다. 미정인 경우 비워두세요.
        </p>
      </div>
    </>
  );
}

export default ScheduleSection;
