import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useParams, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ChevronLeft, Plus, Sparkles, Send, Check, X, XCircle, Clock,
  Trash2, Edit2, FileText, Loader2, BookOpen, Brain,
  AlertCircle, Hash, Layers
} from 'lucide-react';
import { questionBankService, QuestionBank, QuestionBankItem, CreateQuestionBankItemDto } from '../../services/questionBankService';
import { templateService } from '../../services/templateService';
import { AssessmentTemplate } from '../../types';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '../../contexts/ConfirmContext';
import { useLanguage } from '../../contexts/LanguageContext';

const QUESTION_TYPES = [
  { value: 'SHORT_ANSWER', labelKey: 'shortAnswer' as const },
  { value: 'MULTIPLE_CHOICE', labelKey: 'multipleChoice' as const },
  { value: 'TRUE_FALSE', labelKey: 'trueFalse' as const },
];

const DIFFICULTIES = [
  { value: 'STANDARD', labelKey: 'standard' as const },
  { value: 'ADVANCED', labelKey: 'advanced' as const },
  { value: 'SPECIALIST', labelKey: 'specialist' as const },
];

type TypeIcon = { [key: string]: React.ReactNode };
const typeIcons: TypeIcon = {
  SHORT_ANSWER: <FileText size={12} />,
  MULTIPLE_CHOICE: <Layers size={12} />,
  TRUE_FALSE: <Check size={12} />,
};

export default function QuestionBankDetailView() {
  const { id: bankId } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useLanguage();
  const { showSuccess, showError } = useToast();
  const { confirm } = useConfirm();

  if (!bankId) {
    return (
      <div className="p-6">
        <button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors mb-4">
          <ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
        </button>
        <div className="flex items-center gap-2 text-red-500 bg-red-50 rounded-2xl p-4 border border-red-100">
          <AlertCircle size={18} /><span className="text-sm font-bold">{t('invalidBankId')}</span>
        </div>
      </div>
    );
  }

  const [bank, setBank] = useState<QuestionBank | null>(null);
  const [items, setItems] = useState<QuestionBankItem[]>([]);
  const [templates, setTemplates] = useState<AssessmentTemplate[]>([]);
  const [template, setTemplate] = useState<AssessmentTemplate | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const [showAddItem, setShowAddItem] = useState(false);
  const [showGenerate, setShowGenerate] = useState(false);
  const [editingItem, setEditingItem] = useState<QuestionBankItem | null>(null);

  const [itemForm, setItemForm] = useState<CreateQuestionBankItemDto>({
    questionText: '',
    questionType: 'SHORT_ANSWER',
    keyPoints: [],
    difficulty: 'STANDARD',
    dimension: 'WORK_CAPABILITY',
  });
  const [keyPointsInput, setKeyPointsInput] = useState('');

  const [generateForm, setGenerateForm] = useState({ count: 5, knowledgeBaseContent: '' });
  const [generating, setGenerating] = useState(false);
  const [selectedItemIds, setSelectedItemIds] = useState<Set<string>>(new Set());

  const selectableItems = items.filter(i => i.status === 'PENDING_REVIEW');
  const allSelected = selectableItems.length > 0 && selectableItems.every(i => selectedItemIds.has(i.id));

  const toggleSelectAll = () => {
    if (allSelected) {
      setSelectedItemIds(new Set());
    } else {
      setSelectedItemIds(new Set(selectableItems.map(i => i.id)));
    }
  };

  const toggleSelectItem = (itemId: string) => {
    setSelectedItemIds(prev => {
      const next = new Set(prev);
      if (next.has(itemId)) next.delete(itemId); else next.add(itemId);
      return next;
    });
  };

  const handleBatchApprove = async () => {
    const ids = Array.from(selectedItemIds);
    if (ids.length === 0) return;
    try {
      await questionBankService.batchReviewItems(bankId, ids, true);
      showSuccess(`已通过 ${ids.length} 道题目`);
      setSelectedItemIds(new Set());
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const handleBatchReject = async () => {
    const ids = Array.from(selectedItemIds);
    if (ids.length === 0) return;
    try {
      await questionBankService.batchReviewItems(bankId, ids, false);
      showSuccess(`已驳回 ${ids.length} 道题目`);
      setSelectedItemIds(new Set());
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  useEffect(() => { fetchData(); fetchTemplates(); }, [bankId]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const bankData = await questionBankService.getBank(bankId);
      setBank(bankData);
      const itemsData = await questionBankService.getBankItems(bankId);
      setItems(itemsData);
    } catch (err: any) {
      setError(err.message || t('actionFailed'));
      showError(err.message || t('actionFailed'));
    } finally {
      setLoading(false);
    }
  };

  const fetchTemplates = async () => {
    try {
      const data = await templateService.getAll();
      setTemplates(data);
      const bankData = await questionBankService.getBank(bankId);
      if (bankData.templateId) {
        const tpl = data.find(tpl => tpl.id === bankData.templateId);
        setTemplate(tpl || null);
      }
    } catch {
      // silent
    }
  };

  const openGenerateModal = () => {
    setShowGenerate(true);
    setGenerateForm({ count: 5, knowledgeBaseContent: '' });
  };

  const dimensionOptions = template?.dimensions?.map(d => ({ value: d.name || d.label, label: d.label || d.name }))
    || [
      { value: 'PROMPT', label: 'Prompt' },
      { value: 'LLM', label: 'LLM' },
      { value: 'IDE', label: 'IDE' },
      { value: 'DEV_PATTERN', label: 'Dev Pattern' },
      { value: 'WORK_CAPABILITY', label: 'Work Capability' },
    ];

  const handleCreateItem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!itemForm.questionText.trim()) return;
    setSaving(true);
    try {
      await questionBankService.createItem(bankId, { ...itemForm, keyPoints: keyPointsInput.split('\n').filter(k => k.trim()) });
      closeItemForm();
      showSuccess(t('questionAdded'));
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed'));
    } finally { setSaving(false); }
  };

  const handleUpdateItem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingItem || !itemForm.questionText.trim()) return;
    setSaving(true);
    try {
      await questionBankService.updateItem(bankId, editingItem.id, { ...itemForm, keyPoints: keyPointsInput.split('\n').filter(k => k.trim()) });
      closeItemForm();
      showSuccess(t('questionUpdated'));
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed'));
    } finally { setSaving(false); }
  };

  const handleDeleteItem = async (itemId: string) => {
    const ok = await confirm({ message: t('confirmDeleteQuestion'), confirmLabel: t('delete'), cancelLabel: t('cancel') });
    if (!ok) return;
    try { await questionBankService.deleteItem(bankId, itemId); showSuccess(t('questionDeleted')); fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const handleGenerate = async () => {
    setGenerating(true);
    try {
      await questionBankService.generateQuestions(bankId, generateForm.count, generateForm.knowledgeBaseContent);
      setShowGenerate(false);
      setGenerateForm({ count: 5, knowledgeBaseContent: '' });
      showSuccess(t('generatedQuestions').replace('$1', String(generateForm.count)));
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed'));
    } finally { setGenerating(false); }
  };

  const handleSubmitForReview = async () => {
    const ok = await confirm({ message: t('confirmSubmitReview'), confirmLabel: t('submitForReview'), cancelLabel: t('cancel') });
    if (!ok) return;
    try { await questionBankService.submitForReview(bankId); showSuccess(t('bankSubmittedForReview')); fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const handlePublish = async () => {
    const isPendingReview = bank?.status === 'PENDING_REVIEW';
    const label = isPendingReview ? t('approve') : t('republish');
    const msg = isPendingReview ? t('confirmApproveBank') : t('confirmRepublishBank');
    const ok = await confirm({ message: msg, confirmLabel: label, cancelLabel: t('cancel') });
    if (!ok) return;
    try {
      if (isPendingReview) await questionBankService.approveBank(bankId);
      else await questionBankService.publishBank(bankId);
      showSuccess(isPendingReview ? t('bankApproved') : t('bankRepublished'));
      fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const handleApproveItem = async (itemId: string) => {
    try { await questionBankService.updateItem(bankId, itemId, { status: 'PUBLISHED' } as any); showSuccess(t('questionApproved')); fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const handleRejectItem = async (itemId: string) => {
    try { await questionBankService.batchReviewItems(bankId, [itemId], false); showSuccess(t('questionReturned')); fetchData();
    } catch (err: any) { showError(err.message || t('actionFailed')); }
  };

  const openEditItem = (item: QuestionBankItem) => {
    setEditingItem(item);
    setItemForm({ questionText: item.questionText, questionType: item.questionType, options: item.options || [], keyPoints: item.keyPoints, difficulty: item.difficulty, dimension: item.dimension });
    setKeyPointsInput(item.keyPoints.join('\n'));
    setShowAddItem(true);
  };

  const closeItemForm = () => { setShowAddItem(false); setEditingItem(null); };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600 opacity-20" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-4">
        <button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors">
          <ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
        </button>
        <div className="flex items-center gap-3 text-red-500 bg-red-50 rounded-2xl p-6 border border-red-100">
          <AlertCircle size={20} /><span className="text-sm font-bold">{error}</span>
          <button onClick={fetchData} className="ml-auto text-xs font-black text-red-600 hover:text-red-700 uppercase tracking-widest">{t('retry')}</button>
        </div>
      </div>
    );
  }

  const pendingItems = items.filter(i => i.status === 'PENDING_REVIEW');
  const publishedItems = items.filter(i => i.status === 'PUBLISHED');

  const statusColors: Record<string, { bg: string; text: string; border: string; label: string; blur: string; icon: React.ReactNode }> = {
    PUBLISHED: { bg: 'bg-emerald-50', text: 'text-emerald-600', border: 'border-emerald-200/50', label: t('published'), blur: 'bg-emerald-500/5', icon: <Check size={12} /> },
    PENDING_REVIEW: { bg: 'bg-amber-50', text: 'text-amber-600', border: 'border-amber-200/50', label: t('pendingReview'), blur: 'bg-amber-500/5', icon: <Clock size={12} /> },
    DRAFT: { bg: 'bg-slate-50', text: 'text-slate-500', border: 'border-slate-200/50', label: t('draft'), blur: 'bg-blue-500/5', icon: <FileText size={12} /> },
    REJECTED: { bg: 'bg-red-50', text: 'text-red-500', border: 'border-red-200/50', label: t('rejected'), blur: 'bg-red-500/5', icon: <XCircle size={12} /> },
  };

  const bankStatus = statusColors[bank?.status || 'DRAFT'] || statusColors.DRAFT;

  const statCards = [
    { label: t('questionList'), value: items.length, icon: <FileText size={18} />, classes: 'bg-slate-50 border-slate-200/50 text-slate-700' },
    { label: t('published'), value: publishedItems.length, icon: <Check size={18} />, classes: 'bg-emerald-50 border-emerald-200/50 text-emerald-700' },
    { label: t('pendingReview'), value: pendingItems.length, icon: <Clock size={18} />, classes: 'bg-amber-50 border-amber-200/50 text-amber-700' },
  ];

  return (
    <div className="space-y-6 overflow-y-auto h-full">
      <button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors">
        <ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
      </button>

      <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center shadow-sm shrink-0"><BookOpen size={28} /></div>
          <div>
            <h1 className="text-2xl font-black text-slate-900">{bank?.name}</h1>
            <p className="text-sm text-slate-500 mt-1">{bank?.description || t('noDescription')}</p>
            <div className="flex items-center gap-3 mt-2 flex-wrap">
              {template && (
                <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-bold rounded-lg border border-purple-100/50">
                  <Brain size={12} />{template.name}
                </span>
              )}
              <span className={`inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full border ${bankStatus.bg} ${bankStatus.text} ${bankStatus.border}`}>
                {bankStatus.icon}{bankStatus.label}
              </span>
            </div>
          </div>
        </div>

        <div className="flex gap-2 shrink-0">
          {bank?.status === 'DRAFT' && (
            <button onClick={handleSubmitForReview} className="px-5 py-3 bg-amber-500 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-amber-100 hover:bg-amber-600 transition-all active:scale-95">
              <Send size={16} /> {t('submitForReview')}
            </button>
          )}
          {(bank?.status === 'PENDING_REVIEW' || bank?.status === 'REJECTED') && (
            <button onClick={handlePublish} className="px-5 py-3 bg-emerald-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-emerald-100 hover:bg-emerald-700 transition-all active:scale-95">
              <Check size={16} /> {bank?.status === 'PENDING_REVIEW' ? t('approve') : t('republish')}
            </button>
          )}
          <button onClick={openGenerateModal} className="px-5 py-3 bg-purple-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-purple-100 hover:bg-purple-700 transition-all active:scale-95">
            <Sparkles size={16} /> {t('aiGenerate')}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {statCards.map((stat, i) => (
          <motion.div key={stat.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.08 }}
            className={`rounded-2xl border p-4 ${stat.classes}`}>
            <div className="flex items-center justify-between mb-2">
              <span className="text-[10px] font-black uppercase tracking-widest opacity-70">{stat.label}</span>
              {stat.icon}
            </div>
            <div className="text-3xl font-black">{stat.value}</div>
          </motion.div>
        ))}
      </div>

      <div className="flex items-center justify-between">
        <h2 className="text-lg font-black text-slate-900">{t('questionList')}</h2>
        <div className="flex items-center gap-2">
          {selectedItemIds.size > 0 && (
            <>
              <button onClick={handleBatchApprove}
                className="px-4 py-2.5 bg-emerald-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-emerald-100 hover:bg-emerald-700 transition-all active:scale-95">
                <Check size={14} /> 通过所选 ({selectedItemIds.size})
              </button>
              <button onClick={handleBatchReject}
                className="px-4 py-2.5 bg-red-500 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-red-100 hover:bg-red-600 transition-all active:scale-95">
                <X size={14} /> 驳回所选
              </button>
            </>
          )}
          <button onClick={toggleSelectAll}
            className="px-4 py-2.5 bg-slate-100 text-slate-600 rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 hover:bg-slate-200 transition-all">
            {allSelected ? '取消全选' : '全选'}
          </button>
          <button onClick={() => { setShowAddItem(true); setEditingItem(null); setKeyPointsInput(''); setItemForm({ questionText: '', questionType: 'SHORT_ANSWER', keyPoints: [], difficulty: 'STANDARD', dimension: (dimensionOptions[0]?.value as any) || 'WORK_CAPABILITY' }); }}
            className="px-5 py-3 bg-blue-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-blue-100 hover:bg-blue-700 transition-all active:scale-95">
            <Plus size={16} /> {t('addQuestion')}
          </button>
        </div>
      </div>

      {items.length === 0 ? (
        <div className="bg-slate-50 rounded-[2rem] border-2 border-dashed border-slate-200 p-16 text-center">
          <div className="w-14 h-14 bg-slate-100 rounded-2xl flex items-center justify-center mx-auto mb-4"><FileText size={28} className="text-slate-300" /></div>
          <p className="text-slate-400 font-black uppercase tracking-widest text-xs mb-1">{t('noQuestions')}</p>
          <p className="text-slate-300 text-xs">{t('noQuestionsDesc')}</p>
        </div>
      ) : (
        <div className="space-y-4">
          <AnimatePresence mode="popLayout">
            {items.map((item, idx) => {
              const itemStat = item.status === 'PUBLISHED' ? statusColors.PUBLISHED : statusColors.PENDING_REVIEW;
              return (
                <motion.div key={item.id} layout initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
                  transition={{ delay: Math.min(idx * 0.03, 0.3) }}
                  className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all group relative overflow-hidden">
                  <div className={`absolute top-0 right-0 w-40 h-40 rounded-full blur-3xl -mr-20 -mt-20 ${itemStat.blur}`} />
                  <div className="relative z-10 flex items-start justify-between">
                    {item.status === 'PENDING_REVIEW' && (
                      <input type="checkbox" checked={selectedItemIds.has(item.id)}
                        onChange={() => toggleSelectItem(item.id)}
                        className="mt-1.5 mr-3 w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 shrink-0 cursor-pointer" />
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2.5 flex-wrap">
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-slate-50 text-slate-600 text-[10px] font-bold rounded-lg border border-slate-100">{typeIcons[item.questionType]}{t(QUESTION_TYPES.find(qt => qt.value === item.questionType)?.labelKey || 'shortAnswer')}</span>
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-50 text-blue-600 text-[10px] font-bold rounded-lg border border-blue-100"><Hash size={10} />{t(DIFFICULTIES.find(d => d.value === item.difficulty)?.labelKey || 'standard')}</span>
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-bold rounded-lg border border-purple-100"><Brain size={10} />{dimensionOptions.find(d => d.value === item.dimension)?.label || item.dimension}</span>
                        <span className={`inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full border ${itemStat.bg} ${itemStat.text} ${itemStat.border}`}>{itemStat.icon}{itemStat.label}</span>
                      </div>
                      <p className="font-bold text-slate-900 leading-relaxed">{item.questionText}</p>
                      {item.questionType === 'MULTIPLE_CHOICE' && item.options && item.options.length > 0 && (
                        <div className="mt-3 space-y-1.5 pl-1 border-l-2 border-blue-200">
                          {item.options.map((opt, i) => {
                            const letter = String.fromCharCode(65 + i);
                            const isCorrect = item.correctAnswer === letter;
                            return (
                              <div key={i} className={`flex items-center gap-2 px-3 py-2 rounded-xl text-sm ${isCorrect ? 'bg-emerald-50 border border-emerald-200' : 'bg-slate-50'}`}>
                                <span className={`inline-flex items-center justify-center w-6 h-6 rounded-lg text-[10px] font-black shrink-0 ${isCorrect ? 'bg-emerald-500 text-white' : 'bg-slate-200 text-slate-500'}`}>{letter}</span>
                                <span className={`font-medium ${isCorrect ? 'text-emerald-700' : 'text-slate-600'}`}>{opt}</span>
                                {isCorrect && <Check size={14} className="text-emerald-500 shrink-0 ml-auto" />}
                              </div>
                            );
                          })}
                        </div>
                      )}
                      {item.judgment && (
                        <div className="mt-3 bg-blue-50/50 border border-blue-100 rounded-xl p-3">
                          <span className="text-[10px] font-black text-blue-400 uppercase tracking-widest">{item.questionType === 'MULTIPLE_CHOICE' ? '解析' : '判定依据'}</span>
                          <p className="text-xs text-slate-600 mt-1 leading-relaxed">{item.judgment}</p>
                        </div>
                      )}
                      {item.questionType === 'SHORT_ANSWER' && item.followupHints && item.followupHints.length > 0 && (
                        <div className="mt-2 flex flex-wrap gap-1.5 items-center">
                          <span className="text-[10px] font-black text-purple-400 uppercase tracking-widest">追问方向</span>
                          {item.followupHints.map((hint, i) => <span key={i} className="px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-medium rounded-lg border border-purple-100/50">#{i + 1} {hint}</span>)}
                        </div>
                      )}
                      {item.keyPoints.length > 0 && (
                        <div className="mt-3 flex flex-wrap gap-1.5 items-center">
                          <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mr-1">{t('gradingPoints')}</span>
                          {item.keyPoints.map((kp, i) => <span key={i} className="px-2.5 py-1 bg-amber-50 text-amber-700 text-[10px] font-bold rounded-lg border border-amber-100/50">{kp}</span>)}
                        </div>
                      )}
                      {item.basis && (
                        <div className="mt-2 flex items-center gap-1.5 text-[10px] text-slate-400"><FileText size={10} /><span className="font-medium">{t('basis')}</span><span>{item.basis}</span></div>
                      )}
                    </div>
                    <div className="flex items-center gap-1 ml-4 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                      {item.status === 'PENDING_REVIEW' && (<>
                        <button onClick={() => handleApproveItem(item.id)} className="p-2 text-emerald-600 hover:bg-emerald-50 rounded-xl transition-all" title={t('approve')}><Check size={15} /></button>
                        <button onClick={() => handleRejectItem(item.id)} className="p-2 text-red-500 hover:bg-red-50 rounded-xl transition-all" title={t('rejected')}><X size={15} /></button>
                      </>)}
                      <button onClick={() => openEditItem(item)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-all" title={t('edit')}><Edit2 size={15} /></button>
                      <button onClick={() => handleDeleteItem(item.id)} className="p-2 text-red-500 hover:bg-red-50 rounded-xl transition-all" title={t('delete')}><Trash2 size={15} /></button>
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </AnimatePresence>
        </div>
      )}

      {createPortal(
        <AnimatePresence>
          {(showAddItem || editingItem) && (
            <div key="question-item-modal" className="fixed inset-0 z-[1000] flex items-center justify-center p-4">
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={closeItemForm} className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm" />
              <motion.div initial={{ opacity: 0, scale: 0.9, y: 20 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.9, y: 20 }}
                className="w-full max-w-xl bg-white rounded-[2.5rem] shadow-2xl relative z-10 overflow-hidden">
                <div className="p-8 pb-4 flex items-center justify-between border-b border-slate-100">
                  <div className="flex items-center gap-3"><div className="w-12 h-12 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center">{editingItem ? <Edit2 size={24} /> : <Plus size={24} />}</div>
                    <h3 className="text-xl font-black text-slate-900">{editingItem ? t('editQuestion') : t('addQuestionTitle')}</h3></div>
                  <button onClick={closeItemForm} className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-xl transition-all"><X size={20} /></button>
                </div>
                <form id="item-form" onSubmit={editingItem ? handleUpdateItem : handleCreateItem} className="p-8 space-y-5">
                  <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><FileText size={12} className="text-blue-500" /> {t('questionContent')} <span className="text-red-500">*</span></label>
                    <textarea value={itemForm.questionText} onChange={(e) => setItemForm({...itemForm, questionText: e.target.value})} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300" placeholder={t('questionContent')} rows={3} required />
                  </div>
                  <div className="grid grid-cols-2 gap-5">
                    <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Layers size={12} className="text-blue-500" /> {t('questionType')}</label>
                      <select value={itemForm.questionType} onChange={(e) => setItemForm({...itemForm, questionType: e.target.value as any})} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">{ QUESTION_TYPES.map(qt => <option key={qt.value} value={qt.value}>{t(qt.labelKey)}</option>) }</select>
                    </div>
                    <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-blue-500" /> {t('difficultyDistribution')}</label>
                      <select value={itemForm.difficulty} onChange={(e) => setItemForm({...itemForm, difficulty: e.target.value as any})} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">{ DIFFICULTIES.map(d => <option key={d.value} value={d.value}>{t(d.labelKey)}</option>) }</select>
                    </div>
                  </div>
                  <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Brain size={12} className="text-blue-500" /> {t('dimension')}</label>
                    <select value={itemForm.dimension} onChange={(e) => setItemForm({...itemForm, dimension: e.target.value as any})} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">{ dimensionOptions.map(d => <option key={d.value} value={d.value}>{d.label}</option>) }</select>
                  </div>
                  <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><AlertCircle size={12} className="text-blue-500" /> {t('gradingPoints')}</label>
                    <textarea value={keyPointsInput} onChange={(e) => setKeyPointsInput(e.target.value)} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300" placeholder={'1\n2\n3'} rows={4} />
                  </div>
                  <div className="flex justify-end gap-3 pt-4">
                    <button type="button" onClick={closeItemForm} className="px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors">{t('cancel')}</button>
                    <button type="submit" form="item-form" disabled={saving} className="px-10 py-4 bg-blue-600 text-white rounded-[1.25rem] font-black uppercase tracking-widest text-xs shadow-xl shadow-blue-100 hover:bg-blue-700 transition-all active:scale-95 flex items-center gap-2">{saving && <Loader2 size={16} className="animate-spin" />}{saving ? t('saving') : (editingItem ? t('save') : t('addQuestion'))}</button>
                  </div>
                </form>
              </motion.div>
            </div>
          )}
        </AnimatePresence>, document.body
      )}

      {createPortal(
        <AnimatePresence>
          {showGenerate && (
            <div key="generate-modal" className="fixed inset-0 z-[1000] flex items-center justify-center p-4">
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setShowGenerate(false)} className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm" />
              <motion.div initial={{ opacity: 0, scale: 0.9, y: 20 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.9, y: 20 }}
                className="w-full max-w-md bg-white rounded-[2.5rem] shadow-2xl relative z-10 overflow-hidden">
                <div className="p-8 pb-4 flex items-center justify-between border-b border-slate-100">
                  <div className="flex items-center gap-3"><div className="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center"><Sparkles size={24} /></div>
                    <h3 className="text-xl font-black text-slate-900">{t('aiGenerateTitle')}</h3></div>
                  <button onClick={() => setShowGenerate(false)} className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-xl transition-all"><X size={20} /></button>
                </div>
                <div className="p-8 space-y-5">
                  <div className="space-y-1.5"><label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-purple-500" /> {t('generateCount')}</label>
                    <input type="number" value={generateForm.count} onChange={(e) => setGenerateForm({...generateForm, count: parseInt(e.target.value) || 5})} className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-purple-500/10 focus:border-purple-500/50 outline-none transition-all" min={1} max={20} />
                  </div>
                  <p className="text-[10px] text-slate-400 px-1">知识库内容已自动加载</p>
                  <div className="flex gap-3 pt-4">
                    <button onClick={() => setShowGenerate(false)} className="flex-1 px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors">{t('cancel')}</button>
                    <button onClick={handleGenerate} disabled={generating} className="flex-1 px-6 py-4 bg-purple-600 text-white rounded-[1.25rem] font-black uppercase tracking-widest text-xs shadow-xl shadow-purple-100 hover:bg-purple-700 transition-all active:scale-95 flex items-center justify-center gap-2">
                      {generating ? <><Loader2 size={16} className="animate-spin" /> {t('generating')}</> : <><Sparkles size={16} /> {t('generate')}</>}</button>
                  </div>
                </div>
              </motion.div>
            </div>
          )}
        </AnimatePresence>, document.body
      )}
    </div>
  );
}
