"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { format, parseISO } from "date-fns";

interface Message {
  id: string;
  seq: number;
  senderType: string;
  senderId: string | null;
  senderName: string | null;
  content: string;
  contentType: string;
  sendAt: string;
  revoked: string | null;
  inReplyTo: string | null;
}

const SENDER_LABELS: Record<string, string> = {
  user: "用户", member: "用户", ai: "AI", system: "系统", bot: "Bot",
};

const CONTENT_TYPE_LABELS: Record<string, string> = {
  text: "文本", markdown: "Markdown", code: "代码", image: "图片",
};

export default function RoomDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [messages, setMessages] = useState<Message[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [revoking, setRevoking] = useState<string | null>(null);
  const pageSize = 50;

  useEffect(() => { loadMessages(); }, [page]);

  function loadMessages() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    fetch(`/api/platform/rooms/${id}/messages?${params}`)
      .then((r) => r.json())
      .then((data) => {
        setMessages(data.messages || []);
        setTotal(data.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  async function revokeMessage(msgId: string) {
    if (!confirm("确定撤回此消息？")) return;
    setRevoking(msgId);
    try {
      const res = await fetch(`/api/platform/rooms/${id}/messages/${msgId}`, { method: "DELETE" });
      if (res.ok) {
        setMessages((msgs) => msgs.map((m) => m.id === msgId ? { ...m, revoked: new Date().toISOString() } : m));
      } else {
        const data = await res.json();
        alert(data.error || "撤回失败");
      }
    } finally {
      setRevoking(null);
    }
  }

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">房间消息</h1>
        <p className="page-subtitle">ID: {id}</p>
      </div>

      <div className="toolbar">
        <span style={{ fontSize: "13px", color: "#737373" }}>
          共 {total.toLocaleString()} 条消息
        </span>
      </div>

      <div className="card">
        {loading ? <div className="loading">加载中...</div> : messages.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">💬</div>
            <p>暂无消息</p>
          </div>
        ) : (
          <div style={{ maxHeight: "600px", overflow: "auto" }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th style={{ width: "60px" }}>序号</th>
                  <th style={{ width: "140px" }}>发送者</th>
                  <th>内容</th>
                  <th style={{ width: "80px" }}>类型</th>
                  <th style={{ width: "160px" }}>时间</th>
                  <th style={{ width: "80px" }}>操作</th>
                </tr>
              </thead>
              <tbody>
                {messages.map((msg) => (
                  <tr key={msg.id} style={{ opacity: msg.revoked ? "0.5" : "1" }}>
                    <td style={{ fontSize: "11px", fontFamily: "monospace" }}>#{msg.seq}</td>
                    <td>
                      <div style={{ fontSize: "12px" }}>
                        <div style={{ fontWeight: 500 }}>
                          {msg.senderName || <span style={{ color: "#a3a3a3" }}>未知</span>}
                        </div>
                        <div style={{ color: "#737373", fontSize: "11px" }}>
                          {SENDER_LABELS[msg.senderType] || msg.senderType}
                        </div>
                      </div>
                    </td>
                    <td style={{ maxWidth: "400px" }}>
                      {msg.revoked ? (
                        <span style={{ color: "#a3a3a3", fontStyle: "italic", fontSize: "12px" }}>
                          [此消息已被撤回]
                        </span>
                      ) : (
                        <span
                          style={{
                            fontSize: "12px",
                            fontFamily: msg.contentType === "code" ? "monospace" : "inherit",
                            display: "block",
                            maxWidth: "400px",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                          }}
                          title={msg.content}
                        >
                          {msg.content.slice(0, 200)}
                        </span>
                      )}
                    </td>
                    <td>
                      <span className="badge badge-neutral">
                        {CONTENT_TYPE_LABELS[msg.contentType] || msg.contentType}
                      </span>
                    </td>
                    <td style={{ fontSize: "11px" }}>
                      {format(parseISO(msg.sendAt), "yyyy-MM-dd HH:mm:ss")}
                    </td>
                    <td>
                      {!msg.revoked && (
                        <button
                          className="btn btn-secondary btn-sm"
                          disabled={revoking === msg.id}
                          onClick={() => revokeMessage(msg.id)}
                          style={{ fontSize: "11px", padding: "2px 8px" }}
                        >
                          {revoking === msg.id ? "..." : "撤回"}
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {totalPages > 1 && (
        <div className="pagination">
          <span className="pagination-info">第 {page} / {totalPages} 页，共 {total} 条</span>
          <button className="btn btn-secondary btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button>
          <button className="btn btn-secondary btn-sm" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>下一页</button>
        </div>
      )}
    </div>
  );
}
