import { useEffect, useState } from 'react';
import { Table, Tag } from 'antd';
import dayjs from 'dayjs';
import { listLogs, OperationLog } from '../api/logs';

const actionMap: Record<string, string> = {
  BATCH_DELETE: '批量删除',
  BATCH_DOWNLOAD: '批量下载',
  BATCH_UPDATE: '批量更新',
};

const actionColor: Record<string, string> = {
  BATCH_DELETE: 'red',
  BATCH_DOWNLOAD: 'blue',
  BATCH_UPDATE: 'green',
};

export default function LogsPage() {
  const [logs, setLogs] = useState<OperationLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const fetchLogs = async (page: number, size: number) => {
    setLoading(true);
    try {
      const result = await listLogs({ pageNo: page, pageSize: size });
      setLogs(result.logs);
      setTotal(result.total);
      setPageNo(result.pageNo);
      setPageSize(result.pageSize);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs(1, 20);
  }, []);

  const columns = [
    {
      title: '时间',
      dataIndex: 'createdAt',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    { title: '用户', dataIndex: 'username', width: 120 },
    {
      title: '操作',
      dataIndex: 'action',
      width: 120,
      render: (action: string) => <Tag color={actionColor[action] || 'default'}>{actionMap[action] || action}</Tag>,
    },
    { title: '目标类型', dataIndex: 'targetType', width: 100 },
    {
      title: '目标 ID',
      dataIndex: 'targetIds',
      ellipsis: true,
      render: (ids: string | null) => ids || '-',
    },
    {
      title: '详情',
      dataIndex: 'details',
      ellipsis: true,
      render: (details: string | null) => (details ? JSON.stringify(JSON.parse(details)) : '-'),
    },
  ];

  return (
    <Table
      rowKey="id"
      columns={columns}
      dataSource={logs}
      loading={loading}
      pagination={{
        current: pageNo,
        pageSize,
        total,
        showSizeChanger: true,
        showTotal: (t) => `共 ${t} 条`,
        onChange: (page, size) => fetchLogs(page, size || 20),
      }}
    />
  );
}
