import { useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import {
  YoutubeFilled,
  GlobeFilled,
  VideoFilled,
  FileTextFilled,
  ShareFilled,
  RefreshFilled,
  BoltFilled,
} from '../icons/FilledIcons';
import type { AssetCard, YouTubeRepurposeItem, AssetSource, AssetType, AssetStatus } from '../../types/plan';

type ModalAsset =
  | { kind: 'asset'; data: AssetCard }
  | { kind: 'youtube'; data: YouTubeRepurposeItem };

interface AssetDetailModalProps {
  asset: ModalAsset | null;
  onClose: () => void;
}

const sourceIcon: Record<AssetSource, typeof GlobeFilled> = {
  homepage: GlobeFilled,
  naver_place: GlobeFilled,
  blog: FileTextFilled,
  social: ShareFilled,
  youtube: YoutubeFilled,
};

const typeLabels: Record<AssetType, string> = {
  photo: '사진',
  video: '영상',
  text: '텍스트',
};

const statusConfig: Record<AssetStatus, { bg: string; text: string; border: string; label: string }> = {
  collected:      { bg: 'bg-[#F3F0FF]', text: 'text-[#4A3A7C]', border: 'border-[#D5CDF5]', label: '수집 완료' },
  pending:        { bg: 'bg-[#FFF6ED]', text: 'text-[#7C5C3A]', border: 'border-[#F5E0C5]', label: '수집 대기' },
  needs_creation: { bg: 'bg-[#FFF0F0]', text: 'text-[#7C3A4B]', border: 'border-[#F5D5DC]', label: '제작 필요' },
};

function formatViews(views: number): string {
  if (views >= 1_000_000) return `${(views / 1_000_000).toFixed(1)}M`;
  if (views >= 1_000) return `${Math.round(views / 1_000)}K`;
  return String(views);
}

export default function AssetDetailModal({ asset, onClose }: AssetDetailModalProps) {
  // Close on Escape
  useEffect(() => {
    if (!asset) return;
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [asset, onClose]);

  return (
    <AnimatePresence>
      {asset && (
        <>
          {/* Backdrop */}
          <motion.div
            className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
          />

          {/* Modal Panel */}
          <motion.div
            className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"
            initial={{ opacity: 0, scale: 0.95, y: 16 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 8 }}
            transition={{ duration: 0.22, ease: 'easeOut' }}
          >
            <div
              className="bg-white rounded-3xl shadow-2xl w-full max-w-lg pointer-events-auto overflow-hidden"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Header bar */}
              <div className="flex items-center justify-between px-6 pt-5 pb-4 border-b border-slate-100">
                <div className="flex items-center gap-3">
                  {asset.kind === 'asset' ? (
                    <>
                      {(() => {
                        const Icon = sourceIcon[asset.data.source];
                        const status = statusConfig[asset.data.status];
                        return (
                          <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${status.bg} border ${status.border}`}>
                            <Icon size={16} className={status.text} />
                          </div>
                        );
                      })()}
                      <div>
                        <p className="font-bold text-[#0A1128] text-sm">{asset.data.title}</p>
                        <p className="text-xs text-slate-500">{asset.data.sourceLabel} · {typeLabels[asset.data.type]}</p>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="w-9 h-9 rounded-xl bg-[#FFF0F0] border border-[#F5D5DC] flex items-center justify-center">
                        <YoutubeFilled size={16} className="text-[#D4889A]" />
                      </div>
                      <div>
                        <p className="font-bold text-[#0A1128] text-sm">{asset.data.title}</p>
                        <p className="text-xs text-slate-500">YouTube · {asset.data.type === 'Short' ? 'Shorts' : 'Long-form'} · {formatViews(asset.data.views)} views</p>
                      </div>
                    </>
                  )}
                </div>
                <button
                  onClick={onClose}
                  className="w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center transition-colors"
                >
                  <svg className="w-4 h-4 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* Body */}
              <div className="px-6 py-5 space-y-5 max-h-[60vh] overflow-y-auto">
                {asset.kind === 'asset' && (
                  <>
                    {/* Status + type badges */}
                    <div className="flex flex-wrap gap-2">
                      {(() => {
                        const s = statusConfig[asset.data.status];
                        return (
                          <span className={`text-xs font-semibold px-3 py-1 rounded-full border ${s.bg} ${s.text} ${s.border}`}>
                            {s.label}
                          </span>
                        );
                      })()}
                      <span className="text-xs font-medium px-3 py-1 rounded-full bg-slate-100 text-slate-600">
                        {typeLabels[asset.data.type]}
                      </span>
                    </div>

                    {/* Description */}
                    <div>
                      <p className="text-xs font-semibold text-slate-400 uppercase tracking-widest mb-1.5">설명</p>
                      <p className="text-sm text-slate-700 leading-relaxed">{asset.data.description}</p>
                    </div>

                    {/* Repurposing suggestions */}
                    {asset.data.repurposingSuggestions.length > 0 && (
                      <div>
                        <div className="flex items-center gap-2 mb-2">
                          <RefreshFilled size={13} className="text-[#6C5CE7]" />
                          <p className="text-xs font-semibold text-slate-400 uppercase tracking-widest">리퍼포징 제안</p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {asset.data.repurposingSuggestions.map((s, i) => (
                            <span key={i} className="text-xs px-3 py-1.5 rounded-full bg-[#F3F0FF] text-[#4A3A7C] border border-[#D5CDF5]">
                              {s}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </>
                )}

                {asset.kind === 'youtube' && (
                  <>
                    {/* Stats */}
                    <div className="flex gap-3">
                      <div className="flex-1 rounded-xl bg-slate-50 border border-slate-100 p-3 text-center">
                        <p className="text-xl font-bold text-[#0A1128]">{formatViews(asset.data.views)}</p>
                        <p className="text-xs text-slate-500 mt-0.5">조회수</p>
                      </div>
                      <div className="flex-1 rounded-xl bg-[#F3F0FF] border border-[#D5CDF5] p-3 text-center">
                        <p className="text-xl font-bold text-[#4A3A7C]">{asset.data.type === 'Short' ? 'Shorts' : 'Long'}</p>
                        <p className="text-xs text-[#6C5CE7] mt-0.5">포맷</p>
                      </div>
                    </div>

                    {/* Repurpose targets */}
                    {asset.data.repurposeAs.length > 0 && (
                      <div>
                        <div className="flex items-center gap-2 mb-2">
                          <BoltFilled size={13} className="text-[#6C5CE7]" />
                          <p className="text-xs font-semibold text-slate-400 uppercase tracking-widest">리퍼포징 타겟</p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {asset.data.repurposeAs.map((s, i) => (
                            <span key={i} className="text-xs px-3 py-1.5 rounded-full bg-[#F3F0FF] text-[#4A3A7C] border border-[#D5CDF5]">
                              {s}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>

              {/* Footer CTA */}
              <div className="px-6 pb-5 pt-3 border-t border-slate-50">
                <button
                  onClick={onClose}
                  className="w-full py-2.5 rounded-xl bg-gradient-to-r from-[#4F1DA1] to-[#021341] text-white text-sm font-semibold hover:opacity-90 transition-opacity"
                >
                  제작 파이프라인에 추가
                </button>
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
