import React, { useEffect, useState } from 'react';
import {
  Button, Card, Space, Table, Tag, Typography, message,
} from 'antd';
import {
  HistoryOutlined, ReloadOutlined,
} from '@ant-design/icons';
import { getOperationLogs } from '../api';
import { formatDate } from '../utils/formatDate';

interface OperationLog {
  id: string;
  userId: string;
  username: string;
  action: string;
  method: string;
  path: string;
  detail?: string;
  ip?: string;
  createdAt: string;
}

const METHOD_COLORS: Record<string, string> = { POST: 'green', PUT: 'blue', DELETE: 'red' };

const AdminOperationLogs: React.FC = () => {
  const [logs, setLogs] = useState<OperationLog[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  const load = async (p?: number) => {
    setLoading(true);
    try {
      const res = await getOperationLogs(p || page);
      setLogs(res.items || []);
      setTotal(res.total || 0);
    } catch {
      message.error('加载操作日志失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const columns = [
    {
      title: '操作人', dataIndex: 'username', width: 120,
      render: (v: string) => <Typography.Text strong>{v}</Typography.Text>,
    },
    {
      title: '操作', dataIndex: 'action', width: 160,
      render: (v: string) => <Typography.Text>{v}</Typography.Text>,
    },
    {
      title: '方法', dataIndex: 'method', width: 80,
      render: (v: string) => <Tag color={METHOD_COLORS[v] || 'default'}>{v}</Tag>,
    },
    {
      title: '路径', dataIndex: 'path', width: 220, ellipsis: true,
      render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{v}</Typography.Text>,
    },
    {
      title: '时间', dataIndex: 'createdAt', width: 160,
      render: (v: string) => <Typography.Text type="secondary" style={{ fontSize: 12 }}>{formatDate(v)}</Typography.Text>,
    },
  ];

  return (
    <div>
      <Card variant="outlined" style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Space>
            <HistoryOutlined style={{ fontSize: 18, color: '#6366f1' }} />
            <Typography.Text strong style={{ fontSize: 16 }}>操作日志</Typography.Text>
          </Space>
          <Button icon={<ReloadOutlined />} onClick={() => load()}>刷新</Button>
        </div>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            pageSize: 20,
            total,
            showTotal: (t) => `共 ${t} 条记录`,
            onChange: (p) => { setPage(p); load(p); },
          }}
          scroll={{ x: 800 }}
        />
      </Card>
    </div>
  );
};

export default AdminOperationLogs;
