import { View, Text, Button, Image, ScrollView } from '@tarojs/components'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { getCompetitionDetail, enrollCompetition, getMyCompetitionEnrollment, getProjects } from '../../api'
import MarkdownReader from '../../components/MarkdownReader'
import './detail.scss'

export default function CompetitionDetail() {
  const [detail, setDetail] = useState<any>(null)
  const [enrollment, setEnrollment] = useState<any>(null)
  const [projects, setProjects] = useState<any[]>([])
  const [myProject, setMyProject] = useState<any>(null)
  const [activeTab, setActiveTab] = useState(0)
  const [loading, setLoading] = useState(false)

  useLoad((options) => {
    const { id } = options
    if (id) {
      fetchDetail(id)
      fetchEnrollment(id)
      fetchProjects(id)
    }
  })

  useDidShow(() => {
    // 每次显示页面时刷新一下我的项目信息（比如从编辑页返回）
    if (detail?.id) {
        fetchMyProject(detail.id)
    }
  })

  const fetchDetail = async (id) => {
    setLoading(true)
    try {
      const res = await getCompetitionDetail(id)
      setDetail(res)
      fetchMyProject(id)
    } catch (e) {
      Taro.showToast({ title: '加载详情失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const fetchMyProject = async (competitionId) => {
    try {
        const userInfo = Taro.getStorageSync('userInfo')
        if (!userInfo) return

        const res = await getProjects({ competition: competitionId })
        const list = res.results || res
        // 尝试通过 enrollment.id 匹配，或者通过 user nickname 匹配（不够严谨但暂时可用）
        
        if (enrollment) {
             const mine = list.find((p: any) => p.contestant === enrollment.id)
             if (mine) {
                 setMyProject(mine)
                 return
             }
        }
        
        // Fallback: use nickname match if enrollment not ready or failed
        const myProj = list.find((p: any) => p.contestant_info?.nickname === userInfo.nickname)
        if (myProj) setMyProject(myProj)
        
    } catch (e) {
        console.error(e)
    }
  }

  const fetchEnrollment = async (id) => {
    try {
      const res = await getMyCompetitionEnrollment(id)
      setEnrollment(res)
      // 获取到 enrollment 后，去匹配 myProject
      if (projects.length > 0) {
          const mine = projects.find((p: any) => p.contestant === res.id)
          setMyProject(mine)
      }
    } catch (e) {
      // 没报名则无数据，忽略
    }
  }

  const fetchProjects = async (id) => {
    try {
      // 注意：这里我们去掉了 status='submitted'，因为我们要找自己的 draft
      const res = await getProjects({ competition: id })
      const list = res.results || res
      const allProjects = Array.isArray(list) ? list : []
      
      // 过滤出 submitted 的给列表显示
      const submittedProjects = allProjects.filter(p => p.status === 'submitted')
      setProjects(submittedProjects)
    } catch (e) {
      console.error('Fetch projects failed', e)
    }
  }
  
  // 监听变化设置 myProject
  useEffect(() => {
      if (enrollment && projects.length >= 0) { // projects could be empty
          fetchMySpecificProject(detail?.id, enrollment.id)
      }
  }, [enrollment])

  const fetchMySpecificProject = async (compId, enrollId) => {
      if (!compId || !enrollId) return
      try {
          const res = await getProjects({ competition: compId })
          const list = res.results || res
          const mine = list.find((p: any) => p.contestant === enrollId)
          setMyProject(mine)
      } catch (e) {}
  }

  const handleEnroll = async () => {
    if (!detail) return
    try {
      await enrollCompetition(detail.id, { role: 'contestant' })
      Taro.showToast({ title: '报名成功', icon: 'success' })
      fetchEnrollment(detail.id)
    } catch (e) {
      Taro.showToast({ title: e.message || '报名失败', icon: 'none' })
    }
  }

  const getStatusText = (status) => {
    const map = {
      'registration': '报名中',
      'submission': '作品提交中',
      'judging': '评审中',
      'ended': '已结束',
    }
    return map[status] || status
  }

  const getEmptyMessage = (visibility, enrollment) => {
      const role = enrollment?.status === 'approved' ? enrollment.role : null;
      
      if (visibility === 'judge') {
          if (role === 'judge') return '暂无参赛项目';
          return '该比赛项目仅评委可见';
      }
      if (visibility === 'guest') {
          if (role === 'judge' || role === 'guest') return '暂无参赛项目';
          return '该比赛项目仅嘉宾/评委可见';
      }
      if (visibility === 'contestant') {
          if (role) return '暂无参赛项目';
          return '该比赛项目仅参赛选手可见，请先报名';
      }
      return '暂无参赛项目';
  }

  if (loading || !detail) return <View className='loading'>加载中...</View>

  return (
    <ScrollView scrollY className='comp-detail'>
      <Image 
        className='banner' 
        mode='aspectFill' 
        src={detail.display_cover_image || 'https://via.placeholder.com/400x200'} 
      />
      
      <View className='content'>
        <View className='header'>
          <Text className='title'>{detail.title}</Text>
          <Text className={`status ${detail.status}`}>{getStatusText(detail.status)}</Text>
        </View>
        
        <View className='tabs'>
          {['详情', '参赛项目', '排行榜'].map((tab, index) => (
            <View 
              key={index} 
              className={`tab-item ${activeTab === index ? 'active' : ''}`}
              onClick={() => setActiveTab(index)}
            >
              {tab}
            </View>
          ))}
        </View>

        {activeTab === 0 && (
          <>
            <View className='section'>
              <Text className='section-title'>简介</Text>
              <MarkdownReader content={detail.description} />
            </View>

            <View className='section'>
              <Text className='section-title'>规则</Text>
              <MarkdownReader content={detail.rule_description} />
            </View>

            <View className='section'>
              <Text className='section-title'>参赛条件</Text>
              <MarkdownReader content={detail.condition_description} />
            </View>
          </>
        )}

        {activeTab === 1 && (
          <View className='project-list'>
            {projects.map(project => (
              <View className='project-card' key={project.id} onClick={() => Taro.navigateTo({ url: `/pages/competition/project-detail?id=${project.id}` })}>
                <Image 
                  className='cover' 
                  mode='aspectFill' 
                  src={project.display_cover_image || 'https://via.placeholder.com/120x90'} 
                />
                <View className='info'>
                  <Text className='title'>{project.title}</Text>
                  <View className='author'>
                    <View className='user'>
                      <Image className='avatar' src={project.contestant_info?.avatar_url || ''} />
                      <Text>{project.contestant_info?.nickname || '参赛者'}</Text>
                    </View>
                    {project.final_score > 0 && <Text className='score'>{project.final_score}分</Text>}
                  </View>
                </View>
              </View>
            ))}
            {projects.length === 0 && <View className='empty'>{getEmptyMessage(detail.project_visibility, enrollment)}</View>}
          </View>
        )}

        {activeTab === 2 && (
          <View className='ranking-list'>
            {projects
              .filter(p => p.final_score > 0)
              .sort((a, b) => b.final_score - a.final_score)
              .map((project, index) => (
              <View className='rank-item' key={project.id} onClick={() => Taro.navigateTo({ url: `/pages/competition/project-detail?id=${project.id}` })}>
                <Text className={`rank-num top${index + 1}`}>{index + 1}</Text>
                <View className='info'>
                  <Image className='avatar' src={project.contestant_info?.avatar_url || ''} />
                  <View className='detail'>
                     <Text className='nickname'>{project.contestant_info?.nickname || '参赛者'}</Text>
                     <Text className='project-title'>{project.title}</Text>
                  </View>
                </View>
                <Text className='score'>{project.final_score}</Text>
              </View>
            ))}
            {projects.filter(p => p.final_score > 0).length === 0 && <View className='empty'>暂无排名数据</View>}
          </View>
        )}
      </View>

      <View className='footer-action'>
        {enrollment ? (
          myProject ? (
              <View style={{ display: 'flex', width: '100%', gap: '10px' }}>
                <Button 
                    className='btn enrolled'
                    style={{ flex: 1 }}
                    onClick={() => Taro.navigateTo({ url: `/pages/competition/project?id=${myProject.id}` })}
                >
                    我的作品 ({myProject.status === 'submitted' ? '已提交' : '草稿'})
                </Button>
                <Button 
                    className='btn'
                    style={{ width: '80px', background: '#fff', color: '#333', border: '1px solid #ddd', fontSize: '12px', padding: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                    onClick={() => Taro.navigateTo({ url: `/pages/competition/project-detail?id=${myProject.id}` })}
                >
                    评语
                </Button>
              </View>
          ) : (
            enrollment.status === 'approved' ? (
              <Button 
                className='btn enrolled'
                onClick={() => Taro.navigateTo({ url: `/pages/competition/project?competitionId=${detail.id}` })}
              >
                立即提交作品
              </Button>
            ) : (
              <Button disabled className='btn enrolled'>
                报名审核中
              </Button>
            )
          )
        ) : (
          <Button 
            className='btn enroll' 
            onClick={handleEnroll} 
            disabled={detail.status !== 'registration'}
          >
            {detail.status === 'registration' ? '立即报名' : '报名未开始/已结束'}
          </Button>
        )}
      </View>
    </ScrollView>
  )
}
