<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDeviceStore } from '@/stores/device'
import { useAuthStore } from '@/stores/auth'
import AppLayout from '@/components/layout/AppLayout.vue'
import type { Device } from '@/types'

const deviceStore = useDeviceStore()
const authStore = useAuthStore()

const showRenameDialog = ref(false)
const renamingDevice = ref<Device | null>(null)
const newDeviceName = ref('')

const devices = computed(() => deviceStore.devices)
const currentDeviceId = computed(() => authStore.device?.id)

onMounted(async () => {
  await deviceStore.fetchDevices()
})

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleString('zh-CN')
}

function handleRename(device: Device) {
  renamingDevice.value = device
  newDeviceName.value = device.deviceName
  showRenameDialog.value = true
}

async function submitRename() {
  if (!renamingDevice.value || !newDeviceName.value.trim()) return

  try {
    const response = await deviceStore.updateDeviceName(
      renamingDevice.value.id,
      newDeviceName.value.trim()
    )
    if (response.success) {
      ElMessage.success('重命名成功')
      showRenameDialog.value = false
    } else {
      ElMessage.error(response.message || '重命名失败')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '重命名失败')
  }
}

async function handleSetAdmin(device: Device) {
  try {
    await ElMessageBox.confirm(
      `确定要将 "${device.deviceName}" 设置为管理员设备吗？原管理员设备将失去管理员权限。`,
      '设置管理员设备',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await deviceStore.setAdminDevice(device.id)
    if (response.success) {
      ElMessage.success('设置成功')
    }
  } catch {
    // 取消
  }
}

async function handleDelete(device: Device) {
  if (device.isAdmin) {
    ElMessage.warning('无法删除管理员设备，请先将管理员权限转移到其他设备')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除设备 "${device.deviceName}" 吗？该设备将被强制退出登录。`,
      '删除设备',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    const response = await deviceStore.deleteDevice(device.id)
    if (response.success) {
      ElMessage.success('删除成功')
    }
  } catch {
    // 取消
  }
}
</script>

<template>
  <AppLayout>
    <div class="devices-view">
      <div class="page-header">
        <h1>设备管理</h1>
        <p>管理您登录过的所有设备</p>
      </div>

      <div class="devices-list">
        <div
          v-for="device in devices"
          :key="device.id"
          class="device-card"
          :class="{ current: device.id === currentDeviceId }"
        >
          <div class="device-icon">
            <el-icon size="32">
              <Monitor v-if="device.deviceType.includes('Windows') || device.deviceType.includes('Mac')" />
              <Cellphone v-else-if="device.deviceType.includes('Android') || device.deviceType.includes('iOS')" />
              <Monitor v-else />
            </el-icon>
          </div>

          <div class="device-info">
            <div class="device-name">
              {{ device.deviceName }}
              <el-tag v-if="device.isAdmin" size="small" type="warning">管理员设备</el-tag>
              <el-tag v-if="device.id === currentDeviceId" size="small" type="success">当前设备</el-tag>
            </div>
            <div class="device-type">{{ device.deviceType }}</div>
            <div class="device-time">
              <span>首次登录: {{ formatDate(device.createdAt) }}</span>
              <span>最后活跃: {{ formatDate(device.lastActiveAt) }}</span>
            </div>
          </div>

          <div class="device-actions">
            <el-button size="small" @click="handleRename(device)">
              <el-icon><Edit /></el-icon>
              重命名
            </el-button>
            <el-button
              v-if="!device.isAdmin"
              size="small"
              type="primary"
              @click="handleSetAdmin(device)"
            >
              <el-icon><Star /></el-icon>
              设为管理员
            </el-button>
            <el-button
              v-if="device.id !== currentDeviceId && !device.isAdmin"
              size="small"
              type="danger"
              @click="handleDelete(device)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>

        <el-empty v-if="devices.length === 0" description="暂无设备" />
      </div>

      <!-- 重命名对话框 -->
      <el-dialog v-model="showRenameDialog" title="重命名设备" width="400px">
        <el-input v-model="newDeviceName" placeholder="请输入新的设备名称" />
        <template #footer>
          <el-button @click="showRenameDialog = false">取消</el-button>
          <el-button type="primary" @click="submitRename">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </AppLayout>
</template>

<style lang="scss" scoped>
.devices-view {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  p {
    color: #666;
    font-size: 14px;
  }
}

.devices-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.device-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.current {
    border: 2px solid #67c23a;
  }

  .device-icon {
    width: 60px;
    height: 60px;
    background: #f5f5f5;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
  }

  .device-info {
    flex: 1;

    .device-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 4px;
    }

    .device-type {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .device-time {
      display: flex;
      gap: 16px;
      font-size: 12px;
      color: #999;
    }
  }

  .device-actions {
    display: flex;
    gap: 8px;
  }
}
</style>

