import { useEffect, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { Button, Text, View, Video } from '@tarojs/components';
import { loadQuestionVideos, playVideo, type QuestionVideoItem, type VideoPlayback } from '@/services/video';
import '../student.css';

export default function StudentVideoPage() {
  const router = useRouter();
  const questionId = router.params?.questionId || '';
  const [videos, setVideos] = useState<QuestionVideoItem[]>([]);
  const [selected, setSelected] = useState<QuestionVideoItem | null>(null);
  const [playback, setPlayback] = useState<VideoPlayback | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!questionId) {
      setError('缺少题目 ID，无法加载视频解析。');
      return;
    }
    loadQuestionVideos(questionId)
      .then(payload => {
        const nextVideos = payload.videos || [];
        setVideos(nextVideos);
        setSelected(nextVideos[0] || null);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '视频加载失败'));
  }, [questionId]);

  async function startPlay(item = selected) {
    if (!item) return;
    setError('');
    try {
      const payload = await playVideo({ videoId: item.id, questionId });
      setSelected(item);
      setPlayback(payload);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '播放授权失败');
    }
  }

  const playUrl = playback?.playback?.url;

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Video</Text>
          <Text className='student-title'>视频解析</Text>
          <Text className='student-subtitle'>播放地址由后端按会员权益或视频次数签名生成，前端不保存私有资源 URL。</Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateBack()}>返回</Button>
      </View>

      {playUrl ? (
        <Video className='video-frame' src={playUrl} controls autoplay />
      ) : <View className='empty-state'>选择视频后获取播放授权。</View>}

      <View className='section-block'>
        <Text className='section-heading'>可用视频</Text>
        <View className='list-stack'>
          {videos.map(item => (
            <View className={`list-row ${selected?.id === item.id ? 'active' : ''}`} key={item.id} onClick={() => startPlay(item)}>
              <Text className='row-main'>{item.title}</Text>
              <Text className='row-meta'>{item.accessMode || 'svip'} · {item.duration ? `${item.duration} 秒` : '未标注时长'}</Text>
            </View>
          ))}
        </View>
        {!videos.length ? <View className='empty-state'>这道题暂未绑定视频解析。</View> : null}
      </View>

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