import { View, Text, Button, Image, ScrollView, Video } from '@tarojs/components'
import Taro, { useLoad, useDidShow, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import { useState, useRef } from 'react'
import { getVBCourseDetail } from '../../api'
import { login } from '../../utils/request'
import { checkLogin } from '../../utils/auth'
import './detail.scss'

export default function CourseDetail() {
  const [detail, setDetail] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const courseIdRef = useRef<string>('')

  useLoad((options) => {
    if (options.id) {
      courseIdRef.current = options.id
    }
  })

  useDidShow(async () => {
    if (!courseIdRef.current) return
    
    // 检查并确保有 Token，以便获取最新的购买状态
    const token = Taro.getStorageSync('token')
    if (!token) {
      try {
        await login()
      } catch (e) {
        console.error('Silent login failed', e)
      }
    }
    
    fetchDetail(courseIdRef.current)
  })

  const typeMap: Record<string, string> = {
    software: '软件课程',
    hardware: '硬件课程',
    incubation: '产品商业孵化'
  }

  const fetchDetail = async (id: string) => {
    try {
      // Add timestamp to prevent caching
      const res: any = await getVBCourseDetail(Number(id))
      console.log('Course detail:', res)
      setDetail(res)
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleLaunch = () => {
    if (!checkLogin()) return
    if (!detail) return
    Taro.navigateTo({
      url: `/pages/order/checkout?id=${detail.id}&type=course`
    })
  }

  useShareAppMessage(() => {
    return {
      title: detail?.title || 'VC 课程详情',
      path: `/pages/courses/detail?id=${detail?.id}`,
      imageUrl: detail?.cover_image_url
    }
  })

  useShareTimeline(() => {
    return {
      title: detail?.title || 'VC 课程详情',
      query: `id=${detail?.id}`,
      imageUrl: detail?.cover_image_url
    }
  })

  if (loading) return <View className='page-container'><Text style={{color:'#fff'}}>Loading...</Text></View>
  if (!detail) return <View className='page-container'><Text style={{color:'#fff'}}>Not Found</Text></View>

  const formatDateTime = (dateStr: string) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}/${month}/${day} ${hour}:${minute}`
  }

  const extractIframeSrc = (html: string) => {
    if (!html) return null
    const match = html.match(/src=["'](.*?)["']/)
    return match ? match[1] : null
  }

  const handleOpenWebview = (url: string) => {
    if (!url) return
    Taro.navigateTo({
      url: `/pages/webview/index?url=${encodeURIComponent(url)}`
    })
  }

  return (
    <View className='page-container'>
      <ScrollView scrollY className='scroll-content'>
        {/* 封面图 */}
        {detail.cover_image_url && (
            <Image src={detail.cover_image_url} className='cover-image' mode='aspectFill' />
        )}

        <View className='content-wrapper'>
            {/* 标题区 */}
            <View className='header-section'>
                <Text className='title'>{detail.title}</Text>
                <View className='tags-row'>
                    <Text className='tag'>{typeMap[detail.course_type] || 'VC课程'}</Text>
                    {detail.tag && <Text className='tag highlight'>{detail.tag}</Text>}
                </View>
                <Text className='price'>¥{detail.price}</Text>
            </View>

            {/* 视频播放区域 */}
            {detail.is_video_course && (
                <View className='section video-section'>
                    <Text className='section-title'>课程视频</Text>
                    {detail.video_url ? (
                        <Video
                            src={detail.video_url}
                            className='course-video'
                            poster={detail.cover_image_url}
                            controls
                            autoplay={false}
                        />
                    ) : detail.video_embed_code ? (
                        <View className='video-locked' onClick={() => {
                            const src = extractIframeSrc(detail.video_embed_code)
                            if (src) handleOpenWebview(src)
                            else Taro.showToast({ title: '无法解析视频地址', icon: 'none' })
                        }}>
                            <Image src={detail.cover_image_url} className='locked-bg' mode='aspectFill' />
                            <View className='locked-overlay'>
                                <View className='lock-icon' style={{fontSize: '40px'}}>▶</View>
                                <Text className='lock-text'>点击观看视频</Text>
                            </View>
                        </View>
                    ) : (
                        <View className='video-locked' onClick={handleLaunch}>
                            <Image src={detail.cover_image_url} className='locked-bg' mode='aspectFill' />
                            <View className='locked-overlay'>
                                <View className='lock-icon'>🔒</View>
                                <Text className='lock-text'>购买课程后解锁视频</Text>
                                <Button className='btn-unlock'>立即解锁</Button>
                            </View>
                        </View>
                    )}
                </View>
            )}

            {/* 讲师信息 */}
            <View className='section instructor-section'>
                <Text className='section-title'>讲师介绍</Text>
                <View className='instructor-row'>
                    {detail.instructor_avatar_url ? (
                        <Image src={detail.instructor_avatar_url} className='avatar' mode='aspectFill' />
                    ) : (
                        <View className='avatar-placeholder'>
                            <Text>讲师</Text>
                        </View>
                    )}
                    <View className='instructor-info'>
                        <Text className='name'>{detail.instructor} <Text className='title-tag'>{detail.instructor_title}</Text></Text>
                        <Text className='desc'>{detail.instructor_desc}</Text>
                    </View>
                </View>
            </View>

            {/* 课程信息 */}
            <View className='section info-grid'>
                <View className='grid-item'>
                    <Text className='label'>时长</Text>
                    <Text className='value'>{detail.duration}</Text>
                </View>
                <View className='grid-item'>
                    <Text className='label'>课时</Text>
                    <Text className='value'>{detail.lesson_count}节</Text>
                </View>
                <View className='grid-item'>
                    <Text className='label'>难度</Text>
                    <Text className='value'>中级</Text>
                </View>
            </View>

            {/* 开课时间 */}
            {detail.is_fixed_schedule && (detail.start_time || detail.end_time) && (
                <View className='section schedule-section'>
                    <Text className='section-title'>开课时间</Text>
                    <View className='schedule-box'>
                        {detail.start_time && (
                            <View className='time-row'>
                                <Text className='label'>开始时间：</Text>
                                <Text className='value'>{formatDateTime(detail.start_time)}</Text>
                            </View>
                        )}
                        {detail.end_time && (
                            <View className='time-row'>
                                <Text className='label'>结束时间：</Text>
                                <Text className='value'>{formatDateTime(detail.end_time)}</Text>
                            </View>
                        )}
                    </View>
                </View>
            )}

            {/* 课程简介 */}
            <View className='section'>
                <Text className='section-title'>课程简介</Text>
                <Text className='desc-text'>{detail.description}</Text>
            </View>

            {/* 详情长图 */}
            <View className='section detail-images'>
                <Text className='section-title'>课程详情</Text>
                {detail.display_detail_image || detail.detail_image_url ? (
                    <Image 
                        src={detail.detail_image_url || detail.display_detail_image} 
                        className='detail-long-image' 
                        mode='widthFix' 
                    />
                ) : (
                    <View className='placeholder-box'>
                        <Text>暂无详情长图</Text>
                    </View>
                )}
            </View>
        </View>
      </ScrollView>

      {/* 底部栏 */}
      <View className='bottom-bar'>
        <View className='price-container'>
            <Text className='label'>总价:</Text>
            <Text className='amount'>¥{detail.price}</Text>
        </View>
        <Button 
            className={`btn-buy ${detail.is_purchased ? 'disabled' : ''}`} 
            onClick={() => !detail.is_purchased && handleLaunch()}
            disabled={detail.is_purchased}
        >
            {detail.is_purchased ? '已购买' : (detail.is_video_course ? '立即购买' : '立即报名')}
        </Button>
      </View>
    </View>
  )
}
