import { useEffect, useMemo, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import {
  loadContentEntries,
  loadContentNodes,
  loadPracticeBlueprints,
  loadQuestionCollections,
  type ContentEntry,
  type ContentNode,
  type PracticeBlueprint,
  type QuestionCollection,
} from '@/services/catalog';
import '../student.css';

export default function StudentCatalogPage() {
  const router = useRouter();
  const query = router.params || {};
  const [entries, setEntries] = useState<ContentEntry[]>([]);
  const [selectedEntryId, setSelectedEntryId] = useState(query.entryId || '');
  const [nodes, setNodes] = useState<ContentNode[]>([]);
  const [selectedNodeId, setSelectedNodeId] = useState(query.nodeId || '');
  const [collections, setCollections] = useState<QuestionCollection[]>([]);
  const [blueprints, setBlueprints] = useState<PracticeBlueprint[]>([]);
  const [error, setError] = useState('');

  useEffect(() => {
    loadContentEntries(undefined, 'question_bank')
      .then(payload => {
        const nextEntries = payload.items || [];
        setEntries(nextEntries);
        if (!selectedEntryId && nextEntries[0]) setSelectedEntryId(nextEntries[0].id);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '题库入口加载失败'));
  }, []);

  useEffect(() => {
    if (!selectedEntryId) return;
    setSelectedNodeId('');
    loadContentNodes(selectedEntryId, 'root', 'children')
      .then(payload => setNodes(payload.items || []))
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '分类加载失败'));
    loadQuestionCollections({ entryId: selectedEntryId })
      .then(payload => setCollections(payload.items || []))
      .catch(() => setCollections([]));
    loadPracticeBlueprints({ entryId: selectedEntryId })
      .then(payload => setBlueprints(payload.items || []))
      .catch(() => setBlueprints([]));
  }, [selectedEntryId]);

  useEffect(() => {
    if (!selectedNodeId) return;
    Promise.all([
      loadQuestionCollections({ entryId: selectedEntryId, nodeId: selectedNodeId }),
      loadPracticeBlueprints({ entryId: selectedEntryId, nodeId: selectedNodeId }),
    ]).then(([nextCollections, nextBlueprints]) => {
      setCollections(nextCollections.items || []);
      setBlueprints(nextBlueprints.items || []);
    }).catch(nextError => setError(nextError instanceof Error ? nextError.message : '组卷配置加载失败'));
  }, [selectedNodeId]);

  const selectedEntry = useMemo(() => entries.find(item => item.id === selectedEntryId), [entries, selectedEntryId]);

  function startPractice(input: { collection?: QuestionCollection; blueprint?: PracticeBlueprint; mode?: string }) {
    const params = [
      input.collection ? `collectionId=${encodeURIComponent(input.collection.id)}` : '',
      input.blueprint ? `blueprintId=${encodeURIComponent(input.blueprint.id)}` : '',
      selectedEntryId ? `entryId=${encodeURIComponent(selectedEntryId)}` : '',
      selectedNodeId ? `contentNodeId=${encodeURIComponent(selectedNodeId)}` : '',
      `mode=${encodeURIComponent(input.mode || input.blueprint?.mode || 'sequential')}`,
    ].filter(Boolean).join('&');
    Taro.navigateTo({ url: `/pages/student/practice/index?${params}` });
  }

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Question Bank</Text>
          <Text className='student-title'>题库练习</Text>
          <Text className='student-subtitle'>{selectedEntry?.description || '按入口、分类、集合和蓝图进入练习，分类层级不在前端写死。'}</Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateBack()}>
          返回
        </Button>
      </View>

      <View className='section-block'>
        <Text className='section-heading'>入口</Text>
        <View className='toolbar'>
          {entries.map(item => (
            <Button key={item.id} className={`pill-button ${item.id === selectedEntryId ? 'active' : ''}`} onClick={() => setSelectedEntryId(item.id)}>
              {item.name}
            </Button>
          ))}
        </View>
      </View>

      <View className='section-block'>
        <Text className='section-heading'>分类</Text>
        {nodes.length ? (
          <View className='list-stack'>
            {nodes.map(item => (
              <View className='list-row' key={item.id} onClick={() => setSelectedNodeId(item.id)}>
                <Text className='row-main'>{item.name}</Text>
                <Text className='row-meta'>{item.markerType || item.nodeType || '分类'}{item.isLeaf ? ' · 可练习' : ''}</Text>
              </View>
            ))}
          </View>
        ) : <View className='empty-state'>暂无分类，导入题库后会在这里展示。</View>}
      </View>

      <View className='section-block'>
        <Text className='section-heading'>练习方式</Text>
        <View className='grid-two'>
          {blueprints.map(item => (
            <View className='metric' key={item.id} onClick={() => startPractice({ blueprint: item })}>
              <Text className='metric-value'>{item.name}</Text>
              <Text className='metric-label'>{item.mode} · {item.questionLimit || '不限'} 题</Text>
            </View>
          ))}
          {collections.map(item => (
            <View className='metric' key={item.id} onClick={() => startPractice({ collection: item, mode: item.collectionType === 'paper' ? 'mock_exam' : 'sequential' })}>
              <Text className='metric-value'>{item.name}</Text>
              <Text className='metric-label'>{item.collectionType || 'collection'} · {item.questionCount || 0} 题</Text>
            </View>
          ))}
        </View>
        {!collections.length && !blueprints.length ? <View className='empty-state'>当前入口还没有可用集合或练习蓝图。</View> : null}
        {error ? <Text className='error-text'>{error}</Text> : null}
      </View>
    </View>
  );
}
