<template>
  <div class="admin-container">
    <div v-if="!isLoggedIn" class="glass-card login-card" style="max-width: 400px; margin: 0 auto;">
      <h2 class="text-center mb-1">管理员登录</h2>
      <div v-if="errorMsg" style="color: #ef4444; margin-bottom: 1rem; text-align: center;">{{ errorMsg }}</div>
      
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label>用户名</label>
          <input type="text" v-model="username" class="form-control" required />
        </div>
        <div class="form-group">
          <label>密码</label>
          <input type="password" v-model="password" class="form-control" required />
        </div>
        <button type="submit" class="btn btn-accent" style="width: 100%;">登录</button>
      </form>
    </div>

    <div v-else class="glass-card dashboard-card">
      <div style="display: flex; justify-content: space-between; align-items: center;" class="mb-2">
        <h2>管理员控制台</h2>
        <button @click="logout" class="btn">退出登录</button>
      </div>

      <div class="upload-section mb-2" style="background: rgba(15, 23, 42, 0.4); padding: 1.5rem; border-radius: 8px;">
        <h3 class="mb-1">上传新 PDF 文档</h3>
        <form @submit.prevent="handleUpload">
          <div class="form-group">
            <label>文档标题（可选）</label>
            <input type="text" v-model="uploadTitle" class="form-control" placeholder="默认为文件名..." />
          </div>
          <div class="form-group">
            <label>选择 PDF 文件</label>
            <input type="file" ref="fileInput" accept=".pdf" class="form-control" required />
          </div>
          <button type="submit" class="btn btn-accent" :disabled="uploading">
            {{ uploading ? '正在上传并处理...' : '上传文档' }}
          </button>
          <div v-if="uploadStatus" style="margin-top: 1rem; color: #10b981;">{{ uploadStatus }}</div>
        </form>
      </div>

      <div>
        <h3>管理文档</h3>
        <p style="color: var(--text-muted); margin-bottom: 1rem;">从系统中删除文档。</p>
        
        <div v-for="doc in documents" :key="doc.id" style="display: flex; justify-content: space-between; padding: 1rem; border-top: 1px solid var(--glass-border); align-items: center;">
            <div>
              <strong>{{ doc.title }}</strong><br />
              <span style="font-size: 0.85rem; color: var(--text-muted)">上传时间: {{ new Date(doc.created_at).toLocaleDateString() }}</span>
            </div>
            <button @click="deleteDoc(doc.id)" class="btn" style="background: #ef4444; padding: 0.5rem 1rem; font-size: 0.9rem;">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const API = import.meta.env.VITE_API_BASE_URL;

const isLoggedIn = ref(false);
const username = ref('');
const password = ref('');
const errorMsg = ref('');

const fileInput = ref(null);
const uploadTitle = ref('');
const uploading = ref(false);
const uploadStatus = ref('');
const documents = ref([]);

onMounted(() => {
  const token = localStorage.getItem('admin_token');
  if (token) {
    isLoggedIn.value = true;
    fetchDocs();
  }
});

const handleLogin = async () => {
  try {
    const res = await axios.post(`${API}/api/admin/login`, {
      username: username.value,
      password: password.value
    });
    localStorage.setItem('admin_token', res.data.token);
    isLoggedIn.value = true;
    errorMsg.value = '';
    fetchDocs();
  } catch (err) {
    errorMsg.value = '凭证无效';
  }
};

const logout = () => {
  localStorage.removeItem('admin_token');
  isLoggedIn.value = false;
};

const fetchDocs = async () => {
  try {
    const res = await axios.get(`${API}/api/documents`);
    documents.value = res.data;
  } catch (e) {
    console.error("Failed to load documents");
  }
};

const handleUpload = async () => {
  const file = fileInput.value.files[0];
  if (!file) return;

  uploading.value = true;
  uploadStatus.value = '';
  
  const formData = new FormData();
  formData.append('document', file);
  if (uploadTitle.value) formData.append('title', uploadTitle.value);

  try {
    const token = localStorage.getItem('admin_token');
    await axios.post(`${API}/api/admin/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
      }
    });
    
    uploadStatus.value = '文档上传并处理成功！';
    fileInput.value.value = '';
    uploadTitle.value = '';
    fetchDocs();
  } catch (e) {
    console.error(e);
    uploadStatus.value = '上传文档失败。';
  } finally {
    uploading.value = false;
  }
};

const deleteDoc = async (id) => {
    if(!confirm("确定要执行此操作吗？")) return;
    try {
        const token = localStorage.getItem('admin_token');
        await axios.delete(`${API}/api/admin/documents/${id}`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        fetchDocs();
    } catch(e) {
        alert("删除失败");
    }
}
</script>
