/**
 * 充电桩大盘 - 留言模块
 */

import { state } from './state.js';
import { escapeHtml, showToast, refreshIcons } from './utils.js';
import { createTimedCache } from './perf-cache.js';

// 当前打开留言的充电桩信息
let currentCommentCharger = null;

// Mock 留言数据
const mockComments = {};
const commentCountCache = createTimedCache(2 * 60 * 1000);

// 是否为 Mock 模式
function isMockMode() {
  const params = new URLSearchParams(window.location.search);
  if (params.get('mock') === 'true') return true;
  if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    return params.has('mock') || !window.RUNTIME_CONFIG?.apiAvailable;
  }
  return false;
}

/**
 * 打开留言弹窗
 */
export function showCommentModal(connectorId, connectorName) {
  currentCommentCharger = { connectorId, connectorName };

  // 设置标题
  document.getElementById('comment-modal-title').textContent = `${connectorName} 留言`;

  // 清空输入
  document.getElementById('comment-feishu-name').value = localStorage.getItem('comment_feishu_name') || '';
  document.getElementById('comment-content').value = '';

  // 加载留言列表
  loadComments(connectorId);

  // 显示弹窗
  document.getElementById('comment-modal').classList.add('show');
}

/**
 * 隐藏留言弹窗
 */
export function hideCommentModal(e) {
  if (e && e.target !== e.currentTarget) return;
  document.getElementById('comment-modal').classList.remove('show');
  currentCommentCharger = null;
}

/**
 * 加载留言列表
 */
async function loadComments(connectorId) {
  const listEl = document.getElementById('comment-list');
  listEl.innerHTML = '<div class="text-center text-slate-500 text-sm py-4">加载中...</div>';

  // Mock 模式
  if (isMockMode()) {
    const comments = mockComments[connectorId] || [];
    if (comments.length > 0) {
      listEl.innerHTML = comments.map(comment => `
        <div class="text-sm">
          <div class="flex items-center gap-2 mb-1">
            <span class="text-slate-300 font-medium">${escapeHtml(comment.feishu_name)}</span>
            <span class="text-slate-600 text-xs">${formatTime(comment.created_at)}</span>
          </div>
          <div class="text-slate-400 pl-0">${escapeHtml(comment.content)}</div>
        </div>
      `).join('');
    } else {
      listEl.innerHTML = '<div class="text-center text-slate-500 text-sm py-4">暂无留言</div>';
    }
    return;
  }

  try {
    const res = await fetch(`/api/comments/${connectorId}`);
    const result = await res.json();

    if (result.success && result.data && result.data.length > 0) {
      listEl.innerHTML = result.data.map(comment => `
        <div class="text-sm">
          <div class="flex items-center gap-2 mb-1">
            <span class="text-slate-300 font-medium">${escapeHtml(comment.feishu_name)}</span>
            <span class="text-slate-600 text-xs">${formatTime(comment.created_at)}</span>
          </div>
          <div class="text-slate-400 pl-0">${escapeHtml(comment.content)}</div>
        </div>
      `).join('');
    } else {
      listEl.innerHTML = '<div class="text-center text-slate-500 text-sm py-4">暂无留言</div>';
    }
  } catch (err) {
    console.error('加载留言失败:', err);
    listEl.innerHTML = '<div class="text-center text-slate-500 text-sm py-4">暂无留言</div>';
  }
}

/**
 * 填充快捷短语
 */
export function fillComment(text) {
  document.getElementById('comment-content').value = text;
  document.getElementById('comment-content').focus();
}

/**
 * 提交留言
 */
export async function submitComment() {
  if (!currentCommentCharger) return;

  const feishuName = document.getElementById('comment-feishu-name').value.trim();
  const content = document.getElementById('comment-content').value.trim();

  // 验证
  if (!feishuName) {
    showToast('请填写飞书花名', 'error');
    return;
  }
  if (feishuName.length > 10) {
    showToast('飞书花名不能超过10个字', 'error');
    return;
  }
  if (!content) {
    showToast('留言内容不能为空', 'error');
    return;
  }
  if (content.length > 20) {
    showToast('留言内容不能超过20个字', 'error');
    return;
  }

  // 保存花名到本地
  localStorage.setItem('comment_feishu_name', feishuName);

  const btn = document.getElementById('comment-submit-btn');
  btn.disabled = true;
  btn.textContent = '提交中...';

  // Mock 模式
  if (isMockMode()) {
    const connectorId = currentCommentCharger.connectorId;
    if (!mockComments[connectorId]) {
      mockComments[connectorId] = [];
    }

    // 频率限制检查
    const now = Date.now();
    const recentComment = mockComments[connectorId].find(c =>
      c.feishu_name === feishuName && (now - new Date(c.created_at).getTime()) < 5 * 60 * 1000
    );
    if (recentComment) {
      showToast('5分钟内已留言，请稍后再试', 'error');
      btn.disabled = false;
      btn.textContent = '提交';
      return;
    }

    mockComments[connectorId].unshift({
      id: Date.now(),
      feishu_name: feishuName,
      content: content,
      created_at: new Date().toISOString()
    });

    showToast('留言成功', 'success');
    document.getElementById('comment-content').value = '';
    loadComments(connectorId);
    commentCountCache.delete(connectorId);
    updateCardCommentCount(connectorId);
    btn.disabled = false;
    btn.textContent = '提交';
    hideCommentModal();
    return;
  }

  try {
    const res = await fetch('/api/comment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        connector_id: currentCommentCharger.connectorId,
        connector_name: currentCommentCharger.connectorName,
        feishu_name: feishuName,
        content: content
      })
    });

    const result = await res.json();

    if (result.success) {
      showToast('留言成功', 'success');
      document.getElementById('comment-content').value = '';
      commentCountCache.delete(currentCommentCharger.connectorId);
      // 重新加载留言列表
      loadComments(currentCommentCharger.connectorId);
      // 更新卡片留言数
      updateCardCommentCount(currentCommentCharger.connectorId);
      // 关闭弹窗
      hideCommentModal();
    } else {
      showToast(result.message || '留言失败', 'error');
    }
  } catch (err) {
    console.error('提交留言失败:', err);
    showToast('网络连接失败', 'error');
  } finally {
    btn.disabled = false;
    btn.textContent = '提交';
  }
}

/**
 * 更新卡片留言数显示
 */
function updateCardCommentCount(connectorId) {
  if (isMockMode()) {
    const comments = mockComments[connectorId] || [];
    updateCardCommentDisplay(connectorId, comments.length, comments.length > 0 ? comments[0] : null);
    return;
  }

  const countEl = document.getElementById(`comment-count-${connectorId}`);
  if (countEl) {
    const cached = commentCountCache.get(connectorId);
    if (cached) {
      updateCardCommentDisplay(connectorId, cached.count || 0, cached.latest || null);
      return;
    }

    fetch('/api/comments/batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ connector_ids: [connectorId] })
    })
    .then(res => res.json())
    .then(result => {
      if (result.success) {
        const info = result.data[connectorId] || {};
        const count = info.count || 0;
        commentCountCache.set(connectorId, { count, latest: info.latest || null });
        updateCardCommentDisplay(connectorId, count, info.latest || null);
      }
    })
    .catch(() => {});
  }
}

/**
 * 批量获取留言数量并更新卡片
 */
export async function refreshCommentCounts(connectorIds) {
  if (!connectorIds || connectorIds.length === 0) return;

  // Mock 模式
  if (isMockMode()) {
    for (const connectorId of connectorIds) {
      const comments = mockComments[connectorId] || [];
      const count = comments.length;
      updateCardCommentDisplay(connectorId, count, count > 0 ? comments[0] : null);
    }
    return;
  }

  try {
    const missingIds = [];
    for (const connectorId of connectorIds) {
      const cached = commentCountCache.get(connectorId);
      if (cached) {
        updateCardCommentDisplay(connectorId, cached.count || 0, cached.latest || null);
      } else {
        missingIds.push(connectorId);
      }
    }

    if (missingIds.length === 0) return;

    const res = await fetch('/api/comments/batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ connector_ids: missingIds })
    });

    const result = await res.json();
    if (result.success) {
      for (const [connectorId, info] of Object.entries(result.data)) {
        commentCountCache.set(connectorId, {
          count: info.count || 0,
          latest: info.latest || null,
        });
        updateCardCommentDisplay(connectorId, info.count || 0, info.latest || null);
      }
    }
  } catch (err) {
    console.error('获取留言数量失败:', err);
  }
}

/**
 * 更新单个卡片的留言显示（数量气泡 + 最新留言替换调侃）
 */
function updateCardCommentDisplay(connectorId, count, latest) {
  // 更新留言数气泡
  const countEl = document.getElementById(`comment-count-${connectorId}`);
  if (countEl) {
    const textEl = countEl.querySelector('.comment-count-text');
    if (count > 0) {
      if (textEl) textEl.textContent = `${count}条留言`;
      countEl.classList.remove('hidden');
    } else {
      countEl.classList.add('hidden');
    }
  }

  // 用最新留言替换调侃语录
  const jokeEl = document.getElementById(`joke-${connectorId}`);
  if (jokeEl && latest) {
    const timeText = latest.created_at ? formatTime(latest.created_at) : '';
    const meta = [escapeHtml(latest.feishu_name), timeText].filter(Boolean).join(' · ');
    jokeEl.innerHTML = `<i data-lucide="message-circle" class="w-3 h-3 inline-block opacity-50 -mt-0.5"></i> <span class="text-cyan-400/70">${escapeHtml(latest.content)}</span> <span class="text-slate-600">${meta}</span>`;
    jokeEl.classList.remove('italic', 'text-slate-500');
    jokeEl.classList.add('comment-replace-in');
    refreshIcons();
  }
}

/**
 * 格式化时间
 */
function formatTime(dateStr) {
  const date = new Date(dateStr);
  const now = new Date();
  const diff = Math.floor((now - date) / 1000);

  if (diff < 60) return '刚刚';
  if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
  return `${Math.floor(diff / 86400)}天前`;
}
