<template>
  <div class="space-y-6">
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold">身份管理</h2>
      <button
        @click="loadIdentities"
        class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition"
      >
        重新整理
      </button>
    </div>

    <!-- Search Filter -->
    <div class="bg-gray-800 rounded-lg p-4 border border-gray-700">
      <input
        v-model="filterQuery"
        @keyup.enter="loadIdentities"
        type="text"
        placeholder="搜尋身份..."
        class="w-full bg-gray-700 border border-gray-600 rounded-lg px-4 py-2 text-white focus:outline-none focus:border-blue-500"
      />
    </div>

    <!-- Identity List -->
    <div v-if="identities.length > 0" class="grid gap-4">
      <div
        v-for="identity in identities"
        :key="identity.id"
        class="bg-gray-800 rounded-lg p-6 border border-gray-700"
      >
        <div class="flex justify-between items-start">
          <div class="flex-1">
            <div class="flex items-center space-x-3 mb-2">
              <h3 class="text-xl font-semibold text-blue-400">
                {{ identity.profile.name || '未命名' }}
              </h3>
              <span
                v-if="identity.face_identity_id"
                class="bg-green-900 text-green-300 px-2 py-1 rounded text-xs"
              >
                已註冊
              </span>
              <span
                v-else
                class="bg-yellow-900 text-yellow-300 px-2 py-1 rounded text-xs"
              >
                未註冊
              </span>
            </div>
            <div class="grid grid-cols-2 gap-4 text-sm text-gray-400 mb-3">
              <div>角色: {{ identity.profile.character_name || '-' }}</div>
              <div>Speaker: {{ identity.profile.speaker_id || '-' }}</div>
              <div>影片: {{ identity.file_uuid }}</div>
              <div>出現次數: {{ identity.stats.appearance_count }}</div>
            </div>
            <div v-if="identity.profile.original_name" class="text-sm text-gray-500">
              原始名稱: {{ identity.profile.original_name }}
            </div>
          </div>
          
          <!-- Actions -->
          <div class="flex space-x-2">
            <button
              v-if="!identity.face_identity_id"
              @click="registerIdentity(identity.person_id, identity.file_uuid)"
              class="bg-green-600 hover:bg-green-700 px-4 py-2 rounded-lg text-sm transition"
            >
              註冊為全域身份
            </button>
            <button
              @click="viewDetails(identity)"
              class="bg-gray-700 hover:bg-gray-600 px-4 py-2 rounded-lg text-sm transition"
            >
              查看詳情
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-else-if="loading" class="text-center py-12 text-gray-500">
      載入中...
    </div>

    <!-- Empty State -->
    <div v-else class="text-center py-12 text-gray-500">
      尚無身份資料
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { listIdentities } from '@/api/client'
import { useRouter } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'

interface IdentityProfile {
  name: string | null
  original_name: string | null
  character_name: string | null
  speaker_id: string | null
}

interface IdentityStats {
  appearance_count: number
  total_duration: number
  first_appearance: number | null
  last_appearance: number | null
}

interface Identity {
  id: number
  person_id: string
  face_identity_id: number | null
  file_uuid: string
  profile: IdentityProfile
  stats: IdentityStats
  is_confirmed: boolean
}

const identities = ref<Identity[]>([])
const loading = ref(false)
const filterQuery = ref('')
const router = useRouter()

const loadIdentities = async () => {
  loading.value = true
  try {
    const result = await listIdentities()
    identities.value = result.identities
  } catch (error) {
    console.error('Failed to load identities:', error)
    alert('載入失敗: ' + error)
  } finally {
    loading.value = false
  }
}

const registerIdentity = async (personId: string, videoUuid: string) => {
  try {
    await invoke('register_identity', {
      personId,
      videoUuid
    })
    alert('註冊成功！')
    await loadIdentities()
  } catch (error) {
    console.error('Registration failed:', error)
    alert('註冊失敗: ' + error)
  }
}

const viewDetails = (identity: Identity) => {
  router.push({
    name: 'video-detail',
    params: { uuid: identity.file_uuid }
  })
}

onMounted(() => {
  loadIdentities()
})
</script>
