<template>
  <div class="settings-view">
    <div class="settings-header">
      <h2>设置</h2>
      <p>配置 OpenList 后端接口，绑定您的云盘账户</p>
    </div>

    <div class="settings-card">
      <h3 class="settings-card__title">
        <span class="settings-card__icon">🔗</span>
        OpenList 绑定
      </h3>

      <form class="settings-form" @submit.prevent="handleBind">
        <!-- OpenList 地址 -->
        <div class="form-group">
          <label class="form-label" for="openlist-url">
            <span class="form-label__icon">🌐</span>
            <span class="form-label__text">OpenList 地址</span>
          </label>
          <input
            id="openlist-url"
            v-model="formData.url"
            type="url"
            class="form-input"
            placeholder="例如：https://olist.example.com 或 http://localhost:5575"
            required
            autocomplete="off"
          />
          <span class="form-help">请填写 OpenList 服务的完整访问地址，包含协议头</span>
        </div>

        <!-- 账号 -->
        <div class="form-group">
          <label class="form-label" for="openlist-username">
            <span class="form-label__icon">👤</span>
            <span class="form-label__text">账号</span>
          </label>
          <input
            id="openlist-username"
            v-model="formData.username"
            type="text"
            class="form-input"
            placeholder="请输入 OpenList 用户名"
            required
            autocomplete="username"
          />
        </div>

        <!-- 密码 -->
        <div class="form-group">
          <label class="form-label" for="openlist-password">
            <span class="form-label__icon">🔒</span>
            <span class="form-label__text">密码</span>
          </label>
          <div class="password-input-wrapper">
            <input
              id="openlist-password"
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              class="form-input"
              placeholder="请输入 OpenList 密码"
              required
              autocomplete="current-password"
            />
            <button
              type="button"
              class="password-toggle"
              @click="showPassword = !showPassword"
              :title="showPassword ? '隐藏密码' : '显示密码'"
            >
              {{ showPassword ? '🙈' : '👁️' }}
            </button>
          </div>
        </div>

        <!-- 绑定按钮 -->
        <div class="form-actions">
          <button
            type="submit"
            class="btn-bind"
            :disabled="binding"
            :class="{ 'btn-bind--loading': binding }"
          >
            <span v-if="!binding">🔗 绑定 OpenList</span>
            <span v-else class="loading-spinner">⏳ 绑定中...</span>
          </button>
          <button
            type="button"
            class="btn-reset"
            @click="resetForm"
            :disabled="binding"
          >
            重置
          </button>
        </div>
      </form>

      <!-- 绑定状态提示 -->
      <Transition name="fade">
        <div v-if="bindStatus" class="bind-status" :class="`bind-status--${bindStatus.type}`">
          <span class="bind-status__icon">{{ bindStatus.icon }}</span>
          <span class="bind-status__text">{{ bindStatus.message }}</span>
        </div>
      </Transition>

      <!-- 已绑定信息 -->
      <Transition name="fade">
        <div v-if="boundInfo" class="bound-info">
          <div class="bound-info__header">
            <span class="bound-info__icon">✅</span>
            <span class="bound-info__text">已绑定 OpenList</span>
          </div>
          <div class="bound-info__details">
            <div class="bound-info__item">
              <span class="bound-info__label">地址：</span>
              <span class="bound-info__value">{{ boundInfo.url }}</span>
            </div>
            <div class="bound-info__item">
              <span class="bound-info__label">账号：</span>
              <span class="bound-info__value">{{ boundInfo.username }}</span>
            </div>
            <div class="bound-info__item">
              <span class="bound-info__label">绑定时间：</span>
              <span class="bound-info__value">{{ boundInfo.boundAt }}</span>
            </div>
          </div>
          <button
            type="button"
            class="btn-unbind"
            @click="handleUnbind"
          >
            🗑️ 解除绑定
          </button>
        </div>
      </Transition>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { bindOpenList, unbindOpenList, fetchOpenListStatus } from '../api'

// 表单数据
const formData = reactive({
  url: '',
  username: '',
  password: '',
})

// 状态控制
const binding = ref(false)
const showPassword = ref(false)
const bindStatus = ref(null)
const boundInfo = ref(null)

/**
 * 加载已绑定的 OpenList 信息
 */
async function loadBoundInfo() {
  try {
    const result = await fetchOpenListStatus()
    if (result?.code === 200 && result?.data?.bound) {
      boundInfo.value = {
        url: result.data.url || '',
        username: result.data.username || '',
        boundAt: result.data.boundAt || '-',
      }
    }
  } catch (err) {
    console.warn('加载绑定信息失败:', err)
  }
}

/**
 * 处理绑定表单提交
 */
async function handleBind() {
  if (!formData.url || !formData.username || !formData.password) {
    setBindStatus('error', '请填写所有必填字段')
    return
  }

  // 验证 URL 格式
  try {
    new URL(formData.url)
  } catch {
    setBindStatus('error', '请输入有效的 URL 地址（需包含协议头，如 https://）')
    return
  }

  binding.value = true
  setBindStatus(null, '')

  try {
    const result = await bindOpenList({
      url: formData.url,
      username: formData.username,
      password: formData.password,
    })

    if (result?.code === 200) {
      setBindStatus('success', '绑定成功！')
      boundInfo.value = {
        url: formData.url,
        username: formData.username,
        boundAt: new Date().toLocaleString('zh-CN'),
      }
      // 清空密码字段
      formData.password = ''
      // 重新加载绑定信息
      await loadBoundInfo()
    } else {
      setBindStatus('error', result?.message || '绑定失败，请稍后重试')
    }
  } catch (err) {
    console.error('绑定 OpenList 失败:', err)
    const errorMsg = err?.message || err?.payload?.message || '网络错误，请检查后端连接'
    setBindStatus('error', errorMsg)
  } finally {
    binding.value = false
  }
}

/**
 * 处理解除绑定
 */
async function handleUnbind() {
  if (!confirm('确定要解除 OpenList 绑定吗？')) {
    return
  }

  try {
    const result = await unbindOpenList()
    if (result?.code === 200) {
      setBindStatus('success', '已解除绑定')
      boundInfo.value = null
      resetForm()
      setTimeout(() => {
        setBindStatus(null, '')
      }, 3000)
    } else {
      setBindStatus('error', result?.message || '解除绑定失败')
    }
  } catch (err) {
    console.error('解除绑定失败:', err)
    setBindStatus('error', err?.message || '网络错误')
  }
}

/**
 * 重置表单
 */
function resetForm() {
  formData.url = ''
  formData.username = ''
  formData.password = ''
  setBindStatus(null, '')
}

/**
 * 设置绑定状态提示
 */
function setBindStatus(type, message) {
  if (!type) {
    bindStatus.value = null
    return
  }

  const icons = {
    success: '✅',
    error: '❌',
    warning: '⚠️',
    info: 'ℹ️',
  }

  bindStatus.value = {
    type,
    message,
    icon: icons[type] || '',
  }

  // 3秒后自动清除
  if (type !== 'success') {
    setTimeout(() => {
      bindStatus.value = null
    }, 3000)
  }
}

// 组件挂载时加载已绑定信息
onMounted(() => {
  loadBoundInfo()
})
</script>

<style scoped>
.settings-view {
  max-width: 720px;
  margin: 0 auto;
  padding: 24px 16px;
}

.settings-header {
  margin-bottom: 24px;
}

.settings-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.settings-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 卡片样式 */
.settings-card {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e8e8e8;
}

.settings-card__title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 24px 0;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.settings-card__icon {
  font-size: 20px;
}

/* 表单样式 */
.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.form-label__icon {
  font-size: 16px;
}

.form-input {
  width: 100%;
  padding: 10px 14px;
  font-size: 14px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
}

.form-input:hover {
  border-color: #409eff;
}

.form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.15);
}

.form-input::placeholder {
  color: #bfbfbf;
}

.form-help {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  color: #999;
}

/* 密码输入框 */
.password-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.password-input-wrapper .form-input {
  padding-right: 44px;
}

.password-toggle {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.password-toggle:hover {
  background-color: #f5f5f5;
}

/* 按钮组 */
.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 28px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.btn-bind {
  flex: 1;
  padding: 12px 24px;
  font-size: 15px;
  font-weight: 500;
  color: #fff;
  background: linear-gradient(135deg, #409eff, #337ecc);
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 140px;
}

.btn-bind:hover:not(:disabled) {
  background: linear-gradient(135deg, #66b1ff, #409eff);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.btn-bind:active:not(:disabled) {
  transform: translateY(0);
}

.btn-bind:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-bind--loading {
  background: linear-gradient(135deg, #909399, #69696d);
}

.btn-reset {
  padding: 12px 24px;
  font-size: 14px;
  color: #666;
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
}

.btn-reset:hover:not(:disabled) {
  color: #409eff;
  border-color: #409eff;
  background: #ecf5ff;
}

.btn-reset:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 状态提示 */
.bind-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  margin-top: 20px;
  border-radius: 8px;
  font-size: 14px;
}

.bind-status--success {
  background: #f0f9ff;
  border: 1px solid #b3e19c;
  color: #67c23a;
}

.bind-status--error {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  color: #f56c6c;
}

.bind-status__icon {
  font-size: 16px;
}

/* 已绑定信息 */
.bound-info {
  margin-top: 20px;
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #b3e19c;
  border-radius: 8px;
}

.bound-info__header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #67c23a;
  margin-bottom: 12px;
}

.bound-info__details {
  margin-bottom: 16px;
}

.bound-info__item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
  margin-bottom: 6px;
}

.bound-info__label {
  color: #999;
  min-width: 70px;
}

.bound-info__value {
  color: #333;
  word-break: break-all;
}

.btn-unbind {
  width: 100%;
  padding: 8px 16px;
  font-size: 13px;
  color: #f56c6c;
  background: #fff;
  border: 1px solid #fbc4c4;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-unbind:hover {
  background: #fef0f0;
  border-color: #f56c6c;
}

/* 加载动画 */
.loading-spinner {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .settings-header h2 {
    color: #e5e5e5;
  }

  .settings-header p {
    color: #999;
  }

  .settings-card {
    background: #2a2a2a;
    border-color: #3a3a3a;
  }

  .settings-card__title {
    color: #e5e5e5;
    border-bottom-color: #3a3a3a;
  }

  .form-label {
    color: #ccc;
  }

  .form-input {
    background: #1a1a1a;
    border-color: #3a3a3a;
    color: #e5e5e5;
  }

  .form-input:hover {
    border-color: #409eff;
  }

  .form-input:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  .form-input::placeholder {
    color: #666;
  }

  .password-toggle:hover {
    background-color: #333;
  }

  .btn-reset {
    color: #ccc;
    background: #333;
    border-color: #444;
  }

  .btn-reset:hover:not(:disabled) {
    color: #409eff;
    border-color: #409eff;
    background: #1a2a3a;
  }

  .bound-info {
    background: #1a2a3a;
    border-color: #2a4a5a;
  }

  .bound-info__item {
    color: #999;
  }

  .bound-info__value {
    color: #ccc;
  }

  .btn-unbind {
    color: #f56c6c;
    background: #2a1a1a;
    border-color: #4a2a2a;
  }

  .btn-unbind:hover {
    background: #3a1a1a;
    border-color: #f56c6c;
  }
}

/* 响应式 */
@media (max-width: 600px) {
  .settings-view {
    padding: 16px 12px;
  }

  .settings-card {
    padding: 16px;
  }

  .form-actions {
    flex-direction: column;
  }

  .btn-bind,
  .btn-reset {
    width: 100%;
  }
}
</style>