import { useIntl } from '@umijs/max';
import { Card, Descriptions, Drawer, Space, Tag, Typography } from 'antd';
import {
  OPERATION_MODULE_LABELS,
  OPERATION_TYPE_COLORS,
  OPERATION_TYPE_LABELS,
} from '../constants';
import type { LogItem } from '../data';

interface DetailDrawerProps {
  visible: boolean;
  logItem: LogItem | null;
  onClose: () => void;
}

const { Text, Paragraph } = Typography;

// 格式化 JSON 数据
const formatJson = (data?: string | Record<string, unknown>) => {
  if (!data) return '-';
  try {
    const parsed = typeof data === 'string' ? JSON.parse(data) : data;
    return JSON.stringify(parsed, null, 2);
  } catch {
    return String(data);
  }
};

const DetailDrawer: React.FC<DetailDrawerProps> = ({
  visible,
  logItem,
  onClose,
}) => {
  const intl = useIntl();

  if (!logItem) return null;

  return (
    <Drawer
      title={intl.formatMessage({
        id: 'logAudit.detail.title',
        defaultMessage: '日志详情',
      })}
      width={800}
      open={visible}
      onClose={onClose}
      destroyOnClose
    >
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 基本信息 */}
        <Card
          title={intl.formatMessage({
            id: 'logAudit.detail.basicInfo',
            defaultMessage: '基本信息',
          })}
          size="small"
        >
          <Descriptions column={2} size="small">
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.createdAt',
                defaultMessage: '操作时间',
              })}
            >
              {logItem.createdAt}
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.operatorName',
                defaultMessage: '操作人',
              })}
            >
              <Text strong>{logItem.operatorName}</Text>
              {logItem.operatorRole && (
                <Tag style={{ marginLeft: 8, fontSize: 12 }}>
                  {logItem.operatorRole}
                </Tag>
              )}
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.operationType',
                defaultMessage: '操作类型',
              })}
            >
              <Tag color={OPERATION_TYPE_COLORS[logItem.operationType]}>
                {OPERATION_TYPE_LABELS[logItem.operationType]}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.operationModule',
                defaultMessage: '操作模块',
              })}
            >
              <Tag>{OPERATION_MODULE_LABELS[logItem.operationModule]}</Tag>
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.status',
                defaultMessage: '操作结果',
              })}
              span={2}
            >
              <Tag color={logItem.status === 'success' ? 'success' : 'error'}>
                {logItem.status === 'success'
                  ? intl.formatMessage({
                      id: 'logAudit.status.success',
                      defaultMessage: '成功',
                    })
                  : intl.formatMessage({
                      id: 'logAudit.status.failure',
                      defaultMessage: '失败',
                    })}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.operationDesc',
                defaultMessage: '操作描述',
              })}
              span={2}
            >
              {logItem.operationDesc}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 请求信息 */}
        <Card
          title={intl.formatMessage({
            id: 'logAudit.detail.requestInfo',
            defaultMessage: '请求信息',
          })}
          size="small"
        >
          <Descriptions column={2} size="small">
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.requestMethod',
                defaultMessage: '请求方法',
              })}
            >
              <Tag color={logItem.requestMethod === 'GET' ? 'blue' : 'green'}>
                {logItem.requestMethod}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.requestUrl',
                defaultMessage: '请求URL',
              })}
            >
              <Text code copyable>
                {logItem.requestUrl}
              </Text>
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.ipAddress',
                defaultMessage: 'IP地址',
              })}
            >
              {logItem.ipAddress}
            </Descriptions.Item>
            <Descriptions.Item
              label={intl.formatMessage({
                id: 'logAudit.detail.executionTime',
                defaultMessage: '执行时长',
              })}
            >
              <Text type={logItem.executionTime > 1000 ? 'warning' : undefined}>
                {logItem.executionTime}ms
              </Text>
            </Descriptions.Item>
          </Descriptions>
          {logItem.userAgent && (
            <Descriptions column={1} size="small" style={{ marginTop: 8 }}>
              <Descriptions.Item
                label={intl.formatMessage({
                  id: 'logAudit.detail.userAgent',
                  defaultMessage: 'User Agent',
                })}
              >
                <Text type="secondary" ellipsis style={{ maxWidth: 600 }}>
                  {logItem.userAgent}
                </Text>
              </Descriptions.Item>
            </Descriptions>
          )}
        </Card>

        {/* 请求参数 */}
        {logItem.requestParams && (
          <Card
            title={intl.formatMessage({
              id: 'logAudit.detail.requestParams',
              defaultMessage: '请求参数',
            })}
            size="small"
          >
            <Paragraph>
              <pre
                style={{
                  background: '#f6ffed',
                  padding: 12,
                  borderRadius: 4,
                  maxHeight: 300,
                  overflow: 'auto',
                  fontSize: 12,
                }}
              >
                <code>{formatJson(logItem.requestParams)}</code>
              </pre>
            </Paragraph>
          </Card>
        )}

        {/* 响应数据 */}
        {logItem.responseData && logItem.status === 'success' && (
          <Card
            title={intl.formatMessage({
              id: 'logAudit.detail.responseData',
              defaultMessage: '响应数据',
            })}
            size="small"
          >
            <Paragraph>
              <pre
                style={{
                  background: '#e6f7ff',
                  padding: 12,
                  borderRadius: 4,
                  maxHeight: 300,
                  overflow: 'auto',
                  fontSize: 12,
                }}
              >
                <code>{formatJson(logItem.responseData)}</code>
              </pre>
            </Paragraph>
          </Card>
        )}

        {/* 错误信息 */}
        {logItem.errorMessage && logItem.status === 'failure' && (
          <Card
            title={intl.formatMessage({
              id: 'logAudit.detail.errorMessage',
              defaultMessage: '错误信息',
            })}
            size="small"
          >
            <Paragraph>
              <pre
                style={{
                  background: '#fff2f0',
                  padding: 12,
                  borderRadius: 4,
                  color: '#cf1322',
                  maxHeight: 300,
                  overflow: 'auto',
                  fontSize: 12,
                }}
              >
                {logItem.errorMessage}
              </pre>
            </Paragraph>
          </Card>
        )}
      </Space>
    </Drawer>
  );
};

export default DetailDrawer;
