import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, ChevronRight, ChevronLeft, CheckCircle, Factory, ClipboardList, Share2, Package } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

interface OnboardingStep {
  id: string;
  title: string;
  description: string;
  icon: React.ElementType;
  action?: string;
  actionPath?: string;
}

// 采购商新手指引步骤
const purchaserSteps: OnboardingStep[] = [
  {
    id: 'welcome',
    title: '欢迎使用昱森纺织管理系统',
    description: '这是专为纺织行业设计的全流程协作平台，帮助您高效管理生产计划、库存和工厂协作。',
    icon: Factory,
  },
  {
    id: 'create-plan',
    title: '创建生产计划',
    description: '点击"新建计划"，填写产品信息、纱线配比等，系统会自动生成唯一的计划编号。',
    icon: ClipboardList,
    action: '去创建计划',
    actionPath: '/purchaser/plans/new',
  },
  {
    id: 'share-plan',
    title: '分享计划给工厂',
    description: '创建计划后，点击"分享计划"按钮，通过二次确认后将链接发送给纺织厂。',
    icon: Share2,
    action: '去计划总览',
    actionPath: '/purchaser/plans',
  },
  {
    id: 'manage-inventory',
    title: '管理库存',
    description: '在"产品信息"中查看和管理所有入库的坯布，支持出入库历史查询。',
    icon: Package,
    action: '去仓库管理',
    actionPath: '/purchaser/warehouse',
  },
];

// 纺织厂新手指引步骤
const textileSteps: OnboardingStep[] = [
  {
    id: 'welcome',
    title: '欢迎使用昱森纺织管理系统',
    description: '作为纺织厂，您可以接收采购商的生产计划，管理生产流程和坯布入库。',
    icon: Factory,
  },
  {
    id: 'import-plan',
    title: '导入生产计划',
    description: '通过采购商分享的链接或剪贴板导入计划，确认后即可开始生产。',
    icon: Share2,
    action: '去导入计划',
    actionPath: '/import',
  },
  {
    id: 'confirm-steps',
    title: '确认生产流程',
    description: '按计划流程逐步确认：确认计划 → 采纱 → 染纱 → 上机 → 坯布入库',
    icon: ClipboardList,
    action: '去计划总览',
    actionPath: '/textile/plans',
  },
  {
    id: 'fabric-warehouse',
    title: '坯布入库管理',
    description: '生产完成后，在"已生产坯布"页面录入入库数量和匹数。',
    icon: Package,
    action: '去坯布仓库',
    actionPath: '/textile/fabric-warehouse',
  },
];

interface OnboardingGuideProps {
  role: 'purchaser' | 'textile' | 'washing';
  isOpen: boolean;
  onClose: () => void;
}

export function OnboardingGuide({ role, isOpen, onClose }: OnboardingGuideProps) {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(0);
  const [isCompleted, setIsCompleted] = useState(false);

  const steps = role === 'purchaser' ? purchaserSteps : textileSteps;
  const step = steps[currentStep];

  useEffect(() => {
    // 检查是否已完成新手引导
    const completed = localStorage.getItem(`onboarding_completed_${role}`);
    if (completed) {
      setIsCompleted(true);
    }
  }, [role]);

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      completeOnboarding();
    }
  };

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleSkip = () => {
    completeOnboarding();
  };

  const completeOnboarding = () => {
    localStorage.setItem(`onboarding_completed_${role}`, 'true');
    setIsCompleted(true);
    onClose();
  };

  const handleAction = () => {
    if (step.actionPath) {
      completeOnboarding();
      navigate(step.actionPath);
    }
  };

  // 如果已完成引导或不显示，返回null
  if (!isOpen || isCompleted) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 20 }}
        className="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-hidden"
      >
        {/* 进度条 */}
        <div className="h-1 bg-gray-100">
          <motion.div
            className="h-full bg-gradient-to-r from-blue-500 to-indigo-600"
            initial={{ width: 0 }}
            animate={{ width: `${((currentStep + 1) / steps.length) * 100}%` }}
            transition={{ duration: 0.3 }}
          />
        </div>

        {/* 内容 */}
        <div className="p-6 sm:p-8">
          {/* 步骤指示器 */}
          <div className="flex items-center justify-center gap-2 mb-6">
            {steps.map((_, index) => (
              <div
                key={index}
                className={`w-2 h-2 rounded-full transition-colors ${
                  index === currentStep
                    ? 'bg-blue-500 w-6'
                    : index < currentStep
                    ? 'bg-blue-300'
                    : 'bg-gray-200'
                }`}
              />
            ))}
          </div>

          {/* 图标 */}
          <div className="flex justify-center mb-6">
            <motion.div
              key={step.id}
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              transition={{ type: 'spring', stiffness: 200, damping: 15 }}
              className="w-20 h-20 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-2xl flex items-center justify-center"
            >
              <step.icon className="w-10 h-10 text-blue-600" />
            </motion.div>
          </div>

          {/* 文字内容 */}
          <div className="text-center mb-8">
            <h2 className="text-xl sm:text-2xl font-bold text-gray-900 mb-3">
              {step.title}
            </h2>
            <p className="text-sm sm:text-base text-gray-600 leading-relaxed">
              {step.description}
            </p>
          </div>

          {/* 操作按钮 */}
          {step.action && (
            <button
              onClick={handleAction}
              className="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-medium transition-colors mb-4 flex items-center justify-center gap-2"
            >
              {step.action}
              <ChevronRight className="w-4 h-4" />
            </button>
          )}

          {/* 导航按钮 */}
          <div className="flex items-center justify-between">
            <button
              onClick={handleSkip}
              className="text-sm text-gray-500 hover:text-gray-700 transition-colors"
            >
              跳过引导
            </button>

            <div className="flex items-center gap-3">
              {currentStep > 0 && (
                <button
                  onClick={handlePrev}
                  className="px-4 py-2 border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50 transition-colors text-sm font-medium"
                >
                  上一步
                </button>
              )}
              <button
                onClick={handleNext}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl transition-colors text-sm font-medium flex items-center gap-2"
              >
                {currentStep === steps.length - 1 ? (
                  <>
                    <CheckCircle className="w-4 h-4" />
                    完成
                  </>
                ) : (
                  <>
                    下一步
                    <ChevronRight className="w-4 h-4" />
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}

// 检查是否需要显示新手引导
export function shouldShowOnboarding(role: 'purchaser' | 'textile' | 'washing'): boolean {
  const completed = localStorage.getItem(`onboarding_completed_${role}`);
  return !completed;
}

// 重置新手引导（用于测试）
export function resetOnboarding(role: 'purchaser' | 'textile' | 'washing') {
  localStorage.removeItem(`onboarding_completed_${role}`);
}
