"use client";

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

interface Room {
  id: string;
  roomName: string;
  isPublic: boolean;
  projectId: string;
  projectName: string;
  workspaceName: string;
  memberCount: number;
  messageCount: number;
  lastMsgAt: string;
}

export default function RoomsPage() {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const pageSize = 30;

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

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

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

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">房间管理</h1>
        <p className="page-subtitle">项目聊天室（只读）</p>
      </div>

      <div className="toolbar">
        <input
          type="text"
          className="form-input search-input"
          placeholder="搜索房间名称..."
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
        />
      </div>

      <div className="card">
        {loading ? <div className="loading">加载中...</div> : rooms.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">💬</div>
            <p>暂无房间</p>
          </div>
        ) : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>房间名称</th>
                  <th>项目</th>
                  <th>可见性</th>
                  <th>成员</th>
                  <th>消息数</th>
                  <th>最后活跃</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {rooms.map((room) => (
                  <tr key={room.id}>
                    <td>{room.roomName}</td>
                    <td>
                      <span style={{ fontSize: "12px" }}>
                        {room.workspaceName ? `${room.workspaceName} / ` : ""}
                        {room.projectName}
                      </span>
                    </td>
                    <td>
                      <span className={`badge ${room.isPublic ? "badge-success" : "badge-neutral"}`}>
                        {room.isPublic ? "公开" : "私有"}
                      </span>
                    </td>
                    <td>{room.memberCount}</td>
                    <td>{room.messageCount.toLocaleString()}</td>
                    <td style={{ fontSize: "12px" }}>
                      {room.lastMsgAt ? format(parseISO(room.lastMsgAt), "yyyy-MM-dd HH:mm") : "—"}
                    </td>
                    <td>
                      <Link href={`/admin/rooms/${room.id}`} className="btn btn-secondary btn-sm">
                        查看
                      </Link>
                    </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>
  );
}
