'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { XMarkIcon, PlayIcon } from '@heroicons/react/24/outline';
import SkinViewer from './SkinViewer';

interface SkinDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  texture: {
    id: number;
    name: string;
    url: string;
    type: 'SKIN' | 'CAPE';
    is_slim?: boolean;
    description?: string;
    favorite_count?: number;
    download_count?: number;
    created_at?: string;
    uploader?: {
      username: string;
    };
  } | null;
  isExternalPreview?: boolean;
}

export default function SkinDetailModal({ isOpen, onClose, texture, isExternalPreview = false }: SkinDetailModalProps) {
  const [currentAnimation, setCurrentAnimation] = useState<'idle' | 'walking' | 'running' | 'swimming'>('idle');
  const [autoRotate, setAutoRotate] = useState(!isExternalPreview);
  const [rotation, setRotation] = useState(true);
  const [isMinimized, setIsMinimized] = useState(false);
  const [isPaused, setIsPaused] = useState(false); // 新增：动画暂停状态
  
  // 重置状态当对话框关闭时
  useEffect(() => {
    if (!isOpen) {
      setCurrentAnimation('idle');
      setAutoRotate(!isExternalPreview);
      setRotation(true);
      setIsMinimized(false);
      setIsPaused(false); // 重置暂停状态
    }
  }, [isOpen]);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isOpen) return;
      
      switch (e.key) {
        case 'Escape':
          onClose();
          break;
        case ' ':
          e.preventDefault();
          // 空格键暂停/继续动画
          setIsPaused(prev => !prev);
          break;
        case '1':
          setCurrentAnimation('idle');
          break;
        case '2':
          setCurrentAnimation('walking');
          break;
        case '3':
          setCurrentAnimation('running');
          break;
        case '4':
          setCurrentAnimation('swimming');
          break;
        case 'm':
        case 'M':
          setIsMinimized(prev => !prev);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  // 动画控制函数
  const handleAnimationChange = (animation: 'idle' | 'walking' | 'running' | 'swimming') => {
    setCurrentAnimation(animation);
    // 添加触觉反馈
    if (navigator.vibrate) {
      navigator.vibrate(50);
    }
  };

  const getModalVariants = () => ({
    initial: { 
      opacity: 0, 
      scale: 0.7, 
      rotateX: -15,
      y: 50
    },
    animate: { 
      opacity: 1, 
      scale: 1, 
      rotateX: 0,
      y: 0,
      transition: {
        duration: 0.5,
        type: "spring" as const,
        stiffness: 100,
        damping: 15
      }
    },
    exit: { 
      opacity: 0, 
      scale: 0.7, 
      rotateX: 15,
      y: 50,
      transition: {
        duration: 0.3
      }
    },
    minimized: {
      scale: 0.8,
      y: window.innerHeight - 200,
      x: window.innerWidth - 300,
      width: 280,
      height: 150,
      transition: {
        duration: 0.4
      }
    }
  });

  if (!texture) return null;

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
          onClick={onClose}
          style={{ 
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            isolation: 'isolate'
          }}
        >
          <motion.div
            variants={getModalVariants()}
            initial="initial"
            animate={isMinimized ? "minimized" : "animate"}
            exit="exit"
            transition={{ type: "spring", damping: 20, stiffness: 300 }}
            className={`relative bg-white/98 dark:bg-gray-800/98 rounded-2xl shadow-2xl overflow-hidden border border-white/40 dark:border-gray-700/60 backdrop-blur-2xl ${
              isMinimized ? 'fixed bottom-4 right-4' : 'w-full max-w-6xl h-[90vh]'
            }`}
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <motion.div 
              className="absolute top-0 left-0 right-0 bg-gradient-to-r from-white/95 via-orange-50/95 to-amber-50/95 dark:from-gray-800/95 dark:via-gray-800/95 dark:to-gray-700/95 backdrop-blur-xl border-b border-orange-200/60 dark:border-gray-600/60 p-4 z-10 shadow-lg"
              initial={{ y: -100 }}
              animate={{ y: 0 }}
              transition={{ delay: 0.2, duration: 0.4 }}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <motion.h2 
                    className="text-3xl font-bold bg-gradient-to-r from-orange-500 via-amber-500 to-yellow-500 bg-clip-text text-transparent drop-shadow-sm"
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: 0.3 }}
                  >
                    {texture.name}
                  </motion.h2>
                  <div className="flex items-center space-x-2">
                    <motion.span 
                      className={`px-4 py-2 text-sm rounded-full font-semibold shadow-md ${
                        texture.type === 'SKIN' 
                          ? 'bg-gradient-to-r from-orange-100 to-amber-100 text-orange-800 dark:from-orange-900/40 dark:to-amber-900/40 dark:text-orange-300 border border-orange-200/50 dark:border-orange-700/30' 
                          : 'bg-gradient-to-r from-purple-100 to-pink-100 text-purple-800 dark:from-purple-900/40 dark:to-pink-900/40 dark:text-purple-300 border border-purple-200/50 dark:border-purple-700/30'
                      }`}
                      initial={{ scale: 0, opacity: 0 }}
                      animate={{ scale: 1, opacity: 1 }}
                      transition={{ delay: 0.4, type: "spring", stiffness: 200 }}
                    >
                      {texture.type === 'SKIN' ? '皮肤' : '披风'}
                    </motion.span>
                    {texture.is_slim && (
                    <motion.span 
                      className="px-4 py-2 bg-gradient-to-r from-pink-100 to-rose-100 text-pink-800 dark:from-pink-900/40 dark:to-rose-900/40 text-sm rounded-full font-semibold shadow-md border border-pink-200/50 dark:border-pink-700/30"
                      initial={{ scale: 0, opacity: 0 }}
                      animate={{ scale: 1, opacity: 1 }}
                      transition={{ delay: 0.5, type: "spring", stiffness: 200 }}
                    >
                        细臂
                      </motion.span>
                    )}
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <motion.button
                    onClick={() => setIsMinimized(!isMinimized)}
                    className="p-2 text-gray-500 hover:text-orange-500 dark:text-gray-400 dark:hover:text-orange-400 rounded-full hover:bg-orange-100 dark:hover:bg-orange-900/20 transition-all duration-200"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                    initial={{ opacity: 0, rotate: -180 }}
                    animate={{ opacity: 1, rotate: 0 }}
                    transition={{ delay: 0.6 }}
                    title={isMinimized ? "最大化" : "最小化"}
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={isMinimized ? "M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" : "M9 9V4.5M9 9H4.5M9 9L3.5 3.5M15 9v4.5M15 9h4.5M15 9l5.5 5.5M9 15v4.5M9 15H4.5M9 15l-5.5 5.5M15 15v4.5M15 15h4.5m-4.5 0l5.5 5.5"} />
                    </svg>
                  </motion.button>
                  <motion.button
                    onClick={onClose}
                    className="p-3 text-gray-500 hover:text-red-500 dark:text-gray-400 dark:hover:text-red-400 rounded-full hover:bg-red-100 dark:hover:bg-red-900/30 transition-all duration-300 shadow-md hover:shadow-lg"
                    whileHover={{ scale: 1.15, rotate: 90 }}
                    whileTap={{ scale: 0.85 }}
                    initial={{ opacity: 0, rotate: -180 }}
                    animate={{ opacity: 1, rotate: 0 }}
                    transition={{ delay: 0.7 }}
                  >
                    <XMarkIcon className="w-6 h-6" />
                  </motion.button>
                </div>
              </div>
            </motion.div>

            {!isMinimized && (
              <div className="flex h-full pt-20">
                {/* 3D 预览区域 */}
                <motion.div
                  className="flex-1 flex items-center justify-center p-8 bg-gradient-to-br from-orange-50/40 via-amber-50/40 to-yellow-50/40 dark:from-gray-900/40 dark:via-gray-800/40 dark:to-gray-700/40"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: 0.3, duration: 0.5 }}
                >
                  <div className="w-full h-full max-w-2xl max-h-2xl flex items-center justify-center">
                    <div className="relative">
                      <div className="absolute inset-0 bg-gradient-to-br from-orange-400/20 to-amber-400/20 dark:from-orange-500/10 dark:to-amber-500/10 rounded-2xl blur-xl"></div>
                      <SkinViewer
                        skinUrl={texture.url}
                        isSlim={texture.is_slim}
                        width={500}
                        height={500}
                        className="rounded-2xl shadow-2xl border-2 border-white/60 dark:border-gray-600/60 relative z-10"
                        autoRotate={autoRotate && currentAnimation === 'idle'}
                        walking={currentAnimation === 'walking'}
                        running={currentAnimation === 'running'}
                        jumping={currentAnimation === 'swimming'}
                        rotation={rotation}
                        paused={isPaused}
                      />
                    </div>
                  </div>
                </motion.div>

                {/* 控制面板 */}
                <motion.div
                  className="w-80 bg-gradient-to-b from-orange-50/90 via-amber-50/90 to-yellow-50/90 dark:from-gray-900/90 dark:via-gray-800/90 dark:to-gray-700/90 backdrop-blur-xl border-l border-orange-200/60 dark:border-gray-600/60 p-6 space-y-6 overflow-y-auto custom-scrollbar shadow-inner"
                  initial={{ opacity: 0, x: 50 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.4, duration: 0.5 }}
                >
                  {/* 动画控制 */}
                  <motion.div className="space-y-4">
                    <motion.h3
                      className="text-xl font-bold bg-gradient-to-r from-orange-500 via-amber-500 to-yellow-500 bg-clip-text text-transparent flex items-center drop-shadow-sm"
                      initial={{ opacity: 0, y: -10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.5 }}
                    >
                      <PlayIcon className="w-6 h-6 mr-3" />
                      动画控制
                    </motion.h3>
                    
                    <div className="grid grid-cols-2 gap-2">
                      {[
                        { key: 'idle', label: '静止', icon: null },
                        { key: 'walking', label: '步行', icon: null },
                        { key: 'running', label: '跑步', icon: null },
                        { key: 'swimming', label: '游泳', icon: null }
                      ].map((anim, i) => (
                        <button
                          key={anim.key}
                          onClick={() => handleAnimationChange(anim.key as any)}
                          className={`p-4 rounded-xl text-sm font-semibold transition-all duration-200 ${
                            currentAnimation === anim.key
                              ? 'bg-gradient-to-r from-orange-500 via-amber-500 to-yellow-500 text-white shadow-lg ring-2 ring-orange-300 dark:ring-orange-500'
                              : 'bg-white/80 dark:bg-gray-700/80 text-gray-700 dark:text-gray-300 hover:bg-orange-50 dark:hover:bg-orange-900/30 border border-orange-200/50 dark:border-gray-600 hover:shadow-md'
                          }`}
                        >
                          {anim.label}
                        </button>
                      ))}
                    </div>
                  </motion.div>

                  {/* 信息面板 */}
                  <motion.div 
                    className="space-y-4"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.8 }}
                  >
                    <h3 className="text-xl font-bold bg-gradient-to-r from-orange-500 via-amber-500 to-yellow-500 bg-clip-text text-transparent drop-shadow-sm">
                      皮肤信息
                    </h3>
                    
                    {texture.description && (
                      <motion.div 
                        className="bg-white/70 dark:bg-gray-700/70 rounded-xl p-4 shadow-md border border-white/30 dark:border-gray-600/30"
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.9 }}
                      >
                        <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed font-medium">
                          {texture.description}
                        </p>
                      </motion.div>
                    )}
                    
                    <div className="space-y-2 text-sm">
                      {texture.uploader && (
                        <motion.div 
                          className="flex justify-between items-center"
                          initial={{ opacity: 0, x: -10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: 1.0 }}
                        >
                          <span className="text-gray-600 dark:text-gray-400">上传者:</span>
                          <span className="font-medium text-gray-800 dark:text-gray-200">{texture.uploader.username}</span>
                        </motion.div>
                      )}
                      
                      {texture.created_at && (
                        <motion.div 
                          className="flex justify-between items-center"
                          initial={{ opacity: 0, x: -10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: 1.1 }}
                        >
                          <span className="text-gray-600 dark:text-gray-400">上传时间:</span>
                          <span className="font-medium text-gray-800 dark:text-gray-200">
                            {new Date(texture.created_at).toLocaleDateString()}
                          </span>
                        </motion.div>
                      )}
                      
                      <motion.div 
                        className="flex justify-between items-center"
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 1.2 }}
                      >
                        <span className="text-gray-600 dark:text-gray-400">收藏数:</span>
                        <span className="font-medium text-gray-800 dark:text-gray-200">{texture.favorite_count || 0}</span>
                      </motion.div>
                      
                      <motion.div 
                        className="flex justify-between items-center"
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 1.3 }}
                      >
                        <span className="text-gray-600 dark:text-gray-400">下载数:</span>
                        <span className="font-medium text-gray-800 dark:text-gray-200">{texture.download_count || 0}</span>
                      </motion.div>
                    </div>
                  </motion.div>

                  {/* 快捷键提示 */}
                  <motion.div 
                    className="bg-gradient-to-r from-orange-100/50 to-amber-100/50 dark:from-gray-700/50 dark:to-gray-600/50 rounded-xl p-4 text-xs text-gray-600 dark:text-gray-400 border border-orange-200/30 dark:border-gray-600/30"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 1.4 }}
                  >
                    <p className="font-bold mb-2 text-orange-700 dark:text-orange-300 flex items-center">
                      <span className="w-2 h-2 bg-orange-500 rounded-full mr-2"></span>
                      快捷键
                    </p>
                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div className="flex items-center"><kbd className="px-2 py-1 bg-white/70 dark:bg-gray-800/70 rounded border border-gray-300 dark:border-gray-600 text-xs mr-2">空格</kbd>暂停/继续</div>
                      <div className="flex items-center"><kbd className="px-2 py-1 bg-white/70 dark:bg-gray-800/70 rounded border border-gray-300 dark:border-gray-600 text-xs mr-2">1-4</kbd>切换动画</div>
                      <div className="flex items-center"><kbd className="px-2 py-1 bg-white/70 dark:bg-gray-800/70 rounded border border-gray-300 dark:border-gray-600 text-xs mr-2">M</kbd>最小化</div>
                      <div className="flex items-center"><kbd className="px-2 py-1 bg-white/70 dark:bg-gray-800/70 rounded border border-gray-300 dark:border-gray-600 text-xs mr-2">ESC</kbd>关闭</div>
                    </div>
                  </motion.div>
                </motion.div>
              </div>
            )}

            {/* 最小化时的内容 */}
            {isMinimized && (
              <motion.div 
                className="flex items-center justify-center h-full p-4"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.2 }}
              >
                <div className="text-center">
                  <div className="w-20 h-20 mx-auto mb-2">
                    <SkinViewer
                      skinUrl={texture.url}
                      isSlim={texture.is_slim}
                      width={80}
                      height={80}
                      autoRotate={autoRotate}
                      walking={currentAnimation === 'walking'}
                      running={currentAnimation === 'running'}
                      jumping={currentAnimation === 'swimming'}
                      paused={isPaused}
                    />
                  </div>
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300 truncate">
                    {texture.name}
                  </p>
                </div>
              </motion.div>
            )}
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}