<template>
  <div class="page-container">
    <!-- 操作按钮 -->
    <div class="table-actions">
      <el-button type="primary" :icon="Plus" @click="showCreateDialog">创建直播</el-button>
      <el-button :icon="Refresh" @click="getList">刷新列表</el-button>
    </div>

    <!-- 直播列表 -->
    <el-table v-loading="loading" :data="liveInputList" border>
      <el-table-column prop="uid" label="Live Input ID" min-width="300" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="live-info">
            <span class="live-id">{{ row.uid }}</span>
            <el-button link type="primary" :icon="CopyDocument" @click="copyToClipboard(row.uid)" />
          </div>
          <div v-if="row.meta?.name" class="live-name">{{ row.meta.name }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status?.current?.state === 'connected' ? 'success' : 'info'">
            {{ row.status?.current?.state === 'connected' ? '直播中' : '未连接' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="录制" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.recording?.mode === 'automatic' ? 'success' : 'info'" size="small">
            {{ row.recording?.mode === 'automatic' ? '开启' : '关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="170" align="center">
        <template #default="{ row }">
          {{ formatTime(row.created) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link :icon="VideoPlay" @click="handleWatch(row)">观看</el-button>
          <el-button type="success" link :icon="Connection" @click="showStreamInfo(row)">推流信息</el-button>
          <el-button type="info" link :icon="List" @click="showRecordings(row)">录像</el-button>
          <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建直播弹窗 -->
    <el-dialog v-model="createDialogVisible" title="创建直播" width="500px">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="直播名称">
          <el-input v-model="createForm.name" placeholder="请输入直播名称" />
        </el-form-item>
        <el-form-item label="自动录制">
          <el-switch v-model="createForm.recording" />
          <span class="form-tip">开启后自动保存直播录像</span>
        </el-form-item>
        <el-form-item label="录像保留" v-if="createForm.recording">
          <el-input-number v-model="createForm.deleteAfterDays" :min="1" :max="365" />
          <span class="form-tip">天后自动删除</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>

    <!-- 推流信息弹窗 -->
    <el-dialog v-model="streamInfoVisible" title="推流信息" width="700px">
      <el-tabs v-model="streamInfoTab" v-if="currentLiveInput">
        <el-tab-pane label="RTMPS 推流" name="rtmps">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="推流地址">
              <div class="url-item">
                <span class="url-text">{{ currentLiveInput.rtmps?.url }}</span>
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(currentLiveInput.rtmps?.url)"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="推流密钥">
              <div class="url-item">
                <span class="url-text">
                  {{ showStreamKey ? currentLiveInput.rtmps?.streamKey : '••••••••••••••••' }}
                </span>
                <el-button link type="primary" :icon="View" @click="showStreamKey = !showStreamKey" />
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(currentLiveInput.rtmps?.streamKey)"
                />
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <el-alert type="info" :closable="false" style="margin-top: 15px">
            <template #title>OBS 推流设置</template>
            <p>服务器：{{ currentLiveInput.rtmps?.url }}</p>
            <p>串流密钥：{{ currentLiveInput.rtmps?.streamKey }}</p>
          </el-alert>
        </el-tab-pane>

        <el-tab-pane label="SRT 推流" name="srt" v-if="currentLiveInput.srt">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="SRT 地址">
              <div class="url-item">
                <span class="url-text">{{ currentLiveInput.srt?.url }}</span>
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(currentLiveInput.srt?.url)"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="Stream ID">
              <div class="url-item">
                <span class="url-text">{{ currentLiveInput.srt?.streamId }}</span>
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(currentLiveInput.srt?.streamId)"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="Passphrase">
              <div class="url-item">
                <span class="url-text">{{ showStreamKey ? currentLiveInput.srt?.passphrase : '••••••••••••' }}</span>
                <el-button link type="primary" :icon="View" @click="showStreamKey = !showStreamKey" />
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(currentLiveInput.srt?.passphrase)"
                />
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="播放地址" name="playback">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="HLS 地址">
              <div class="url-item">
                <span class="url-text">{{ getHlsUrl(currentLiveInput.uid) }}</span>
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(getHlsUrl(currentLiveInput.uid))"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="iframe 嵌入">
              <div class="url-item">
                <span class="url-text">{{ getIframeUrl(currentLiveInput.uid) }}</span>
                <el-button
                  link
                  type="primary"
                  :icon="CopyDocument"
                  @click="copyToClipboard(getIframeUrl(currentLiveInput.uid))"
                />
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <el-alert type="warning" :closable="false" style="margin-top: 15px">播放地址仅在直播中有效</el-alert>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 录像列表弹窗 -->
    <el-dialog v-model="recordingsVisible" title="直播录像" width="800px">
      <el-table v-loading="recordingsLoading" :data="recordings" border max-height="400">
        <el-table-column prop="uid" label="Video ID" min-width="280" show-overflow-tooltip />
        <el-table-column prop="duration" label="时长" width="100" align="center">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="created" label="创建时间" width="170" align="center">
          <template #default="{ row }">
            {{ formatTime(row.created) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="VideoPlay" @click="playRecording(row)">播放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 观看直播弹窗 -->
    <el-dialog v-model="watchDialogVisible" title="观看直播" width="900px" destroy-on-close>
      <div class="player-container">
        <VideoPlayer
          v-if="watchDialogVisible && watchLiveId"
          :player-type="'hls'"
          :src="getHlsUrl(watchLiveId)"
          :autoplay="true"
          :controls="true"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, VideoPlay, Connection, List, Delete, CopyDocument, View } from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { useStreamStore } from '@/store/stream'
import type { CloudflareLiveInput, CloudflareVideo } from '@/types/cloudflare'

const streamStore = useStreamStore()

const loading = ref(false)
const liveInputList = ref<CloudflareLiveInput[]>([])

// 创建相关
const createDialogVisible = ref(false)
const createForm = reactive({
  name: '',
  recording: true,
  deleteAfterDays: 30
})
const creating = ref(false)

// 推流信息相关
const streamInfoVisible = ref(false)
const streamInfoTab = ref('rtmps')
const currentLiveInput = ref<CloudflareLiveInput | null>(null)
const showStreamKey = ref(false)

// 录像相关
const recordingsVisible = ref(false)
const recordingsLoading = ref(false)
const recordings = ref<CloudflareVideo[]>([])

// 观看相关
const watchDialogVisible = ref(false)
const watchLiveId = ref('')

function getHlsUrl(liveInputId: string): string {
  return streamStore.getHlsUrl(liveInputId)
}

function getIframeUrl(liveInputId: string): string {
  return streamStore.getIframeUrl(liveInputId)
}

function formatTime(time: string): string {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

function formatDuration(seconds: number): string {
  if (!seconds) return '-'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  if (h > 0) {
    return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  }
  return `${m}:${s.toString().padStart(2, '0')}`
}

async function copyToClipboard(text?: string) {
  if (!text) return
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}

async function getList() {
  loading.value = true
  try {
    // const res = await listLiveInputs()
    // liveInputList.value = res.data.rows
    liveInputList.value = []
    ElMessage.info('请配置 Cloudflare Stream 并连接后端 API')
  } finally {
    loading.value = false
  }
}

function showCreateDialog() {
  createForm.name = ''
  createForm.recording = true
  createForm.deleteAfterDays = 30
  createDialogVisible.value = true
}

async function handleCreate() {
  creating.value = true
  try {
    // await createLiveInput({
    //   meta: { name: createForm.name },
    //   recording: {
    //     mode: createForm.recording ? 'automatic' : 'off'
    //   },
    //   deleteRecordingAfterDays: createForm.deleteAfterDays
    // })
    ElMessage.success('创建成功')
    createDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('创建失败:', error)
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

function showStreamInfo(row: CloudflareLiveInput) {
  currentLiveInput.value = row
  showStreamKey.value = false
  streamInfoTab.value = 'rtmps'
  streamInfoVisible.value = true
}

function handleWatch(row: CloudflareLiveInput) {
  if (row.status?.current?.state !== 'connected') {
    ElMessage.warning('直播未开始')
    return
  }
  watchLiveId.value = row.uid
  watchDialogVisible.value = true
}

async function showRecordings(row: CloudflareLiveInput) {
  currentLiveInput.value = row
  recordingsVisible.value = true
  recordingsLoading.value = true
  try {
    // const res = await listLiveRecordings(row.uid)
    // recordings.value = res.data.rows
    recordings.value = []
  } finally {
    recordingsLoading.value = false
  }
}

function playRecording(row: CloudflareVideo) {
  watchLiveId.value = row.uid
  recordingsVisible.value = false
  watchDialogVisible.value = true
}

async function handleDelete(row: CloudflareLiveInput) {
  try {
    await ElMessageBox.confirm(`确定要删除直播 "${row.meta?.name || row.uid}" 吗？`, '提示', {
      type: 'warning'
    })
    // await deleteLiveInput(row.uid)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

onMounted(() => {
  streamStore.loadConfig()
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
}

.table-actions {
  margin-bottom: 15px;
}

.live-info {
  display: flex;
  align-items: center;
  gap: 4px;

  .live-id {
    font-family: monospace;
    font-size: 12px;
  }
}

.live-name {
  margin-top: 4px;
  font-size: 13px;
  color: #606266;
}

.url-item {
  display: flex;
  align-items: center;
  gap: 8px;

  .url-text {
    flex: 1;
    font-size: 12px;
    word-break: break-all;
    color: #606266;
    font-family: monospace;
  }
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.player-container {
  width: 100%;
  height: 480px;
  background-color: #000;
  border-radius: var(--radius-base);
  overflow: hidden;
}
</style>
