import { useEffect, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import RichContent from '@/components/RichContent';
import {
  loadPracticeHistory,
  loadPracticeReports,
  loadPracticeSessionReport,
  type PracticeHistoryItem,
  type PracticeReport,
} from '@/services/learning';
import '../student.css';

function percent(value?: number) {
  return `${Math.round((value || 0) * 100)}%`;
}

function stringValue(source: Record<string, unknown>, key: string) {
  const value = source[key];
  return typeof value === 'string' ? value : '';
}

function numberArray(source: Record<string, unknown>, key: string) {
  const value = source[key];
  return Array.isArray(value) ? value.map(item => Number(item)).filter(Number.isFinite) : [];
}

function answerChoiceLabel(value: unknown) {
  const num = Number(value);
  return Number.isFinite(num) ? String.fromCharCode(65 + num) : String(value);
}

function resultStatus(result: Record<string, unknown>) {
  if (!result.answered) return '未答';
  if (result.isCorrect === true) return '正确';
  if (result.isCorrect === false) return '错误';
  return '已答';
}

export default function StudentReportsPage() {
  const router = useRouter();
  const practiceSessionId = router.params?.practiceSessionId || '';
  const [report, setReport] = useState<PracticeReport | null>(null);
  const [reports, setReports] = useState<PracticeReport[]>([]);
  const [activeSessions, setActiveSessions] = useState<PracticeHistoryItem[]>([]);
  const [error, setError] = useState('');

  useEffect(() => {
    if (practiceSessionId) {
      loadPracticeSessionReport(practiceSessionId)
        .then(payload => setReport(payload.item || null))
        .catch(nextError => setError(nextError instanceof Error ? nextError.message : '报告加载失败'));
      return;
    }
    Promise.all([
      loadPracticeReports({ limit: 20 }),
      loadPracticeHistory({ status: 'active', limit: 10 }),
    ])
      .then(([reportPayload, historyPayload]) => {
        setReports(reportPayload.items || []);
        setActiveSessions(historyPayload.items || []);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '报告列表加载失败'));
  }, [practiceSessionId]);

  const current = report || reports[0] || null;

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Report</Text>
          <Text className='student-title'>练习报告</Text>
          <Text className='student-subtitle'>分数、正确率、题型分段和错题明细均以后端 session 快照评分为准。</Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateBack()}>返回</Button>
      </View>

      {current ? (
        <View className='report-panel'>
          <Text className='metric-value'>{String(current.score)} / {String(current.totalScore)}</Text>
          <Text className='metric-label'>{current.mode} · 正确率 {percent(current.accuracy)} · 已答 {current.answeredCount}/{current.totalQuestions}</Text>
          <View className='grid-two section-block'>
            <View className='metric'><Text className='metric-value'>{String(current.correctCount)}</Text><Text className='metric-label'>正确</Text></View>
            <View className='metric'><Text className='metric-value'>{String(current.wrongCount)}</Text><Text className='metric-label'>错误</Text></View>
          </View>
        </View>
      ) : <View className='empty-state'>暂无练习报告，完成一次练习后会在这里展示。</View>}

      {!practiceSessionId && activeSessions.length ? (
        <View className='section-block'>
          <Text className='section-heading'>继续练习</Text>
          <View className='list-stack'>
            {activeSessions.map(item => (
              <View className='list-row' key={item.id}>
                <Text className='row-main'>{item.collectionName || item.contentNodeName || item.entryName || item.mode}</Text>
                <Text className='row-meta'>已答 {String(item.answeredCount || 0)} / {String(item.questionCount || 0)} · {item.startedAt ? item.startedAt.slice(0, 10) : ''}</Text>
                <View className='toolbar'>
                  <Button className='primary-button' onClick={() => Taro.navigateTo({ url: `/pages/student/practice/index?practiceSessionId=${item.id}` })}>继续</Button>
                </View>
              </View>
            ))}
          </View>
        </View>
      ) : null}

      {current?.sectionStats?.length ? (
        <View className='section-block'>
          <Text className='section-heading'>分段统计</Text>
          <View className='list-stack'>
            {current.sectionStats.map((section, index) => (
              <View className='list-row' key={String(section.key || index)}>
                <Text className='row-main'>{String(section.title || section.key || '分段')}</Text>
                <Text className='row-meta'>得分 {String(section.score || 0)} / {String(section.totalScore || 0)} · 正确 {String(section.correctCount || 0)} / {String(section.questionCount || 0)}</Text>
              </View>
            ))}
          </View>
        </View>
      ) : null}

      {!practiceSessionId && reports.length > 1 ? (
        <View className='section-block'>
          <Text className='section-heading'>历史报告</Text>
          <View className='list-stack'>
            {reports.slice(1).map(item => (
              <View className='list-row' key={item.id} onClick={() => setReport(item)}>
                <Text className='row-main'>{item.mode} · {String(item.score)} / {String(item.totalScore)}</Text>
                <Text className='row-meta'>正确率 {percent(item.accuracy)} · {item.submittedAt ? item.submittedAt.slice(0, 10) : ''}</Text>
              </View>
            ))}
          </View>
        </View>
      ) : null}

      {current?.questionResults?.length ? (
        <View className='section-block'>
          <Text className='section-heading'>逐题复盘</Text>
          <View className='list-stack'>
            {current.questionResults.map((raw, index) => {
              const item = raw || {};
              const result = item as Record<string, unknown>;
              const selectedOptions = numberArray(result, 'selectedOptions').map(answerChoiceLabel);
              const correctOptions = numberArray(result, 'correctOptionIndices').map(answerChoiceLabel);
              const correctOptionIndex = result.correctOptionIndex;
              if (!correctOptions.length && correctOptionIndex !== null && correctOptionIndex !== undefined) {
                correctOptions.push(answerChoiceLabel(correctOptionIndex));
              }
              const subResults = Array.isArray(result.subResults) ? result.subResults as Record<string, unknown>[] : [];
              return (
                <View className='list-row' key={stringValue(result, 'questionId') || String(index)}>
                  <View className='amount-row'>
                    <Text className='row-meta'>第 {index + 1} 题 · {stringValue(result, 'questionType') || '题目'}</Text>
                    <Text className={`status-badge ${result.isCorrect === false ? 'danger' : ''}`}>{resultStatus(result)}</Text>
                  </View>
                  <RichContent content={stringValue(result, 'content') || '暂无题干'} compact />
                  <Text className='row-meta'>得分 {String(result.score ?? 0)} / {String(result.totalScore ?? 0)}</Text>
                  {selectedOptions.length ? <Text className='row-meta'>你的选择：{selectedOptions.join('、')}</Text> : null}
                  {correctOptions.length ? <Text className='row-meta'>正确选项：{correctOptions.join('、')}</Text> : null}
                  {stringValue(result, 'answerText') ? (
                    <View className='answer-detail'>
                      <Text className='answer-detail-label'>你的答案</Text>
                      <RichContent content={stringValue(result, 'answerText')} compact muted />
                    </View>
                  ) : null}
                  {stringValue(result, 'correctAnswerText') ? (
                    <View className='answer-detail'>
                      <Text className='answer-detail-label'>参考答案</Text>
                      <RichContent content={stringValue(result, 'correctAnswerText')} compact />
                    </View>
                  ) : null}
                  {stringValue(result, 'explanation') ? (
                    <View className='answer-detail'>
                      <Text className='answer-detail-label'>解析</Text>
                      <RichContent content={stringValue(result, 'explanation')} compact muted />
                    </View>
                  ) : null}
                  {subResults.length ? (
                    <View className='sub-explanation'>
                      <Text className='answer-detail-label'>子题明细</Text>
                      {subResults.map((subResult, subIndex) => (
                        <View className='report-sub-result' key={stringValue(subResult, 'subQuestionId') || String(subIndex)}>
                          <Text className='row-meta'>第 {subIndex + 1} 小题 · {resultStatus(subResult)} · 得分 {String(subResult.score ?? 0)} / {String(subResult.totalScore ?? 0)}</Text>
                          <RichContent content={stringValue(subResult, 'content')} compact muted emptyText='暂无子题题干' />
                          {stringValue(subResult, 'correctAnswerText') ? <RichContent content={`参考答案：${stringValue(subResult, 'correctAnswerText')}`} compact muted /> : null}
                          {stringValue(subResult, 'explanation') ? <RichContent content={`解析：${stringValue(subResult, 'explanation')}`} compact muted /> : null}
                        </View>
                      ))}
                    </View>
                  ) : null}
                </View>
              );
            })}
          </View>
        </View>
      ) : null}

      {error ? <Text className='error-text'>{error}</Text> : null}
    </View>
  );
}
