import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Download, Sparkles, AlertCircle, CheckCircle } from 'lucide-react';

interface VersionInfo {
  version: string;
  date: string;
  changes: string[];
  fixes: string[];
  isRequired: boolean;
}

// 当前版本
const CURRENT_VERSION = '2.1.0';

// 模拟版本更新数据（实际应从服务器获取）
const LATEST_VERSION: VersionInfo = {
  version: '2.1.0',
  date: '2026-06-04',
  changes: [
    '重大版本升级：全流程模拟测试通过',
    '新增 Bug 快速排查检查单（12大类90+检查项）',
    '完善数据库31张表完整文档和API示例',
    '新增 E2E 全流程测试文件 (full-workflow.spec.ts)',
    '系统审计四维度全面通过（文件关联/内存安全/路由/权限）',
    '设计架构规范文档化（CSS变量/动效/响应式/布局差异）',
  ],
  fixes: [
    '修复 usePlanStatusSync 测试间隔标注',
    '修复数据完整性问题（孤儿记录/状态不一致/过期链接）',
    '修复 production_plans RLS 策略文档记录',
  ],
  isRequired: true,
};

interface VersionUpdateProps {
  isOpen: boolean;
  onClose: () => void;
  onUpdate?: () => void;
}

export function VersionUpdate({ isOpen, onClose, onUpdate }: VersionUpdateProps) {
  const [hasUpdate, setHasUpdate] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);
  const [updateComplete, setUpdateComplete] = useState(false);

  useEffect(() => {
    // 检查是否有新版本
    const checkVersion = () => {
      const storedVersion = localStorage.getItem('app_version');
      const lastShownVersion = localStorage.getItem('update_modal_shown');
      
      // 如果版本不同且弹窗未显示过
      if (storedVersion !== CURRENT_VERSION) {
        localStorage.setItem('app_version', CURRENT_VERSION);
        
        // 模拟检查更新（实际应调用API）
        if (LATEST_VERSION.version !== CURRENT_VERSION && lastShownVersion !== LATEST_VERSION.version) {
          setHasUpdate(true);
        }
      }
    };

    checkVersion();
  }, []);

  const handleUpdate = async () => {
    setIsUpdating(true);
    
    // 模拟更新过程
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    setIsUpdating(false);
    setUpdateComplete(true);
    localStorage.setItem('update_modal_shown', LATEST_VERSION.version);
    
    setTimeout(() => {
      onClose();
      if (onUpdate) onUpdate();
      // 刷新页面以应用更新
      window.location.reload();
    }, 1500);
  };

  const handleSkip = () => {
    localStorage.setItem('update_modal_shown', LATEST_VERSION.version);
    onClose();
  };

  if (!isOpen || !hasUpdate) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="bg-white rounded-2xl w-full max-w-md shadow-2xl overflow-hidden"
      >
        {/* 头部 */}
        <div className="bg-gradient-to-r from-blue-500 to-indigo-600 p-6 text-white">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                <Sparkles className="w-6 h-6" />
              </div>
              <div>
                <h2 className="text-xl font-bold">发现新版本</h2>
                <p className="text-sm text-white/80">v{LATEST_VERSION.version} · {LATEST_VERSION.date}</p>
              </div>
            </div>
            <button
              onClick={handleSkip}
              className="p-2 hover:bg-white/20 rounded-lg transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* 内容 */}
        <div className="p-6 space-y-4">
          {updateComplete ? (
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-8 h-8 text-green-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">更新完成</h3>
              <p className="text-sm text-gray-500">页面即将刷新...</p>
            </div>
          ) : (
            <>
              {/* 新功能 */}
              <div>
                <h3 className="text-sm font-semibold text-gray-900 mb-2 flex items-center gap-2">
                  <Sparkles className="w-4 h-4 text-blue-500" />
                  新功能
                </h3>
                <ul className="space-y-1.5">
                  {LATEST_VERSION.changes.map((change, index) => (
                    <li key={index} className="text-sm text-gray-600 flex items-start gap-2">
                      <span className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-1.5 flex-shrink-0" />
                      {change}
                    </li>
                  ))}
                </ul>
              </div>

              {/* 修复 */}
              <div>
                <h3 className="text-sm font-semibold text-gray-900 mb-2 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 text-amber-500" />
                  问题修复
                </h3>
                <ul className="space-y-1.5">
                  {LATEST_VERSION.fixes.map((fix, index) => (
                    <li key={index} className="text-sm text-gray-600 flex items-start gap-2">
                      <span className="w-1.5 h-1.5 bg-amber-400 rounded-full mt-1.5 flex-shrink-0" />
                      {fix}
                    </li>
                  ))}
                </ul>
              </div>

              {/* 按钮 */}
              <div className="flex gap-3 pt-2">
                <button
                  onClick={handleSkip}
                  className="flex-1 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl transition-colors text-sm font-medium"
                >
                  知道了
                </button>
              </div>
            </>
          )}
        </div>
      </motion.div>
    </div>
  );
}

// 版本检查Hook
export function useVersionCheck() {
  const [showUpdate, setShowUpdate] = useState(false);

  useEffect(() => {
    const check = () => {
      const lastShown = localStorage.getItem('update_modal_shown');
      if (LATEST_VERSION.version !== CURRENT_VERSION && lastShown !== LATEST_VERSION.version) {
        setShowUpdate(true);
      }
    };

    check();
    // 每天检查一次
    const interval = setInterval(check, 24 * 60 * 60 * 1000);
    return () => clearInterval(interval);
  }, []);

  return { showUpdate, setShowUpdate, currentVersion: CURRENT_VERSION };
}

// 关于窗口组件
export function AboutModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="bg-white rounded-2xl w-full max-w-sm shadow-2xl overflow-hidden"
      >
        <div className="p-6 text-center">
          {/* Logo */}
          <div className="w-20 h-20 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <span className="text-2xl font-bold text-white">昱</span>
          </div>
          
          {/* 软件信息 */}
          <h2 className="text-xl font-bold text-gray-900 mb-1">昱森纺织管理系统</h2>
          <p className="text-sm text-gray-500 mb-4">Demo版</p>
          
          <div className="space-y-2 text-sm text-gray-600 mb-6">
            <div className="flex justify-between px-4 py-2 bg-gray-50 rounded-lg">
              <span>版本号</span>
              <span className="font-medium">v{CURRENT_VERSION}</span>
            </div>
            <div className="flex justify-between px-4 py-2 bg-gray-50 rounded-lg">
              <span>版权所有</span>
              <span className="font-medium">© 2025 昱森科技</span>
            </div>
            <div className="flex justify-between px-4 py-2 bg-gray-50 rounded-lg">
              <span>技术支持</span>
              <span className="font-medium">support@yusen.com</span>
            </div>
          </div>

          <button
            onClick={onClose}
            className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl transition-colors text-sm font-medium"
          >
            确定
          </button>
        </div>
      </motion.div>
    </div>
  );
}
