<script>
  import { onMount } from 'svelte';
  import { getToken, setToken, clearToken, fetchLinks, updateLink, deleteLink, exportData, downloadBlob } from './api.js';

  let tokenInput = '';
  let authenticated = false;
  let links = [];
  let loading = false;
  let error = '';

  // Edit state
  let editing = null;   // code being edited, or null
  let editUrl = '';
  let editSaving = false;

  // Delete state
  let deleteConfirm = null; // code awaiting confirmation, or null

  // Export state
  let exporting = false;

  onMount(async () => {
    if (getToken()) {
      await loadLinks();
    }
  });

  async function handleLogin() {
    const t = tokenInput.trim();
    if (!t) return;
    setToken(t);
    await loadLinks();
  }

  async function handleLogout() {
    clearToken();
    authenticated = false;
    links = [];
    tokenInput = '';
  }

  async function loadLinks() {
    loading = true;
    error = '';
    try {
      links = await fetchLinks();
      authenticated = true;
    } catch (e) {
      error = e.message;
      authenticated = false;
    } finally {
      loading = false;
    }
  }

  function startEdit(rec) {
    editing = rec.code;
    editUrl = rec.original_url;
    editSaving = false;
    error = '';
  }

  function cancelEdit() {
    editing = null;
    editUrl = '';
  }

  async function saveEdit(code) {
    const url = editUrl.trim();
    if (!url) return;
    editSaving = true;
    error = '';
    try {
      const updated = await updateLink(code, url);
      links = links.map(l => l.code === code ? updated : l);
      editing = null;
      editUrl = '';
    } catch (e) {
      error = e.message;
    } finally {
      editSaving = false;
    }
  }

  function confirmDelete(code) {
    deleteConfirm = code;
    error = '';
  }

  function cancelDelete() {
    deleteConfirm = null;
  }

  async function executeDelete(code) {
    error = '';
    try {
      await deleteLink(code);
      links = links.filter(l => l.code !== code);
      deleteConfirm = null;
    } catch (e) {
      error = e.message;
      deleteConfirm = null;
    }
  }

  async function handleExport(format) {
    exporting = true;
    error = '';
    try {
      const blob = await exportData(format);
      const ext = format === 'csv' ? 'csv' : 'json';
      downloadBlob(blob, `shortlinks.${ext}`);
    } catch (e) {
      error = e.message;
    } finally {
      exporting = false;
    }
  }

  function formatTime(ts) {
    const d = new Date(ts);
    const pad = n => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  }
</script>

<div class="admin-container">
  <header class="admin-header">
    <div class="header-left">
      <h1>管理后台</h1>
      <button class="back-link" on:click={() => window.location.hash = ''}>← 返回</button>
    </div>
    {#if authenticated}
      <button class="btn-logout" on:click={handleLogout}>退出</button>
    {/if}
  </header>

  {#if !authenticated}
    <div class="card token-card">
      <p class="token-prompt">请输入管理 Token</p>
      <div class="token-row">
        <input
          type="password"
          class="token-input"
          placeholder="输入 ADMIN_TOKEN..."
          bind:value={tokenInput}
          on:keydown={(e) => e.key === 'Enter' && handleLogin()}
        />
        <button class="btn" on:click={handleLogin} disabled={!tokenInput.trim()}>
          进入管理
        </button>
      </div>
      {#if error}
        <div class="error">{error}</div>
      {/if}
    </div>
  {:else}
    {#if loading}
      <p class="loading-text">加载中...</p>
    {:else}
      <div class="toolbar">
        <span class="count">共 {links.length} 条记录</span>
        <div class="export-btns">
          <button class="btn-small" on:click={() => handleExport('json')} disabled={exporting}>
            导出 JSON
          </button>
          <button class="btn-small" on:click={() => handleExport('csv')} disabled={exporting}>
            导出 CSV
          </button>
        </div>
      </div>

      {#if error}
        <div class="error">{error}</div>
      {/if}

      {#if links.length === 0}
        <div class="card">
          <p class="empty-text">暂无数据</p>
        </div>
      {:else}
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>短码</th>
                <th>原始链接</th>
                <th class="col-num">访问</th>
                <th class="col-time">创建时间</th>
                <th class="col-action">操作</th>
              </tr>
            </thead>
            <tbody>
              {#each links as rec (rec.code)}
                <tr>
                  <td class="col-code">
                    <a href="/{rec.code}">{rec.code}</a>
                  </td>
                  <td class="col-url">
                    {#if editing === rec.code}
                      <div class="edit-row">
                        <input
                          type="text"
                          class="edit-input"
                          bind:value={editUrl}
                          on:keydown={(e) => e.key === 'Enter' && saveEdit(rec.code)}
                          disabled={editSaving}
                        />
                        <button
                          class="btn-small btn-save"
                          on:click={() => saveEdit(rec.code)}
                          disabled={editSaving || !editUrl.trim()}
                        >保存</button>
                        <button class="btn-small" on:click={cancelEdit} disabled={editSaving}>取消</button>
                      </div>
                    {:else}
                      <span class="url-text" title={rec.original_url}>{rec.original_url}</span>
                    {/if}
                  </td>
                  <td class="col-num">{rec.visit_count}</td>
                  <td class="col-time">{formatTime(rec.created_at)}</td>
                  <td class="col-action">
                    {#if editing === rec.code}
                      <!-- buttons shown inline above -->
                    {:else if deleteConfirm === rec.code}
                      <span class="confirm-text">确认删除?</span>
                      <button class="btn-small btn-yes" on:click={() => executeDelete(rec.code)}>是</button>
                      <button class="btn-small" on:click={cancelDelete}>否</button>
                    {:else}
                      <button class="btn-small" on:click={() => startEdit(rec)}>编辑</button>
                      <button class="btn-small btn-del" on:click={() => confirmDelete(rec.code)}>删除</button>
                    {/if}
                  </td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      {/if}
    {/if}
  {/if}
</div>

<style>
  .admin-container {
    max-width: 960px;
    margin: 0 auto;
    padding: 40px 16px;
  }

  .admin-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .header-left {
    display: flex;
    align-items: baseline;
    gap: 16px;
  }

  .admin-header h1 {
    font-size: 24px;
    font-weight: 700;
  }

  .back-link {
    font-size: 14px;
    color: #4a6cf7;
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    text-decoration: none;
  }

  .back-link:hover {
    text-decoration: underline;
  }

  .btn-logout {
    padding: 8px 16px;
    background: #fff;
    color: #d32f2f;
    border: 1px solid #d32f2f;
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    transition: background 0.2s;
  }

  .btn-logout:hover {
    background: #fff0f0;
  }

  .card {
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  }

  .token-card {
    max-width: 420px;
    margin: 40px auto;
  }

  .token-prompt {
    font-size: 15px;
    color: #444;
    margin-bottom: 12px;
    text-align: center;
  }

  .token-row {
    display: flex;
    gap: 8px;
  }

  .token-input {
    flex: 1;
    padding: 10px 14px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 15px;
    outline: none;
    transition: border-color 0.2s;
  }

  .token-input:focus {
    border-color: #4a6cf7;
  }

  .btn {
    padding: 10px 20px;
    background: #4a6cf7;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    white-space: nowrap;
    transition: background 0.2s;
  }

  .btn:hover:not(:disabled) {
    background: #3b5de7;
  }

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

  .btn-small {
    padding: 5px 12px;
    background: #f0f2f5;
    color: #444;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    white-space: nowrap;
    transition: background 0.2s;
  }

  .btn-small:hover:not(:disabled) {
    background: #e0e0e0;
  }

  .btn-small:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .btn-del {
    color: #d32f2f;
  }

  .btn-del:hover:not(:disabled) {
    background: #fff0f0;
  }

  .btn-save {
    background: #4a6cf7;
    color: #fff;
  }

  .btn-save:hover:not(:disabled) {
    background: #3b5de7;
  }

  .btn-yes {
    background: #d32f2f;
    color: #fff;
  }

  .btn-yes:hover:not(:disabled) {
    background: #b71c1c;
  }

  .error {
    margin-top: 12px;
    padding: 10px 14px;
    background: #fff0f0;
    color: #d32f2f;
    border-radius: 8px;
    font-size: 14px;
  }

  .loading-text {
    text-align: center;
    color: #888;
    padding: 40px;
  }

  .toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
  }

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

  .export-btns {
    display: flex;
    gap: 8px;
  }

  .empty-text {
    text-align: center;
    color: #999;
    padding: 32px;
  }

  .table-wrap {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    overflow: hidden;
  }

  table {
    width: 100%;
    border-collapse: collapse;
  }

  thead {
    background: #f9fafb;
  }

  th {
    padding: 12px 16px;
    text-align: left;
    font-size: 13px;
    font-weight: 600;
    color: #666;
    border-bottom: 1px solid #eee;
  }

  td {
    padding: 12px 16px;
    font-size: 14px;
    border-bottom: 1px solid #f5f5f5;
    vertical-align: middle;
  }

  tr:last-child td {
    border-bottom: none;
  }

  .col-code {
    font-weight: 600;
    white-space: nowrap;
  }

  .col-code a {
    color: #4a6cf7;
    text-decoration: none;
  }

  .col-code a:hover {
    text-decoration: underline;
  }

  .col-url {
    max-width: 320px;
  }

  .url-text {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 320px;
  }

  .col-num {
    width: 60px;
    text-align: right;
  }

  .col-time {
    width: 140px;
    white-space: nowrap;
    font-size: 13px;
    color: #888;
  }

  .col-action {
    width: 140px;
    white-space: nowrap;
  }

  .col-action .btn-small {
    margin-left: 4px;
  }

  .col-action .btn-small:first-child {
    margin-left: 0;
  }

  .edit-row {
    display: flex;
    gap: 4px;
    align-items: center;
  }

  .edit-input {
    flex: 1;
    padding: 6px 10px;
    border: 2px solid #4a6cf7;
    border-radius: 6px;
    font-size: 14px;
    outline: none;
    min-width: 200px;
  }

  .confirm-text {
    font-size: 13px;
    color: #d32f2f;
    margin-right: 4px;
  }

  @media (max-width: 768px) {
    .admin-container {
      padding: 20px 8px;
    }

    .table-wrap {
      overflow-x: auto;
    }

    table {
      min-width: 700px;
    }

    .header-left {
      flex-direction: column;
      gap: 4px;
    }

    .toolbar {
      flex-direction: column;
      gap: 8px;
      align-items: flex-start;
    }
  }
</style>
