<template>
  <el-dialog
    :model-value="visible"
    title="选择摄像头"
    width="500px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <!-- 搜索框 -->
    <div class="selector-search">
      <el-input v-model="searchText" placeholder="搜索摄像头..." clearable :prefix-icon="Search" />
    </div>

    <!-- 摄像头列表 -->
    <div class="selector-list">
      <el-scrollbar height="300px">
        <div
          v-for="camera in filteredCameras"
          :key="camera.id"
          class="selector-item"
          :class="{ 'selector-item--selected': selectedCamera?.id === camera.id }"
          @click="selectedCamera = camera"
        >
          <div class="selector-item__radio">
            <el-icon v-if="selectedCamera?.id === camera.id" color="var(--color-primary)">
              <CircleCheckFilled />
            </el-icon>
            <el-icon v-else color="var(--text-placeholder)">
              <CircleCheck />
            </el-icon>
          </div>
          <div class="selector-item__info">
            <div class="selector-item__name">{{ camera.name }}</div>
            <div class="selector-item__meta">
              <el-tag size="small" :type="camera.streamType === 'webrtc' ? 'success' : 'primary'">
                {{ camera.streamType === 'webrtc' ? 'WebRTC' : 'Cloudflare' }}
              </el-tag>
              <el-tag size="small" :type="camera.online ? 'success' : 'danger'">
                {{ camera.online ? '在线' : '离线' }}
              </el-tag>
            </div>
          </div>
        </div>

        <div v-if="filteredCameras.length === 0" class="selector-empty">
          <el-empty description="没有找到摄像头" :image-size="80" />
        </div>
      </el-scrollbar>
    </div>

    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" :disabled="!selectedCamera" @click="handleConfirm">确定选择</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Search, CircleCheck, CircleCheckFilled } from '@element-plus/icons-vue'
import { adminListCameras } from '@/api/camera'

interface CameraItem {
  id: string
  name: string
  streamType: 'webrtc' | 'cloudflare'
  streamUrl: string
  online: boolean
}

interface Props {
  visible: boolean
  currentPosition?: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  select: [camera: { id: string; name: string; streamType: 'webrtc' | 'cloudflare'; streamUrl: string }]
}>()

const searchText = ref('')
const cameras = ref<CameraItem[]>([])
const selectedCamera = ref<CameraItem | null>(null)
const loading = ref(false)

const filteredCameras = computed(() => {
  if (!searchText.value) return cameras.value
  const keyword = searchText.value.toLowerCase()
  return cameras.value.filter((camera) => camera.name.toLowerCase().includes(keyword))
})

// 加载摄像头列表
async function loadCameras() {
  loading.value = true
  try {
    const res = await adminListCameras()
    if (res.success && res.data.list) {
      cameras.value = res.data.list.map((item) => ({
        id: String(item.id),
        name: item.name || `摄像头 ${item.id}`,
        // 根据实际数据判断 streamType，这里暂时默认为 webrtc
        streamType: (item as any).streamType || 'webrtc',
        streamUrl: (item as any).streamUrl || (item as any).rtspUrl || '',
        online: (item as any).online !== false
      }))
    }
  } catch (error) {
    console.error('Failed to load cameras:', error)
    // 使用模拟数据
    cameras.value = [
      { id: '1', name: '大门入口', streamType: 'webrtc', streamUrl: 'camera1', online: true },
      {
        id: '2',
        name: '停车场',
        streamType: 'cloudflare',
        streamUrl: 'b51e49994b6fd9e56b6f1fdfcd339fe6',
        online: true
      },
      { id: '3', name: '仓库', streamType: 'webrtc', streamUrl: 'camera3', online: false },
      { id: '4', name: '办公区', streamType: 'webrtc', streamUrl: 'camera4', online: true }
    ]
  } finally {
    loading.value = false
  }
}

function handleConfirm() {
  if (!selectedCamera.value) return

  emit('select', {
    id: selectedCamera.value.id,
    name: selectedCamera.value.name,
    streamType: selectedCamera.value.streamType,
    streamUrl: selectedCamera.value.streamUrl
  })
}

// 监听 visible 变化，打开时加载数据
watch(
  () => props.visible,
  (val) => {
    if (val) {
      selectedCamera.value = null
      searchText.value = ''
      loadCameras()
    }
  }
)
</script>

<style lang="scss" scoped>
.selector-search {
  margin-bottom: 16px;
}

.selector-list {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-base);
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid var(--border-color-light);

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: var(--bg-hover);
  }

  &--selected {
    background-color: var(--color-primary-light-9);
  }

  &__radio {
    font-size: 20px;
  }

  &__info {
    flex: 1;
  }

  &__name {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 4px;
  }

  &__meta {
    display: flex;
    gap: 8px;
  }
}

.selector-empty {
  padding: 40px 0;
}
</style>
