import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Calendar, Clock, MapPin, ShoppingBag,
  ExternalLink, Ticket, Disc3, ChevronDown, ChevronRight, X,
} from 'lucide-react';
import { Lightbox, KakaoMap } from '@/components/common';
import { decodeHtmlEntities, formatFullDate, formatTime } from './utils';

const ACCENT = '#f97316';
const COLLAPSE_COUNT = 12;

const DAYS = ['일', '월', '화', '수', '목', '금', '토'];
function shortDate(dateStr) {
  const d = new Date(dateStr);
  return `${d.getMonth() + 1}.${d.getDate()} (${DAYS[d.getDay()]})`;
}

/**
 * 콘서트 일정 섹션 — 몰입형 포스터 히어로 디자인
 */
function ConcertSection({ schedule }) {
  const navigate = useNavigate();
  const members = schedule.members || [];
  const poster = schedule.poster || null;
  const venue = schedule.venue || null;
  const setlist = schedule.setlist || [];
  const merchandise = schedule.merchandise || [];
  const otherRounds = schedule.otherRounds || [];
  const activeCount = schedule.activeMemberCount || 5;

  const kakaoMapUrl = venue && venue.lat && venue.lng
    ? `https://map.kakao.com/link/map/${encodeURIComponent(venue.name)},${venue.lat},${venue.lng}`
    : null;

  const [lightbox, setLightbox] = useState({ open: false, images: [], index: 0 });
  const [mapOpen, setMapOpen] = useState(false);
  const [roundsOpen, setRoundsOpen] = useState(false);
  const [expanded, setExpanded] = useState(false);

  const openLightbox = (images, index) => setLightbox({ open: true, images, index });
  const isUnit = (m) => m.length > 0 && m.length < activeCount;
  const posterImg = poster ? (poster.mediumUrl || poster.originalUrl) : null;

  const allRounds = [
    { scheduleId: schedule.id, date: schedule.date, time: schedule.time, current: true },
    ...otherRounds.map((r) => ({ ...r, current: false })),
  ].sort((a, b) => a.date.localeCompare(b.date));
  const hasMultiRounds = allRounds.length > 1;
  const currentRoundNum = allRounds.findIndex((r) => r.current) + 1;

  // 세트리스트 높이 (2단 그리드, 행 60px) — 펼치기/접기 애니메이션용
  const ROW_H = 60;
  const collapsible = setlist.length > COLLAPSE_COUNT;
  const collapsedHeight = Math.ceil(COLLAPSE_COUNT / 2) * ROW_H;
  const fullHeight = Math.ceil(setlist.length / 2) * ROW_H;

  return (
    <div className="space-y-6">
      {/* ===== 히어로 ===== */}
      <div className="relative rounded-[28px] overflow-hidden shadow-xl">
        {posterImg ? (
          <div className="absolute inset-0">
            <img src={posterImg} alt="" className="w-full h-full object-cover scale-110 blur-xl opacity-90" />
            <div className="absolute inset-0" style={{
              background: 'linear-gradient(110deg, rgba(12,9,7,0.82) 0%, rgba(12,9,7,0.55) 48%, rgba(124,45,18,0.4) 100%)',
            }} />
          </div>
        ) : (
          <div className="absolute inset-0" style={{ background: 'linear-gradient(120deg, #1a1410 0%, #3a1d0c 100%)' }} />
        )}

        <div className="relative flex gap-8 p-8 md:p-10">
          {/* 포스터 */}
          <div className="flex-shrink-0 w-[300px]">
            {posterImg ? (
              <button
                type="button"
                onClick={() => openLightbox([poster.originalUrl || poster.mediumUrl], 0)}
                className="block w-full rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/15 cursor-pointer transition-transform duration-300 hover:scale-[1.02]"
              >
                <img src={posterImg} alt={`${schedule.title} 포스터`} className="w-full h-auto object-cover" />
              </button>
            ) : (
              <div className="w-full aspect-[3/4] rounded-2xl bg-white/5 ring-1 ring-white/10 flex items-center justify-center">
                <Ticket size={64} className="text-white/30" strokeWidth={1.5} />
              </div>
            )}
          </div>

          {/* 정보 */}
          <div className="flex-1 min-w-0 flex flex-col justify-center py-2 text-white">
            <div className="flex items-center gap-2 mb-6">
              <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold tracking-wider uppercase"
                style={{ backgroundColor: ACCENT, color: '#1a0f06' }}>
                <Ticket size={12} />
                Concert
              </span>
              <span className="h-px flex-1 bg-white/15" />
            </div>

            <h1 className="text-3xl md:text-[40px] font-black leading-[1.08] tracking-tight mb-8">
              {decodeHtmlEntities(schedule.title)}
            </h1>

            {/* 날짜/시간/장소 (강조) */}
            <div className="space-y-4">
              {/* 날짜 + 회차 드롭다운 */}
              <div className="relative w-fit">
                <button
                  type="button"
                  onClick={() => hasMultiRounds && setRoundsOpen((v) => !v)}
                  className={`flex items-center gap-2.5 text-white ${hasMultiRounds ? 'cursor-pointer group' : 'cursor-default'}`}
                >
                  <Calendar size={20} className="text-white/55" />
                  <span className="text-xl font-bold">{formatFullDate(schedule.date)}</span>
                  {schedule.time && (
                    <>
                      <span className="text-white/30">·</span>
                      <span className="text-xl font-bold">{formatTime(schedule.time)}</span>
                    </>
                  )}
                  {hasMultiRounds && (
                    <span className="ml-1.5 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white/15 text-sm font-bold border border-white/20 group-hover:bg-white/25 transition-colors">
                      {currentRoundNum}회차
                      <ChevronDown size={15} className={`transition-transform ${roundsOpen ? 'rotate-180' : ''}`} />
                    </span>
                  )}
                </button>

                <AnimatePresence>
                  {roundsOpen && hasMultiRounds && (
                    <>
                      <div className="fixed inset-0 z-20" onClick={() => setRoundsOpen(false)} />
                      <motion.div
                        initial={{ opacity: 0, y: -8 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: -8 }}
                        transition={{ duration: 0.15 }}
                        className="absolute top-full left-0 mt-2 z-30 w-64 bg-white rounded-2xl shadow-2xl border border-gray-100 p-2"
                      >
                        {allRounds.map((round, i) => (
                          <button
                            key={round.scheduleId}
                            type="button"
                            onClick={() => {
                              setRoundsOpen(false);
                              if (!round.current) navigate(`/schedule/${round.scheduleId}`, { replace: true });
                            }}
                            className={`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm transition-colors ${
                              round.current ? 'font-bold' : 'text-gray-600 hover:bg-gray-50'
                            }`}
                            style={round.current ? { backgroundColor: `${ACCENT}14`, color: '#9a3412' } : undefined}
                          >
                            <span className="flex items-center gap-2">
                              <span className="text-xs font-bold tabular-nums w-9" style={{ color: round.current ? ACCENT : '#9ca3af' }}>{i + 1}회차</span>
                              {shortDate(round.date)}
                            </span>
                            {round.time && <span className="text-xs text-gray-400">{formatTime(round.time)}</span>}
                          </button>
                        ))}
                      </motion.div>
                    </>
                  )}
                </AnimatePresence>
              </div>

              {/* 장소 (클릭 → 지도 다이얼로그) */}
              {venue && (
                <button
                  type="button"
                  onClick={() => venue.lat && venue.lng && setMapOpen(true)}
                  className={`flex items-center gap-2.5 text-white ${venue.lat && venue.lng ? 'group cursor-pointer' : 'cursor-default'}`}
                >
                  <MapPin size={20} className="text-white/55" />
                  <span className="text-xl font-bold group-hover:underline underline-offset-4 decoration-white/40">{venue.name}</span>
                  {venue.lat && venue.lng && (
                    <ChevronRight size={18} className="text-white/40 group-hover:text-white/70 transition-colors" />
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* ===== 세트리스트 (2단) ===== */}
      {setlist.length > 0 && (
        <div className="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="flex items-center gap-3 px-8 pt-7 pb-5">
            <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{ backgroundColor: `${ACCENT}1a` }}>
              <Disc3 size={20} style={{ color: ACCENT }} />
            </div>
            <div>
              <p className="text-xs font-bold tracking-[0.18em] uppercase" style={{ color: ACCENT }}>Setlist</p>
              <h2 className="text-xl font-bold text-gray-900 -mt-0.5">세트리스트</h2>
            </div>
            <span className="ml-auto text-sm text-gray-400">{setlist.length}곡</span>
          </div>

          <div className="px-6 pb-2">
            <motion.div
              initial={false}
              animate={{ height: collapsible && !expanded ? collapsedHeight : fullHeight }}
              transition={{ duration: 0.4, ease: [0.4, 0, 0.2, 1] }}
              className="overflow-hidden"
            >
              <div className="grid grid-cols-2 gap-x-6 auto-rows-[60px]">
                {setlist.map((song, idx) => (
                  <div key={song.id} className="flex items-center gap-3 px-2 rounded-xl hover:bg-gray-50 transition-colors">
                    <span className="flex-shrink-0 w-8 text-right text-xl font-black tabular-nums leading-none text-gray-200">
                      {String(idx + 1).padStart(2, '0')}
                    </span>
                    <div className="flex-1 min-w-0">
                      <p className="text-[15px] font-semibold text-gray-900 truncate">{song.songName}</p>
                      {song.albumName && <p className="text-xs text-gray-400 truncate mt-0.5">{song.albumName}</p>}
                    </div>
                    {isUnit(song.members) && (
                      <div className="flex-shrink-0 flex flex-wrap justify-end gap-1 max-w-[140px]">
                        {song.members.map((m) => (
                          <span key={m.id} className="px-2 py-0.5 rounded-full text-xs font-semibold bg-orange-100 text-orange-700">
                            {m.name}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </motion.div>
          </div>

          {/* 펼치기/접기 */}
          {collapsible && (
            <div className="px-6 pb-6 pt-2">
              <button
                type="button"
                onClick={() => setExpanded((v) => !v)}
                className="w-full flex items-center justify-center gap-1.5 py-3 rounded-xl text-sm font-semibold text-gray-500 bg-gray-50 hover:bg-gray-100 transition-colors"
              >
                {expanded ? '접기' : `${setlist.length - COLLAPSE_COUNT}곡 더 보기`}
                <ChevronDown size={16} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />
              </button>
            </div>
          )}
        </div>
      )}

      {/* ===== 굿즈 (MD) — 원본 비율 유지, masonry ===== */}
      {merchandise.length > 0 && (
        <div className="bg-white rounded-3xl shadow-sm border border-gray-100 p-7">
          <div className="flex items-center gap-2.5 mb-5">
            <ShoppingBag size={18} style={{ color: ACCENT }} />
            <h2 className="text-base font-bold text-gray-900">MD</h2>
            <span className="text-sm text-gray-400">{merchandise.length}</span>
          </div>
          <div className="columns-3 gap-3">
            {merchandise.map((md, idx) => (
              <button key={md.id} type="button"
                onClick={() => openLightbox(merchandise.map((x) => x.originalUrl || x.mediumUrl), idx)}
                className="block w-full mb-3 break-inside-avoid rounded-xl overflow-hidden border border-gray-100 cursor-pointer hover:opacity-95 transition-opacity">
                <img src={md.mediumUrl || md.thumbUrl} alt="" className="w-full h-auto" />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* ===== 장소 지도 다이얼로그 ===== */}
      <AnimatePresence>
        {mapOpen && venue && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/50" onClick={() => setMapOpen(false)} />
            <motion.div
              initial={{ opacity: 0, scale: 0.96, y: 10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.96, y: 10 }}
              transition={{ duration: 0.18 }}
              className="relative bg-white rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden"
            >
              <div className="flex items-start justify-between p-5 pb-4">
                <div className="flex items-start gap-2.5">
                  <MapPin size={20} style={{ color: ACCENT }} className="mt-0.5 flex-shrink-0" />
                  <div>
                    <p className="font-bold text-gray-900 text-lg">{venue.name}</p>
                    {venue.address && <p className="text-sm text-gray-500 mt-0.5">{venue.address}</p>}
                  </div>
                </div>
                <button onClick={() => setMapOpen(false)} className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors">
                  <X size={18} className="text-gray-400" />
                </button>
              </div>
              <div className="px-5 pb-5">
                <KakaoMap lat={Number(venue.lat)} lng={Number(venue.lng)} name={venue.name}
                  className="w-full h-64 rounded-2xl overflow-hidden border border-gray-100" />
                {kakaoMapUrl && (
                  <a href={kakaoMapUrl} target="_blank" rel="noopener noreferrer"
                    className="mt-3 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-semibold text-white transition-opacity hover:opacity-90"
                    style={{ backgroundColor: ACCENT }}>
                    카카오맵에서 길찾기
                    <ExternalLink size={14} />
                  </a>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Lightbox */}
      <Lightbox
        images={lightbox.images}
        currentIndex={lightbox.index}
        isOpen={lightbox.open}
        onClose={() => setLightbox((prev) => ({ ...prev, open: false }))}
        onIndexChange={(index) => setLightbox((prev) => ({ ...prev, index }))}
        showCounter={lightbox.images.length > 1}
        showDownload
      />
    </div>
  );
}

export default ConcertSection;
