import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { decodeHtmlEntities, formatXDateTimeWithTime } from './utils';
import { Lightbox } from '@/components/common';

/**
 * URL을 링크로 변환하는 함수
 */
function linkifyText(text) {
  if (!text) return null;

  // 해시태그 또는 URL 매칭
  const pattern = /(#[^\s#]+)|(https?:\/\/[^\s]+|(?:bit\.ly|youtu\.be|t\.co|goo\.gl|tinyurl\.com)\/[^\s]+)/gi;

  const parts = [];
  let lastIndex = 0;
  let match;

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) {
      parts.push(text.slice(lastIndex, match.index));
    }

    const matched = match[0];

    if (matched.startsWith('#')) {
      const tag = matched.slice(1);
      parts.push(
        <a key={match.index} href={`https://x.com/hashtag/${encodeURIComponent(tag)}?src=hashtag_click`} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
          {matched}
        </a>
      );
    } else {
      const href = matched.startsWith('http') ? matched : `https://${matched}`;
      parts.push(
        <a key={match.index} href={href} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
          {matched}
        </a>
      );
    }

    lastIndex = match.index + match[0].length;
  }

  if (lastIndex < text.length) {
    parts.push(text.slice(lastIndex));
  }

  return parts.length > 0 ? parts : text;
}

/**
 * 카드 이미지 (로드 실패 시 fallback 아이콘 — 인스타 등 CDN 만료 대비)
 */
function CardImage({ src, className }) {
  const [error, setError] = useState(false);
  if (!src || error) {
    return (
      <div className={`${className} flex items-center justify-center bg-gray-100 text-gray-300`}>
        <svg className="w-8 h-8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <rect x="3" y="3" width="18" height="18" rx="2" />
          <circle cx="8.5" cy="8.5" r="1.5" />
          <path d="M21 15l-5-5L5 21" />
        </svg>
      </div>
    );
  }
  return <img src={src} alt="" className={`${className} object-cover bg-gray-100`} onError={() => setError(true)} />;
}

/**
 * PC X(트위터) 섹션 컴포넌트
 */
function XSection({ schedule }) {
  const profile = schedule.profile;
  const username = profile?.username || 'realfromis_9';
  const displayName = profile?.displayName || username;
  const avatarUrl = profile?.avatarUrl;

  // 라이트박스 상태
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState(0);
  const historyPushedRef = useRef(false);

  const openLightbox = useCallback((index) => {
    setLightboxIndex(index);
    setLightboxOpen(true);
    window.history.pushState({ lightbox: true }, '');
    historyPushedRef.current = true;
  }, []);

  const closeLightbox = useCallback(() => {
    setLightboxOpen(false);
    if (historyPushedRef.current) {
      historyPushedRef.current = false;
      window.history.back();
    }
  }, []);

  // 뒤로가기 처리 (하드웨어 백버튼)
  useEffect(() => {
    const handlePopState = () => {
      if (lightboxOpen) {
        historyPushedRef.current = false;
        setLightboxOpen(false);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [lightboxOpen]);

  return (
    <div className="max-w-2xl mx-auto">
      {/* X 스타일 카드 */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="bg-white rounded-2xl border border-gray-200 overflow-hidden"
      >
        {/* 헤더 */}
        <div className="p-5 pb-0">
          <div className="flex items-center gap-3">
            {/* 프로필 이미지 */}
            {avatarUrl ? (
              <img src={avatarUrl} alt={displayName} className="w-12 h-12 rounded-full object-cover" />
            ) : (
              <div className="w-12 h-12 rounded-full bg-gradient-to-br from-gray-700 to-gray-900 flex items-center justify-center">
                <span className="text-white font-bold text-lg">{displayName.charAt(0).toUpperCase()}</span>
              </div>
            )}
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span className="font-bold text-gray-900">{displayName}</span>
                <svg className="w-5 h-5 text-blue-500" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M22.25 12c0-1.43-.88-2.67-2.19-3.34.46-1.39.2-2.9-.81-3.91s-2.52-1.27-3.91-.81c-.66-1.31-1.91-2.19-3.34-2.19s-2.67.88-3.34 2.19c-1.39-.46-2.9-.2-3.91.81s-1.27 2.52-.81 3.91C2.63 9.33 1.75 10.57 1.75 12s.88 2.67 2.19 3.34c-.46 1.39-.2 2.9.81 3.91s2.52 1.27 3.91.81c.66 1.31 1.91 2.19 3.34 2.19s2.67-.88 3.34-2.19c1.39.46 2.9.2 3.91-.81s1.27-2.52.81-3.91c1.31-.67 2.19-1.91 2.19-3.34zm-11.07 4.57l-3.84-3.84 1.27-1.27 2.57 2.57 5.39-5.39 1.27 1.27-6.66 6.66z" />
                </svg>
              </div>
              <span className="text-sm text-gray-500 -mt-0.5 block">@{username}</span>
            </div>
          </div>
        </div>

        {/* 본문 */}
        <div className="p-5">
          <p className="text-gray-900 text-[17px] leading-relaxed whitespace-pre-wrap">
            {linkifyText(decodeHtmlEntities(schedule.content || schedule.title))}
          </p>
        </div>

        {/* 이미지 */}
        {schedule.imageUrls?.length > 0 && (
          <div className="px-5 pb-3">
            {schedule.imageUrls.length === 1 ? (
              <img
                src={schedule.imageUrls[0]}
                alt=""
                className="w-full rounded-2xl border border-gray-100 cursor-pointer hover:opacity-90 transition-opacity"
                onClick={() => openLightbox(0)}
              />
            ) : (
              <div
                className={`grid gap-1 rounded-2xl overflow-hidden border border-gray-100 ${
                  schedule.imageUrls.length === 2
                    ? 'grid-cols-2'
                    : schedule.imageUrls.length === 3
                      ? 'grid-cols-2'
                      : 'grid-cols-2'
                }`}
              >
                {schedule.imageUrls.slice(0, 4).map((url, i) => (
                  <img
                    key={i}
                    src={url}
                    alt=""
                    className={`w-full object-cover cursor-pointer hover:opacity-90 transition-opacity ${
                      schedule.imageUrls.length === 3 && i === 0 ? 'row-span-2 h-full' : 'aspect-square'
                    }`}
                    onClick={() => openLightbox(i)}
                  />
                ))}
              </div>
            )}
          </div>
        )}

        {/* 영상 썸네일 (재생 버튼 → 원본 트윗으로 이동) */}
        {schedule.videoThumbnails?.length > 0 && (
          <div className="px-5 pb-3 space-y-2">
            {schedule.videoThumbnails.map((url, i) => (
              <a
                key={i}
                href={schedule.postUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="relative block rounded-2xl overflow-hidden border border-gray-100 group"
              >
                <img src={url} alt="" className="w-full object-cover" />
                <div className="absolute inset-0 flex items-center justify-center bg-black/10 group-hover:bg-black/20 transition-colors">
                  <div className="w-16 h-16 rounded-full bg-black/60 group-hover:bg-black/70 flex items-center justify-center transition-colors">
                    <svg className="w-7 h-7 text-white ml-1" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </div>
                </div>
                {/* 외부(X) 재생 표시 배지 */}
                <div className="absolute bottom-3 right-3 flex items-center gap-1.5 px-2.5 py-1.5 rounded-full bg-black/70 text-white text-xs font-medium backdrop-blur-sm">
                  <svg className="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                  </svg>
                  X에서 재생
                </div>
              </a>
            ))}
          </div>
        )}

        {/* 링크 미리보기 카드 (Open Graph) — 자체 이미지/영상이 있으면 숨김 */}
        {schedule.card?.url && !(schedule.videoThumbnails?.length > 0) && !(schedule.imageUrls?.length > 0) && (
          <div className="px-5 pb-3">
            <a
              href={schedule.card.url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-stretch rounded-2xl border border-gray-200 overflow-hidden hover:bg-gray-50 transition-colors"
            >
              {schedule.card.image && (
                <CardImage src={schedule.card.image} className="w-32 flex-shrink-0" />
              )}
              <div className="flex-1 min-w-0 p-3 flex flex-col justify-center">
                {schedule.card.destination && (
                  <p className="text-xs text-gray-400 mb-0.5">{schedule.card.destination}</p>
                )}
                {schedule.card.title && (
                  <p className="text-[15px] font-medium text-gray-900 line-clamp-2">
                    {decodeHtmlEntities(schedule.card.title)}
                  </p>
                )}
                {schedule.card.description && (
                  <p className="text-sm text-gray-500 line-clamp-2 mt-0.5">
                    {decodeHtmlEntities(schedule.card.description)}
                  </p>
                )}
              </div>
            </a>
          </div>
        )}

        {/* 날짜/시간 */}
        <div className="px-5 py-4 border-t border-gray-100">
          <span className="text-gray-500 text-[15px]">{formatXDateTimeWithTime(schedule.date, schedule.time)}</span>
        </div>

        {/* X에서 보기 버튼 */}
        <div className="px-5 py-4 border-t border-gray-100 bg-gray-50/50">
          <a
            href={schedule.postUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-900 hover:bg-black text-white rounded-full font-medium transition-colors"
          >
            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
              <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
            </svg>
            X에서 보기
          </a>
        </div>
      </motion.div>

      {/* 라이트박스 */}
      <Lightbox
        images={schedule.imageUrls || []}
        currentIndex={lightboxIndex}
        isOpen={lightboxOpen}
        onClose={closeLightbox}
        onIndexChange={setLightboxIndex}
      />
    </div>
  );
}

export default XSection;
