import { useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import {
  YoutubeFilled,
  GlobeFilled,
  VideoFilled,
  FileTextFilled,
  ShareFilled,
  RefreshFilled,
  BoltFilled,
} from '@/shared/icons/FilledIcons';
import { Button } from '@/shared/ui/button';
import type { AssetCard, YouTubeRepurposeItem, AssetSource, AssetType, AssetStatus } from '@/features/plan/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-brand-tint-purple', text: 'text-brand-purple-muted', border: 'border-brand-tint-lavender', label: '수집 완료' },
  pending:        { bg: 'bg-brand-earth-bg', text: 'text-brand-earth', border: 'border-brand-earth-soft', label: '수집 대기' },
  needs_creation: { bg: 'bg-brand-rose-bg', text: 'text-brand-rose', border: 'border-brand-rose-soft', 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) {
  // 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-brand-navy 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-brand-rose-bg border border-brand-rose-soft flex items-center justify-center">
                        <YoutubeFilled size={16} className="text-brand-rose-mid" />
                      </div>
                      <div>
                        <p className="font-bold text-brand-navy 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
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  onClick={onClose}
                  className="rounded-full bg-slate-100 hover:bg-slate-200 text-slate-500"
                >
                  <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-brand-purple-vivid" />
                          <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-brand-tint-purple text-brand-purple-muted border border-brand-tint-lavender">
                              {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-brand-navy">{formatViews(asset.data.views)}</p>
                        <p className="text-xs text-slate-500 mt-0.5">조회수</p>
                      </div>
                      <div className="flex-1 rounded-xl bg-brand-tint-purple border border-brand-tint-lavender p-3 text-center">
                        <p className="text-xl font-bold text-brand-purple-muted">{asset.data.type === 'Short' ? 'Shorts' : 'Long'}</p>
                        <p className="text-xs text-brand-purple-vivid 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-brand-purple-vivid" />
                          <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-brand-tint-purple text-brand-purple-muted border border-brand-tint-lavender">
                              {s}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>

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