import { useQuery } from "@tanstack/react-query";
import { useIsSuperuser } from "@modules/auth";
import { Card, List, Space, Typography } from "antd";
import { getAdminActivityFeed, getAdminServerLog } from "../api/adminApi";

export function AdminActivityPanel(): JSX.Element {
  const isSuperuser = useIsSuperuser();
  const { data, isLoading } = useQuery({
    queryKey: ["admin-activity-feed"],
    queryFn: () => getAdminActivityFeed(120)
  });
  const { data: serverLog } = useQuery({
    queryKey: ["admin-server-log"],
    queryFn: () => getAdminServerLog(80),
    enabled: isSuperuser
  });

  if (isLoading || !data) {
    return <p className="wesp-admin-block">Loading activity...</p>;
  }

  return (
    <div className="wesp-admin-grid">
      <Typography.Title level={4} style={{ margin: 0 }}>
        Activity
      </Typography.Title>
      <Card>
        <List
          dataSource={data.events}
          renderItem={(event, index) => (
            <List.Item key={`${String(event.timestamp ?? "event")}-${index}`}>
              <Space direction="vertical" size={0}>
                <strong>{String(event.action ?? "event")}</strong>
                <Typography.Text type="secondary">{String(event.timestamp ?? "")}</Typography.Text>
              </Space>
            </List.Item>
          )}
        />
      </Card>
      {isSuperuser && serverLog ? (
        <Card title="Server log">
          <pre className="wesp-admin-log">{serverLog.lines.join("\n")}</pre>
        </Card>
      ) : null}
    </div>
  );
}
