import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { CloudflareVideo, CloudflareLiveInput, VideoPlaybackInfo } from '@/types/cloudflare'

// Cloudflare Stream 配置
export interface StreamConfig {
  accountId: string
  customerSubdomain: string
  apiToken?: string
}

export const useStreamStore = defineStore('stream', () => {
  // 配置
  const config = ref<StreamConfig>({
    accountId: '',
    customerSubdomain: ''
  })

  // 视频列表
  const videos = ref<CloudflareVideo[]>([])
  const videosLoading = ref(false)
  const videosTotal = ref(0)

  // 直播列表
  const liveInputs = ref<CloudflareLiveInput[]>([])
  const liveInputsLoading = ref(false)

  // 当前播放
  const currentVideo = ref<CloudflareVideo | null>(null)
  const currentLiveInput = ref<CloudflareLiveInput | null>(null)

  // 计算域名
  const customerDomain = computed(() => {
    if (config.value.customerSubdomain) {
      return `customer-${config.value.customerSubdomain}.cloudflarestream.com`
    }
    return ''
  })

  // 初始化配置
  function initConfig(newConfig: Partial<StreamConfig>) {
    config.value = { ...config.value, ...newConfig }
    // 保存到 localStorage
    localStorage.setItem('stream-config', JSON.stringify(config.value))
  }

  // 从 localStorage 加载配置
  function loadConfig() {
    const saved = localStorage.getItem('stream-config')
    if (saved) {
      try {
        config.value = JSON.parse(saved)
      } catch (e) {
        console.error('Failed to load stream config:', e)
      }
    }
  }

  // 生成播放信息
  function getPlaybackInfo(videoId: string): VideoPlaybackInfo | null {
    if (!customerDomain.value) return null

    return {
      uid: videoId,
      preview: `https://${customerDomain.value}/${videoId}/watch`,
      thumbnail: `https://${customerDomain.value}/${videoId}/thumbnails/thumbnail.jpg`,
      playback: {
        hls: `https://${customerDomain.value}/${videoId}/manifest/video.m3u8`,
        dash: `https://${customerDomain.value}/${videoId}/manifest/video.mpd`
      },
      iframe: `https://${customerDomain.value}/${videoId}/iframe`
    }
  }

  // 生成缩略图 URL
  function getThumbnailUrl(
    videoId: string,
    options?: {
      time?: string
      height?: number
      width?: number
    }
  ): string {
    if (!customerDomain.value) return ''

    const params = new URLSearchParams()
    if (options?.time) params.set('time', options.time)
    if (options?.height) params.set('height', options.height.toString())
    if (options?.width) params.set('width', options.width.toString())
    const queryString = params.toString()

    return `https://${customerDomain.value}/${videoId}/thumbnails/thumbnail.jpg${queryString ? `?${queryString}` : ''}`
  }

  // 生成 iframe URL
  function getIframeUrl(
    videoId: string,
    options?: {
      autoplay?: boolean
      muted?: boolean
      loop?: boolean
      preload?: string
      primaryColor?: string
      letterboxColor?: string
      startTime?: string
      defaultTextTrack?: string
    }
  ): string {
    if (!customerDomain.value) return ''

    const params = new URLSearchParams()
    if (options?.autoplay) params.set('autoplay', 'true')
    if (options?.muted) params.set('muted', 'true')
    if (options?.loop) params.set('loop', 'true')
    if (options?.preload) params.set('preload', options.preload)
    if (options?.primaryColor) params.set('primaryColor', options.primaryColor)
    if (options?.letterboxColor) params.set('letterboxColor', options.letterboxColor)
    if (options?.startTime) params.set('startTime', options.startTime)
    if (options?.defaultTextTrack) params.set('defaultTextTrack', options.defaultTextTrack)
    const queryString = params.toString()

    return `https://${customerDomain.value}/${videoId}/iframe${queryString ? `?${queryString}` : ''}`
  }

  // 生成 HLS URL
  function getHlsUrl(videoId: string): string {
    if (!customerDomain.value) return ''
    return `https://${customerDomain.value}/${videoId}/manifest/video.m3u8`
  }

  // 设置当前视频
  function setCurrentVideo(video: CloudflareVideo | null) {
    currentVideo.value = video
  }

  // 设置当前直播
  function setCurrentLiveInput(liveInput: CloudflareLiveInput | null) {
    currentLiveInput.value = liveInput
  }

  return {
    // 状态
    config,
    videos,
    videosLoading,
    videosTotal,
    liveInputs,
    liveInputsLoading,
    currentVideo,
    currentLiveInput,
    customerDomain,

    // 方法
    initConfig,
    loadConfig,
    getPlaybackInfo,
    getThumbnailUrl,
    getIframeUrl,
    getHlsUrl,
    setCurrentVideo,
    setCurrentLiveInput
  }
})
