import {
  Descriptions,
  Tag,
  Typography,
  Space,
  Button,
  Popconfirm,
  Tooltip,
} from "antd";
import {
  CheckOutlined,
  StopOutlined,
  SafetyCertificateOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Alert } from "../../../api/health/alerts";
import { translateAlertTitle } from "../../../constants/health";

const SEVERITY_CONFIG: Record<
  string,
  { color: string; label: string; icon: React.ReactNode }
> = {
  info: {
    color: "default",
    label: "提示",
    icon: <ExclamationCircleOutlined />,
  },
  warning: {
    color: "orange",
    label: "警告",
    icon: <ExclamationCircleOutlined />,
  },
  critical: {
    color: "red",
    label: "严重",
    icon: <ExclamationCircleOutlined />,
  },
  urgent: {
    color: "magenta",
    label: "紧急",
    icon: <ExclamationCircleOutlined />,
  },
};

const STATUS_CONFIG: Record<string, { color: string; label: string }> = {
  pending: { color: "orange", label: "待处理" },
  active: { color: "orange", label: "待处理" },
  acknowledged: { color: "blue", label: "已确认" },
  resolved: { color: "green", label: "已恢复" },
  dismissed: { color: "default", label: "已忽略" },
};

const DETAIL_LABEL_MAP: Record<string, string> = {
  message: "告警描述",
  value: "监测值",
  threshold: "阈值",
  unit: "单位",
  metric: "指标",
  metric_name: "指标名称",
  indicator_type: "体征类型",
  recorded_at: "记录时间",
  blood_pressure_systolic: "收缩压",
  blood_pressure_diastolic: "舒张压",
  heart_rate: "心率",
  blood_glucose: "血糖",
  temperature: "体温",
  spo2: "血氧饱和度",
};

function formatDetailValue(key: string, value: unknown): string {
  if (value === null || value === undefined) return "-";
  if (typeof value === "string") {
    if (key.endsWith("_at") || key === "recorded_at") {
      try {
        return new Date(value).toLocaleString("zh-CN");
      } catch {
        return value;
      }
    }
    return value;
  }
  if (typeof value === "number") return String(value);
  if (typeof value === "boolean") return value ? "是" : "否";
  return JSON.stringify(value);
}

interface AlertDetailPanelProps {
  alert: Alert;
  onAcknowledge?: (id: string, version: number) => Promise<void>;
  onDismiss?: (id: string, version: number) => Promise<void>;
  onResolve?: (id: string, version: number) => Promise<void>;
  loading?: boolean;
}

/**
 * 告警详情面板 — 展示告警完整信息及操作按钮。
 */
export function AlertDetailPanel({
  alert,
  onAcknowledge,
  onDismiss,
  onResolve,
  loading = false,
}: AlertDetailPanelProps) {
  const severity = SEVERITY_CONFIG[alert.severity] ?? SEVERITY_CONFIG.info;
  const status = STATUS_CONFIG[alert.status] ?? STATUS_CONFIG.pending;
  const isPending = alert.status === "pending" || alert.status === "active";
  const isAcknowledged = alert.status === "acknowledged";

  const detailEntries = alert.detail
    ? Object.entries(alert.detail).filter(
        ([, v]) => v !== null && v !== undefined,
      )
    : [];

  return (
    <div style={{ padding: 16 }}>
      {/* 顶部摘要 */}
      <div style={{ marginBottom: 16 }}>
        <Space align="center" size="middle">
          <Tag
            color={severity.color}
            icon={severity.icon}
            style={{ fontSize: 14, padding: "4px 12px" }}
          >
            {severity.label}
          </Tag>
          <Tag color={status.color}>{status.label}</Tag>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            <ClockCircleOutlined style={{ marginRight: 4 }} />
            {new Date(alert.created_at).toLocaleString("zh-CN")}
          </Typography.Text>
        </Space>
      </div>

      {/* 详情 */}
      <Descriptions column={2} size="small" bordered>
        <Descriptions.Item label="患者">
          <Typography.Text strong>
            {alert.patient_name || "未知患者"}
          </Typography.Text>
          <Tooltip title={alert.patient_id}>
            <Typography.Text
              type="secondary"
              copyable
              style={{ fontSize: 12, marginLeft: 8, cursor: "help" }}
            >
              {alert.patient_id.slice(0, 8)}...
            </Typography.Text>
          </Tooltip>
        </Descriptions.Item>
        <Descriptions.Item label="规则">
          <Typography.Text>
            {translateAlertTitle(alert.title) || "未知规则"}
          </Typography.Text>
          <Tooltip title={alert.rule_id}>
            <Typography.Text
              type="secondary"
              copyable
              style={{ fontSize: 12, marginLeft: 8, cursor: "help" }}
            >
              {alert.rule_id.slice(0, 8)}...
            </Typography.Text>
          </Tooltip>
        </Descriptions.Item>
        <Descriptions.Item label="严重程度">
          <Tag color={severity.color}>{severity.label}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag color={status.color}>{status.label}</Tag>
        </Descriptions.Item>
        {alert.acknowledged_by && (
          <Descriptions.Item label="处理人" span={2}>
            <Typography.Text style={{ fontSize: 12 }}>
              {alert.acknowledged_by_name || `${alert.acknowledged_by.slice(0, 8)}...`}
            </Typography.Text>
          </Descriptions.Item>
        )}
        {alert.acknowledged_at && (
          <Descriptions.Item label="确认时间">
            {new Date(alert.acknowledged_at).toLocaleString("zh-CN")}
          </Descriptions.Item>
        )}
        {alert.resolved_at && (
          <Descriptions.Item label="恢复时间">
            {new Date(alert.resolved_at).toLocaleString("zh-CN")}
          </Descriptions.Item>
        )}
      </Descriptions>

      {/* 告警详情 */}
      {detailEntries.length > 0 && (
        <Descriptions
          column={2}
          size="small"
          bordered
          style={{ marginTop: 12 }}
          title="告警详情"
        >
          {detailEntries.map(([key, value]) => (
            <Descriptions.Item key={key} label={DETAIL_LABEL_MAP[key] ?? key}>
              <Typography.Text style={{ fontSize: 13 }}>
                {formatDetailValue(key, value)}
              </Typography.Text>
            </Descriptions.Item>
          ))}
        </Descriptions>
      )}

      {/* 操作按钮 */}
      <div
        style={{
          marginTop: 16,
          borderTop: "1px solid var(--ant-color-border)",
          paddingTop: 12,
        }}
      >
        <Space>
          {isPending && onAcknowledge && (
            <Tooltip title="确认已知晓此告警">
              <Popconfirm
                title="确认此告警？"
                description="确认后将标记为已确认状态"
                onConfirm={() => onAcknowledge(alert.id, alert.version)}
              >
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  loading={loading}
                >
                  确认
                </Button>
              </Popconfirm>
            </Tooltip>
          )}
          {isPending && onDismiss && (
            <Tooltip title="忽略此告警">
              <Popconfirm
                title="忽略此告警？"
                description="告警将被标记为已忽略"
                onConfirm={() => onDismiss(alert.id, alert.version)}
              >
                <Button icon={<StopOutlined />} loading={loading}>
                  忽略
                </Button>
              </Popconfirm>
            </Tooltip>
          )}
          {(isPending || isAcknowledged) && onResolve && (
            <Tooltip title="标记告警已恢复">
              <Popconfirm
                title="标记为已恢复？"
                description="告警将标记为已恢复状态"
                onConfirm={() => onResolve(alert.id, alert.version)}
              >
                <Button
                  type="primary"
                  ghost
                  icon={<SafetyCertificateOutlined />}
                  loading={loading}
                >
                  恢复
                </Button>
              </Popconfirm>
            </Tooltip>
          )}
        </Space>
      </div>
    </div>
  );
}
