import { Descriptions, Drawer, Tag, Typography } from 'antd'
import dayjs from 'dayjs'
import type { OperationLog } from '@/types/operation-log'
import styles from './OperationLogsPage.module.css'

const { Paragraph, Text } = Typography

interface OperationLogDetailDrawerProps {
  open: boolean
  log: OperationLog | null
  onClose: () => void
}

// Strip HTML tags to prevent XSS when rendering user-controlled fields
function stripHtmlTags(text: string | undefined | null): string {
  if (!text) return '-'
  return text.replace(/<[^>]*>/g, '')
}

export function OperationLogDetailDrawer({ open, log, onClose }: OperationLogDetailDrawerProps) {
  if (!log) {
    return null
  }

  return (
    <Drawer title="操作日志详情" placement="right" width={720} open={open} onClose={onClose}>
      <Descriptions column={1} bordered size="small">
        <Descriptions.Item label="日志 ID">{log.id}</Descriptions.Item>
        <Descriptions.Item label="用户 ID">{log.user_id ?? '-'}</Descriptions.Item>
        <Descriptions.Item label="操作类型">{log.operation_type || '-'}</Descriptions.Item>
        <Descriptions.Item label="操作名称">{log.operation_name || '-'}</Descriptions.Item>
        <Descriptions.Item label="请求方法">
          <Tag>{log.request_method}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="请求路径">
          <Paragraph copyable style={{ marginBottom: 0 }}>
            <Text>{stripHtmlTags(log.request_path)}</Text>
          </Paragraph>
        </Descriptions.Item>
        <Descriptions.Item label="请求参数">
          <pre className={styles.codeBlock}><Text>{stripHtmlTags(log.request_params)}</Text></pre>
        </Descriptions.Item>
        <Descriptions.Item label="状态码">
          <Tag color={log.response_status >= 200 && log.response_status < 300 ? 'success' : 'error'}>
            {log.response_status}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="IP 地址">{log.ip}</Descriptions.Item>
        <Descriptions.Item label="User Agent">
          <div style={{ wordBreak: 'break-all', fontSize: 12 }}>
            <Text>{stripHtmlTags(log.user_agent)}</Text>
          </div>
        </Descriptions.Item>
        <Descriptions.Item label="操作时间">
          {dayjs(log.created_at).format('YYYY-MM-DD HH:mm:ss')}
        </Descriptions.Item>
      </Descriptions>
    </Drawer>
  )
}
