import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { HelpCircle, X, Search, Keyboard, BookOpen, Zap, MessageSquare, ChevronRight } from 'lucide-react';
import { useResponsive } from '../hooks/useResponsive';

interface HelpCenterProps {
  isOpen: boolean;
  onClose: () => void;
}

type HelpSection = 'guide' | 'shortcuts' | 'faq';

// 快捷键配置
const shortcuts = [
  { key: 'F1', description: '打开帮助中心', scope: '全局' },
  { key: 'Ctrl/Cmd + K', description: '快速搜索', scope: '全局' },
  { key: 'Ctrl/Cmd + N', description: '新建计划', scope: '采购商' },
  { key: 'Esc', description: '关闭弹窗/返回', scope: '全局' },
  { key: 'Tab', description: '切换焦点', scope: '表单' },
  { key: 'Enter', description: '确认/提交', scope: '表单' },
];

// FAQ数据
const faqs = [
  {
    question: '如何创建新的生产计划？',
    answer: '在采购商工作台点击"新建计划"按钮，填写产品信息、纱线配比等必填项后提交即可。',
    role: 'purchaser'
  },
  {
    question: '如何分享计划给纺织厂？',
    answer: '在计划总览页面找到目标计划，点击"分享计划"按钮，通过二次确认后复制链接发送给纺织厂。',
    role: 'purchaser'
  },
  {
    question: '如何确认生产计划？',
    answer: '纺织厂在计划总览页面查看待确认计划，点击"确认计划"按钮即可接受该计划。',
    role: 'textile'
  },
  {
    question: '如何录入坯布入库？',
    answer: '在"已生产坯布"页面，找到对应计划，点击"坯布入库"按钮，填写入库数量和匹数后提交。',
    role: 'textile'
  },
  {
    question: '数据是否安全？',
    answer: '系统采用RLS（行级安全）策略，确保您的数据仅对您和授权用户可见。所有敏感信息都经过加密处理。',
    role: 'all'
  },
  {
    question: '如何修改已拒绝的计划？',
    answer: '当纺织厂拒绝计划后，采购商可在弹窗中点击"修改计划"按钮，系统会自动携带原计划数据跳转到新建页面。',
    role: 'purchaser'
  },
];

// 功能介绍
const features = [
  {
    title: '计划管理',
    description: '创建、分享、跟踪生产计划的全流程管理',
    icon: BookOpen,
    steps: ['创建计划', '分享链接', '工厂确认', '进度跟踪', '完成入库']
  },
  {
    title: '库存管理',
    description: '实时查看和管理坯布、纱线库存',
    icon: Zap,
    steps: ['查看库存', '入库记录', '库存预警', '出入库历史']
  },
  {
    title: '协作沟通',
    description: '与工厂实时协作，消息通知及时送达',
    icon: MessageSquare,
    steps: ['计划分享', '状态变更', '拒绝反馈', '结款确认']
  },
];

export function HelpCenter({ isOpen, onClose }: HelpCenterProps) {
  const { isMobile } = useResponsive();
  const [activeSection, setActiveSection] = useState<HelpSection>('guide');
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);

  // F1快捷键监听
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'F1') {
        e.preventDefault();
        if (!isOpen) {
          // 通过自定义事件触发打开
          window.dispatchEvent(new CustomEvent('open-help-center'));
        }
      }
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };

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

  const filteredFaqs = faqs.filter(faq =>
    faq.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
    faq.answer.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const filteredShortcuts = shortcuts.filter(s =>
    s.key.toLowerCase().includes(searchQuery.toLowerCase()) ||
    s.description.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-3 sm: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-2xl max-h-[85vh] overflow-hidden shadow-2xl"
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-100">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
              <HelpCircle className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900">帮助中心</h2>
              <p className="text-xs text-gray-500">按 F1 快速打开</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 搜索栏 */}
        <div className="px-4 py-3 border-b border-gray-100">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="搜索帮助内容..."
              className="w-full pl-9 pr-4 py-2 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>
        </div>

        {/* 标签切换 */}
        <div className="flex border-b border-gray-100">
          {[
            { id: 'guide', label: '功能介绍', icon: BookOpen },
            { id: 'shortcuts', label: '快捷键', icon: Keyboard },
            { id: 'faq', label: '常见问题', icon: MessageSquare },
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveSection(tab.id as HelpSection)}
              className={`flex-1 flex items-center justify-center gap-2 py-3 text-sm font-medium transition-colors ${
                activeSection === tab.id
                  ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* 内容区域 */}
        <div className="p-4 overflow-y-auto max-h-[50vh]">
          <AnimatePresence mode="wait">
            {/* 功能介绍 */}
            {activeSection === 'guide' && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-4"
              >
                {features.map((feature, index) => (
                  <div key={index} className="bg-gray-50 rounded-xl p-4">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center shadow-sm">
                        <feature.icon className="w-4 h-4 text-blue-600" />
                      </div>
                      <div>
                        <h3 className="font-medium text-gray-900">{feature.title}</h3>
                        <p className="text-xs text-gray-500">{feature.description}</p>
                      </div>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {feature.steps.map((step, i) => (
                        <span key={i} className="inline-flex items-center gap-1 text-xs text-gray-600">
                          {i > 0 && <ChevronRight className="w-3 h-3 text-gray-400" />}
                          <span className="px-2 py-1 bg-white rounded-lg border border-gray-200">{step}</span>
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </motion.div>
            )}

            {/* 快捷键 */}
            {activeSection === 'shortcuts' && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-2"
              >
                {filteredShortcuts.map((shortcut, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-xl">
                    <div>
                      <p className="text-sm text-gray-900">{shortcut.description}</p>
                      <p className="text-xs text-gray-500">{shortcut.scope}</p>
                    </div>
                    <kbd className="px-3 py-1.5 bg-white border border-gray-200 rounded-lg text-xs font-mono text-gray-700 shadow-sm">
                      {shortcut.key}
                    </kbd>
                  </div>
                ))}
                {filteredShortcuts.length === 0 && (
                  <p className="text-center text-gray-500 py-8">未找到匹配的快捷键</p>
                )}
              </motion.div>
            )}

            {/* FAQ */}
            {activeSection === 'faq' && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-2"
              >
                {filteredFaqs.map((faq, index) => (
                  <div key={index} className="border border-gray-200 rounded-xl overflow-hidden">
                    <button
                      onClick={() => setExpandedFaq(expandedFaq === index ? null : index)}
                      className="w-full flex items-center justify-between p-3 text-left hover:bg-gray-50 transition-colors"
                    >
                      <span className="text-sm font-medium text-gray-900">{faq.question}</span>
                      <ChevronRight
                        className={`w-4 h-4 text-gray-400 transition-transform ${
                          expandedFaq === index ? 'rotate-90' : ''
                        }`}
                      />
                    </button>
                    <AnimatePresence>
                      {expandedFaq === index && (
                        <motion.div
                          initial={{ height: 0 }}
                          animate={{ height: 'auto' }}
                          exit={{ height: 0 }}
                          className="overflow-hidden"
                        >
                          <div className="p-3 pt-0 text-sm text-gray-600 bg-gray-50">
                            {faq.answer}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                ))}
                {filteredFaqs.length === 0 && (
                  <p className="text-center text-gray-500 py-8">未找到匹配的问题</p>
                )}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* 底部 */}
        <div className="p-4 border-t border-gray-100 bg-gray-50">
          <p className="text-xs text-gray-500 text-center">
            如需更多帮助，请联系客服或查看用户手册
          </p>
        </div>
      </motion.div>
    </div>
  );
}

// 帮助按钮组件（放在通知中心旁边）
export function HelpButton({ onClick }: { onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="w-10 h-10 rounded-xl bg-blue-100 hover:bg-blue-200 flex items-center justify-center transition-colors"
      title="帮助中心 (F1)"
    >
      <HelpCircle className="w-5 h-5 text-blue-600" />
    </button>
  );
}

// 全局帮助中心状态管理
export function useHelpCenter() {
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    const handleOpen = () => setIsOpen(true);
    window.addEventListener('open-help-center', handleOpen);
    return () => window.removeEventListener('open-help-center', handleOpen);
  }, []);

  return { isOpen, setIsOpen };
}
