import { motion } from 'framer-motion';
import { Calendar, Link2, Clock } from 'lucide-react';
import { decodeHtmlEntities, formatXDateTimeWithTime } from './utils';

/**
 * 영상 정보 컴포넌트 (공통)
 */
function VideoInfo({ schedule, isShorts, isScheduled = false }) {
  const members = schedule.members || [];
  const isFullGroup = members.length === 5;
  // 채널명: channelName 또는 source.name에서 가져옴
  const channelName = schedule.channelName || schedule.source?.name;

  return (
    <div className={`bg-gradient-to-br from-gray-100 to-gray-200/80 rounded-2xl p-6 ${isShorts ? 'flex-1' : ''}`}>
      {/* 제목 */}
      <div className="flex items-center gap-3 mb-4">
        <h1 className={`font-bold text-gray-900 leading-relaxed ${isShorts || isScheduled ? 'text-lg' : 'text-xl'}`}>
          {decodeHtmlEntities(schedule.title)}
        </h1>
        {isScheduled && (
          <span className="flex-shrink-0 px-2.5 py-1 bg-amber-100 text-amber-700 text-xs font-semibold rounded-full">
            예정
          </span>
        )}
      </div>

      {/* 메타 정보 */}
      <div className={`flex flex-wrap items-center gap-4 text-sm ${isShorts || isScheduled ? 'gap-3' : ''}`}>
        {/* 날짜/시간 */}
        <div className="flex items-center gap-1.5 text-gray-500">
          <Calendar size={14} />
          <span>{formatXDateTimeWithTime(schedule.date, schedule.time)}</span>
        </div>

        {/* 채널명 */}
        {channelName && (
          <>
            <div className="w-px h-4 bg-gray-300" />
            <div className="flex items-center gap-2 text-gray-500">
              <Link2 size={14} className="opacity-60" />
              <span className="font-medium">{channelName}</span>
            </div>
          </>
        )}
      </div>

      {/* 멤버 목록 */}
      {members.length > 0 && (
        <div className="flex flex-wrap gap-2 mt-4">
          {isFullGroup ? (
            <span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">프로미스나인</span>
          ) : (
            members.map((member) => (
              <span key={member.id} className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
                {member.name}
              </span>
            ))
          )}
        </div>
      )}

      {/* 유튜브에서 보기 버튼 (예정 일정이 아닐 때만) */}
      {!isScheduled && (
        <div className="mt-6 pt-5 border-t border-gray-300/60">
          <a
            href={schedule.videoUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-red-500 hover:bg-red-600 text-white rounded-xl font-medium transition-colors shadow-lg shadow-red-500/20"
          >
            <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
              <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
            </svg>
            YouTube에서 보기
          </a>
        </div>
      )}
    </div>
  );
}

/**
 * 예정 일정 Placeholder 컴포넌트
 */
function ScheduledPlaceholder({ bannerUrl }) {
  return (
    <div className="relative aspect-video bg-gradient-to-br from-gray-800 to-gray-900 rounded-2xl overflow-hidden shadow-lg shadow-black/10">
      {/* 배경: 배너 이미지 또는 패턴 */}
      {bannerUrl ? (
        <div
          className="absolute inset-0 bg-cover bg-center"
          style={{ backgroundImage: `url(${bannerUrl})` }}
        >
          <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent" />
        </div>
      ) : (
        <div className="absolute inset-0 opacity-5">
          <div className="absolute inset-0" style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
          }} />
        </div>
      )}

      {/* 하단 텍스트 */}
      <div className="absolute bottom-0 left-0 right-0 p-6">
        <div className="flex items-center gap-2 text-white/90">
          <Clock size={18} className="text-amber-400" />
          <span className="text-lg font-medium">업로드 예정</span>
        </div>
      </div>
    </div>
  );
}

/**
 * PC 유튜브 섹션 컴포넌트
 */
function YoutubeSection({ schedule }) {
  const videoId = schedule.videoId;
  const isShorts = schedule.videoType === 'shorts';
  const isScheduled = !videoId; // videoId가 없으면 예정 일정

  // 예정 일정: 세로 레이아웃 (Placeholder + 정보)
  if (isScheduled) {
    return (
      <div className="space-y-6">
        {/* 예정 Placeholder */}
        <motion.div
          initial={{ opacity: 0, scale: 0.98 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.1 }}
          className="w-full"
        >
          <ScheduledPlaceholder bannerUrl={schedule.bannerUrl} />
        </motion.div>

        {/* 영상 정보 카드 */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
          <VideoInfo schedule={schedule} isShorts={false} isScheduled={true} />
        </motion.div>
      </div>
    );
  }

  // 숏츠: 가로 레이아웃 (영상 + 정보)
  if (isShorts) {
    return (
      <div className="flex gap-6 items-start">
        {/* 영상 임베드 */}
        <motion.div
          initial={{ opacity: 0, scale: 0.98 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.1 }}
          className="w-[420px] flex-shrink-0"
        >
          <div className="relative aspect-[9/16] bg-gray-900 rounded-2xl overflow-hidden shadow-lg shadow-black/10">
            <iframe
              src={`https://www.youtube.com/embed/${videoId}?rel=0`}
              title={schedule.title}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              className="absolute inset-0 w-full h-full"
            />
          </div>
        </motion.div>

        {/* 영상 정보 카드 */}
        <motion.div
          initial={{ opacity: 0, x: 10 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: 0.2 }}
          className="flex-1"
        >
          <VideoInfo schedule={schedule} isShorts={true} />
        </motion.div>
      </div>
    );
  }

  // 일반 영상: 세로 레이아웃 (영상 위, 정보 아래)
  return (
    <div className="space-y-6">
      {/* 영상 임베드 */}
      <motion.div
        initial={{ opacity: 0, scale: 0.98 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 0.1 }}
        className="w-full"
      >
        <div className="relative aspect-video bg-gray-900 rounded-2xl overflow-hidden shadow-lg shadow-black/10">
          <iframe
            src={`https://www.youtube.com/embed/${videoId}?rel=0`}
            title={schedule.title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            className="absolute inset-0 w-full h-full"
          />
        </div>
      </motion.div>

      {/* 영상 정보 카드 */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
        <VideoInfo schedule={schedule} isShorts={false} />
      </motion.div>
    </div>
  );
}

export default YoutubeSection;
