import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, BookOpen, FileText, Download, ExternalLink, ChevronRight, Search, ChevronLeft } from 'lucide-react';

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

// 手册章节
const manualChapters = [
  {
    id: 'getting-started',
    title: '快速入门',
    icon: BookOpen,
    sections: [
      { title: '系统介绍', content: '昱森纺织管理系统是一款专为纺织行业设计的全流程协作平台，连接采购商、纺织厂和水洗厂三方。' },
      { title: '账号注册', content: '首次使用需要注册账号，选择您的角色（采购商/纺织厂/水洗厂），填写公司信息即可完成注册。' },
      { title: '登录系统', content: '使用注册时的用户名和密码登录系统，支持记住密码功能。' },
    ]
  },
  {
    id: 'purchaser-guide',
    title: '采购商指南',
    icon: FileText,
    sections: [
      { title: '创建生产计划', content: '点击"新建计划"按钮，填写产品名称、颜色、坯布码、色号、计划产量等信息，配置纱线配比后提交。' },
      { title: '分享计划', content: '在计划总览页面，点击"分享计划"按钮，通过二次确认后将链接发送给纺织厂。纺织厂确认后即建立关联。' },
      { title: '查看进度', content: '在计划总览页面实时查看各工厂的生产进度，包括当前环节、完成米数、入库记录等。' },
      { title: '库存管理', content: '在"产品信息"中管理所有入库的坯布，支持按产品名称、克重、颜色分组查看，可查询出入库历史。' },
      { title: '结款管理', content: '生产完成后，在"待结款"页面查看应付款项，确认后完成结款流程。' },
    ]
  },
  {
    id: 'textile-guide',
    title: '纺织厂指南',
    icon: FileText,
    sections: [
      { title: '导入计划', content: '通过采购商分享的链接或剪贴板导入计划，确认计划详情后即可开始生产。' },
      { title: '确认生产流程', content: '按计划流程逐步确认：确认计划 → 采纱 → 染纱 → 上机 → 坯布入库。每个环节完成后点击确认。' },
      { title: '坯布入库', content: '在"已生产坯布"页面，找到对应计划，点击"坯布入库"，填写入库米数和匹数。' },
      { title: '纱线库存', content: '在"原料纱仓库"中管理纱线库存，设置最低库存预警，及时补充原料。' },
      { title: '查看待结款', content: '在"待结款"页面查看采购商应付款项，确认收款后标记为已结款。' },
    ]
  },
  {
    id: 'washing-guide',
    title: '水洗厂指南',
    icon: FileText,
    sections: [
      { title: '接收水洗订单', content: '通过分享链接接收水洗订单，确认订单详情后开始水洗流程。' },
      { title: '水洗流程管理', content: '按流程确认各环节的完成情况，包括接收、水洗、烘干、质检、出库等。' },
    ]
  },
  {
    id: 'faq',
    title: '常见问题',
    icon: BookOpen,
    sections: [
      { title: '忘记密码怎么办？', content: '请联系系统管理员重置密码，或拨打客服电话：400-xxx-xxxx。' },
      { title: '如何修改公司信息？', content: '在账号管理页面可以修改公司名称、地址、联系电话等信息。' },
      { title: '数据安全吗？', content: '系统采用RLS（行级安全）策略，确保您的数据仅对您和授权用户可见。所有敏感信息都经过加密处理。' },
      { title: '支持哪些浏览器？', content: '推荐使用Chrome 90+、Safari 14+、Firefox 88+、Edge 90+等现代浏览器。' },
      { title: '如何联系客服？', content: '点击右上角"反馈"按钮提交问题，或发送邮件至 support@yusen.com。' },
    ]
  },
];

export function UserManual({ isOpen, onClose }: UserManualProps) {
  const [activeChapter, setActiveChapter] = useState(manualChapters[0]);
  const [expandedSection, setExpandedSection] = useState<number | null>(0);
  const [searchQuery, setSearchQuery] = useState('');
  const [showChapterList, setShowChapterList] = useState(true);

  // 搜索过滤
  const filteredChapters = searchQuery
    ? manualChapters.map(ch => ({
        ...ch,
        sections: ch.sections.filter(s =>
          s.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          s.content.toLowerCase().includes(searchQuery.toLowerCase())
        )
      })).filter(ch => ch.sections.length > 0)
    : manualChapters;

  const handleChapterSelect = (chapter: typeof manualChapters[0]) => {
    setActiveChapter(chapter);
    setExpandedSection(0);
    setShowChapterList(false);
  };

  const handleBackToChapters = () => {
    setShowChapterList(true);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-0 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 w-full h-full sm:h-auto sm:max-h-[90vh] sm:rounded-2xl sm:max-w-4xl overflow-hidden shadow-2xl"
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-3 sm:p-4 border-b border-gray-100">
          <div className="flex items-center gap-2 sm:gap-3">
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-blue-100 rounded-xl flex items-center justify-center">
              <BookOpen className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
            </div>
            <div>
              <h2 className="text-base sm:text-lg font-semibold text-gray-900">用户手册</h2>
              <p className="text-xs text-gray-500 hidden sm:block">详细的使用指南和操作说明</p>
            </div>
          </div>
          <div className="flex items-center gap-1 sm:gap-2">
            <button
              onClick={() => window.open('/manual.pdf', '_blank')}
              className="flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 text-xs sm:text-sm text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
            >
              <Download className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
              <span className="hidden sm:inline">下载PDF</span>
              <span className="sm:hidden">下载</span>
            </button>
            <button
              onClick={onClose}
              className="p-1.5 sm:p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <X className="w-4 h-4 sm:w-5 sm:h-5 text-gray-500" />
            </button>
          </div>
        </div>

        {/* 搜索栏 */}
        <div className="px-3 sm:px-4 py-2 sm:py-3 border-b border-gray-100 bg-gray-50">
          <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-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
            />
          </div>
        </div>

        {/* 移动端章节导航栏 */}
        {!showChapterList && (
          <div className="sm:hidden flex items-center gap-2 px-3 py-2 border-b border-gray-100 bg-gray-50">
            <button
              onClick={handleBackToChapters}
              className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
            >
              <ChevronLeft className="w-4 h-4" />
              返回目录
            </button>
            <span className="text-gray-400">|</span>
            <span className="text-sm font-medium text-gray-700 truncate">{activeChapter.title}</span>
          </div>
        )}

        {/* 内容区域 */}
        <div className="flex h-[calc(100vh-140px)] sm:h-[60vh]">
          {/* 左侧章节列表 - 移动端全屏显示，桌面端固定宽度 */}
          <AnimatePresence mode="wait">
            {(showChapterList || window.innerWidth >= 640) && (
              <motion.div
                initial={{ x: -100, opacity: 0 }}
                animate={{ x: 0, opacity: 1 }}
                exit={{ x: -100, opacity: 0 }}
                className={`${showChapterList ? 'flex' : 'hidden sm:flex'} w-full sm:w-64 border-r border-gray-100 overflow-y-auto bg-gray-50/50 flex-col`}
              >
                <div className="p-2 space-y-1">
                  {filteredChapters.map((chapter) => (
                    <button
                      key={chapter.id}
                      onClick={() => handleChapterSelect(chapter)}
                      className={`w-full flex items-center gap-3 px-3 py-3 text-left transition-colors rounded-xl ${
                        activeChapter.id === chapter.id
                          ? 'bg-blue-50 text-blue-700 border-l-4 border-blue-500'
                          : 'text-gray-700 hover:bg-gray-100'
                      }`}
                    >
                      <chapter.icon className={`w-5 h-5 shrink-0 ${activeChapter.id === chapter.id ? 'text-blue-600' : 'text-gray-400'}`} />
                      <div className="flex-1 min-w-0">
                        <span className="text-sm font-medium block">{chapter.title}</span>
                        <span className="text-xs text-gray-400 block mt-0.5">{chapter.sections.length} 个章节</span>
                      </div>
                      <ChevronRight className={`w-4 h-4 shrink-0 ${activeChapter.id === chapter.id ? 'text-blue-500' : 'text-gray-300'}`} />
                    </button>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 右侧内容详情 */}
          <div className={`${!showChapterList ? 'flex' : 'hidden sm:flex'} flex-1 overflow-y-auto bg-white flex-col w-full`}>
            <div className="p-4 sm:p-6">
              {/* 章节标题 */}
              <div className="flex items-center gap-3 mb-4 sm:mb-6">
                <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center">
                  <activeChapter.icon className="w-5 h-5 sm:w-6 sm:h-6 text-white" />
                </div>
                <div>
                  <h3 className="text-lg sm:text-xl font-bold text-gray-900">{activeChapter.title}</h3>
                  <p className="text-xs sm:text-sm text-gray-500">{activeChapter.sections.length} 个操作指南</p>
                </div>
              </div>

              {/* 章节内容列表 */}
              <div className="space-y-2 sm:space-y-3">
                {activeChapter.sections.map((section, index) => (
                  <div
                    key={index}
                    className="border border-gray-200 rounded-xl overflow-hidden bg-white shadow-sm"
                  >
                    <button
                      onClick={() => setExpandedSection(expandedSection === index ? null : index)}
                      className="w-full flex items-center justify-between p-3 sm:p-4 text-left hover:bg-gray-50 transition-colors"
                    >
                      <div className="flex items-center gap-2 sm:gap-3">
                        <span className="w-5 h-5 sm:w-6 sm:h-6 bg-gray-100 text-gray-600 rounded-full flex items-center justify-center text-xs sm:text-sm font-medium shrink-0">
                          {index + 1}
                        </span>
                        <span className="font-medium text-gray-900 text-sm sm:text-base">{section.title}</span>
                      </div>
                      <ChevronRight
                        className={`w-4 h-4 sm:w-5 sm:h-5 text-gray-400 transition-transform shrink-0 ${
                          expandedSection === index ? 'rotate-90' : ''
                        }`}
                      />
                    </button>
                    <AnimatePresence>
                      {expandedSection === index && (
                        <motion.div
                          initial={{ height: 0, opacity: 0 }}
                          animate={{ height: 'auto', opacity: 1 }}
                          exit={{ height: 0, opacity: 0 }}
                          transition={{ duration: 0.2 }}
                          className="overflow-hidden"
                        >
                          <div className="p-3 sm:p-4 pt-0 text-sm text-gray-600 leading-relaxed border-t border-gray-100 bg-gray-50/30">
                            {section.content}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}

// 用户手册入口按钮（用于账号管理页面）
export function UserManualButton({ onClick }: { onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="flex items-center gap-3 w-full px-4 py-3 text-left hover:bg-gray-50 rounded-xl transition-colors"
    >
      <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
        <BookOpen className="w-5 h-5 text-blue-600" />
      </div>
      <div className="flex-1">
        <p className="font-medium text-gray-900">用户手册</p>
        <p className="text-xs text-gray-500">查看详细使用指南</p>
      </div>
      <ExternalLink className="w-4 h-4 text-gray-400" />
    </button>
  );
}
