import { useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import {
  Table,
  Select,
  Button,
  Input,
  Tag,
  Space,
  Popconfirm,
  DatePicker,
  message,
} from 'antd';
import { CheckOutlined, StopOutlined } from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import {
  alertApi,
  type Alert,
} from '../../api/health/alerts';
import { SEVERITY_COLOR, SEVERITY_LABEL, ALERT_STATUS_COLOR, ALERT_STATUS_LABEL, SEVERITY_OPTIONS, ALERT_STATUS_OPTIONS as STATUS_OPTS } from '../../constants/health';
import { AuthButton } from '../../components/AuthButton';
import { PageContainer } from '../../components/PageContainer';
import { EntityName } from '../../components/EntityName';
import { usePaginatedData } from '../../hooks/usePaginatedData';
import { formatRelative, formatDateTime } from '../../utils/format';

// --- 常量映射 ---

// 状态选项保留给筛选下拉使用（使用常量）


// --- 筛选器结构 ---

interface AlertFilters {
  search: string;
  status: string;
  severity: string;
  dateRange: [string, string] | null;
}

const DEFAULT_FILTERS: AlertFilters = {
  search: '',
  status: '',
  severity: '',
  dateRange: null,
};

// --- 辅助函数 ---

/** 从 detail 中提取规则名称 */
function extractRuleName(
  detail: Record<string, unknown> | undefined,
): string {
  if (!detail) return '-';
  const ruleName = detail.rule_name;
  return typeof ruleName === 'string' && ruleName ? ruleName : '-';
}

export default function AlertList() {
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  // ---- 分页数据 Hook ----
  const {
    data,
    total,
    page,
    loading,
    filters,
    setFilters,
    refresh,
  } = usePaginatedData<Alert, AlertFilters>(
    async (p, pageSize, f) => {
      const result = await alertApi.list({
        page: p,
        page_size: pageSize,
        status: f.status || undefined,
      });
      return result;
    },
    { pageSize: 20, defaultFilters: { ...DEFAULT_FILTERS } },
  );

  // ---- 筛选回调 ----

  const handleFilterChange = useCallback(
    (key: keyof AlertFilters, value: string | [string, string] | null) => {
      setFilters((prev) => ({ ...prev, [key]: value }));
      refresh(1);
    },
    [setFilters, refresh],
  );

  const handleResetFilters = useCallback(() => {
    setFilters({ ...DEFAULT_FILTERS });
    refresh(1);
  }, [setFilters, refresh]);

  // ---- 分页 ----

  const handleTableChange = (pagination: TablePaginationConfig) => {
    refresh(pagination.current ?? 1);
  };

  // ---- 操作 ----

  const handleAcknowledge = async (record: Alert) => {
    setActionLoading(record.id);
    try {
      await alertApi.acknowledge(record.id, record.version);
      message.success('告警已确认');
      refresh();
    } catch {
      message.error('确认告警失败');
    } finally {
      setActionLoading(null);
    }
  };

  const handleDismiss = async (record: Alert) => {
    setActionLoading(record.id);
    try {
      await alertApi.dismiss(record.id, record.version);
      message.success('告警已忽略');
      refresh();
    } catch {
      message.error('忽略告警失败');
    } finally {
      setActionLoading(null);
    }
  };

  // ---- 列定义 ----

  const columns: ColumnsType<Alert> = [
    {
      title: '患者',
      dataIndex: 'patient_id',
      key: 'patient_id',
      width: 140,
      render: (_: unknown, record: Alert) => (
        <Link to={`/health/patients/${record.patient_id}`}>
          <EntityName
            name={record.patient_name}
            id={record.patient_id}
          />
        </Link>
      ),
    },
    {
      title: '规则名称',
      key: 'rule_name',
      width: 160,
      render: (_: unknown, record: Alert) =>
        extractRuleName(record.detail),
    },
    {
      title: '告警标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      width: 100,
      render: (val: string) => (
        <Tag color={SEVERITY_COLOR[val] || 'default'}>
          {SEVERITY_LABEL[val] || val}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (val: string) => (
        <Tag color={ALERT_STATUS_COLOR[val] || 'default'}>
          {ALERT_STATUS_LABEL[val] || val}
        </Tag>
      ),
    },
    {
      title: '触发时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 140,
      render: (val: string) => (
        <span title={formatDateTime(val)} style={{ fontSize: 13 }}>
          {formatRelative(val)}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 160,
      render: (_: unknown, record: Alert) => (
        <AuthButton code="health.alerts.manage">
          <Space size={4}>
            {(record.status === 'pending' || record.status === 'active') && (
              <Popconfirm
                title="确认处理该告警？"
                onConfirm={() => handleAcknowledge(record)}
                okText="确认"
                cancelText="取消"
              >
                <Button
                  type="link"
                  size="small"
                  icon={<CheckOutlined />}
                  loading={actionLoading === record.id}
                >
                  确认
                </Button>
              </Popconfirm>
            )}
            {(record.status === 'pending' ||
              record.status === 'active' ||
              record.status === 'acknowledged') && (
              <Popconfirm
                title="确认忽略该告警？"
                onConfirm={() => handleDismiss(record)}
                okText="确认"
                cancelText="取消"
              >
                <Button
                  type="link"
                  size="small"
                  danger
                  icon={<StopOutlined />}
                  loading={actionLoading === record.id}
                >
                  忽略
                </Button>
              </Popconfirm>
            )}
          </Space>
        </AuthButton>
      ),
    },
  ];

  return (
    <PageContainer
      title="告警列表"
      subtitle="查看和管理患者健康告警"
      filters={
        <>
          <Input
            placeholder="搜索告警..."
            value={filters.search}
            onChange={(e) => handleFilterChange('search', e.target.value)}
            allowClear
            style={{ width: 200 }}
          />
          <Select
            allowClear
            placeholder="状态筛选"
            style={{ width: 140 }}
            options={STATUS_OPTS}
            value={filters.status || undefined}
            onChange={(v) => handleFilterChange('status', v ?? '')}
          />
          <Select
            allowClear
            placeholder="严重程度"
            style={{ width: 120 }}
            options={SEVERITY_OPTIONS}
            value={filters.severity || undefined}
            onChange={(v) => handleFilterChange('severity', v ?? '')}
          />
          <DatePicker.RangePicker
            placeholder={['开始日期', '结束日期']}
            onChange={(dates) => {
              if (dates && dates[0] && dates[1]) {
                handleFilterChange('dateRange', [
                  dates[0].format('YYYY-MM-DD'),
                  dates[1].format('YYYY-MM-DD'),
                ]);
              } else {
                handleFilterChange('dateRange', null);
              }
            }}
          />
        </>
      }
      onResetFilters={handleResetFilters}
      loading={loading}
    >
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        onChange={handleTableChange}
        pagination={{
          current: page,
          pageSize: 20,
          total,
          showSizeChanger: true,
          showTotal: (t) => `共 ${t} 条`,
        }}
        scroll={{ x: 970 }}
      />
    </PageContainer>
  );
}
