import { useEffect, useState, useCallback } from 'react';
import { Empty, Spin } from 'antd';
import { actionInboxApi, type ActionItem, type ActionType } from '../../../../api/health/actionInbox';

const TYPE_CONFIG: Record<ActionType, { label: string; color: string; bg: string }> = {
  ai_suggestion: { label: 'AI 建议', color: '#7C3AED', bg: '#F5F3FF' },
  alert: { label: '危急告警', color: '#DC2626', bg: '#FEF2F2' },
  followup: { label: '随访', color: '#0284C7', bg: '#F0F9FF' },
  data_anomaly: { label: '数据异常', color: '#D97706', bg: '#FFFBEB' },
};

const PRIORITY_DOT: Record<string, string> = {
  urgent: '#DC2626',
  high: '#D97706',
  medium: '#2563EB',
  low: '#94A3B8',
};

const FILTER_OPTIONS: { key: ActionType | 'all'; label: string }[] = [
  { key: 'all', label: '全部' },
  { key: 'ai_suggestion', label: 'AI 建议' },
  { key: 'alert', label: '告警' },
  { key: 'followup', label: '随访' },
  { key: 'data_anomaly', label: '数据异常' },
];

const ACTION_LABEL: Record<ActionType, string> = {
  ai_suggestion: '审批建议',
  alert: '立即处理',
  followup: '开始随访',
  data_anomaly: '查看详情',
};

function formatTime(dateStr: string): string {
  const d = new Date(dateStr);
  const now = new Date();
  const diffMs = now.getTime() - d.getTime();
  const diffDays = Math.floor(diffMs / 86400000);
  if (diffDays > 0) return `${diffDays}天前`;
  const hours = d.getHours().toString().padStart(2, '0');
  const mins = d.getMinutes().toString().padStart(2, '0');
  return `${hours}:${mins}`;
}

interface TodoListProps {
  onItemClick?: (item: ActionItem) => void;
}

export default function TodoList({ onItemClick }: TodoListProps) {
  const [items, setItems] = useState<ActionItem[]>([]);
  const [filtered, setFiltered] = useState<ActionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [activeFilter, setActiveFilter] = useState<ActionType | 'all'>('all');

  const fetchItems = useCallback(async (p: number) => {
    setLoading(true);
    try {
      const res = await actionInboxApi.list({
        status: 'pending',
        page: p,
        page_size: 10,
      });
      setItems(res.data);
      setTotal(res.total);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchItems(page);
  }, [page, fetchItems]);

  useEffect(() => {
    if (activeFilter === 'all') {
      setFiltered(items);
    } else {
      setFiltered(items.filter((i) => i.action_type === activeFilter));
    }
  }, [items, activeFilter]);

  if (loading) {
    return <div style={{ textAlign: 'center', padding: 40 }}><Spin /></div>;
  }

  if (items.length === 0) {
    return <Empty description="暂无待处理事项" />;
  }

  return (
    <div>
      {/* 筛选条 */}
      <div style={{ display: 'flex', gap: 4, padding: '12px 16px', borderBottom: '1px solid #F1F5F9' }}>
        {FILTER_OPTIONS.map((opt) => (
          <button
            key={opt.key}
            onClick={() => setActiveFilter(opt.key)}
            style={{
              padding: '4px 12px',
              border: `1px solid ${activeFilter === opt.key ? '#2563EB' : '#E2E8F0'}`,
              borderRadius: 6,
              background: activeFilter === opt.key ? '#2563EB' : 'white',
              color: activeFilter === opt.key ? 'white' : '#475569',
              fontSize: 12,
              cursor: 'pointer',
              fontFamily: 'inherit',
              transition: 'all 0.15s',
            }}
          >
            {opt.label}
          </button>
        ))}
      </div>

      {/* 待办列表 */}
      <div style={{ padding: 8 }}>
        {filtered.length === 0 ? (
          <Empty description="无匹配项" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          filtered.map((item) => {
            const cfg = TYPE_CONFIG[item.action_type];
            const dotColor = PRIORITY_DOT[item.priority] || PRIORITY_DOT.low;
            return (
              <div
                key={item.id}
                onClick={() => onItemClick?.(item)}
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  gap: 12,
                  padding: '14px 12px',
                  borderRadius: 10,
                  cursor: 'pointer',
                  transition: 'all 0.15s',
                  borderBottom: '1px solid #F1F5F9',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.background = '#EFF6FF'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
              >
                {/* 紧急度圆点 */}
                <div style={{
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  background: dotColor,
                  marginTop: 6,
                  flexShrink: 0,
                }} />

                {/* 内容 */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 2 }}>{item.title}</div>
                  <div style={{ fontSize: 12, color: '#94A3B8' }}>{item.summary}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                    <span style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 4,
                      padding: '2px 8px',
                      borderRadius: 4,
                      fontSize: 11,
                      fontWeight: 500,
                      background: cfg.bg,
                      color: cfg.color,
                    }}>
                      {cfg.label}
                    </span>
                    <span style={{ fontSize: 11, color: '#94A3B8' }}>
                      {item.patient_name}
                    </span>
                  </div>
                </div>

                {/* 时间 */}
                <span style={{ fontSize: 11, color: '#94A3B8', whiteSpace: 'nowrap', marginTop: 2 }}>
                  {formatTime(item.created_at)}
                </span>

                {/* 操作按钮 */}
                <button
                  style={{
                    padding: '4px 12px',
                    borderRadius: 6,
                    border: '1px solid #2563EB',
                    background: 'white',
                    color: '#2563EB',
                    fontSize: 12,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    transition: 'all 0.15s',
                    whiteSpace: 'nowrap',
                    marginTop: 2,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = '#2563EB'; e.currentTarget.style.color = 'white'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = '#2563EB'; }}
                >
                  {ACTION_LABEL[item.action_type]}
                </button>
              </div>
            );
          })
        )}
      </div>

      {/* 分页 */}
      {total > 10 && (
        <div style={{
          padding: '8px 16px',
          borderTop: '1px solid #F1F5F9',
          textAlign: 'center',
          fontSize: 12,
          color: '#94A3B8',
        }}>
          <button
            disabled={page <= 1}
            onClick={() => setPage(page - 1)}
            style={{ border: 'none', background: 'none', cursor: page <= 1 ? 'default' : 'pointer', color: page <= 1 ? '#CBD5E1' : '#2563EB', padding: '4px 8px', fontFamily: 'inherit' }}
          >
            上一页
          </button>
          <span style={{ margin: '0 8px' }}>{page} / {Math.ceil(total / 10)}</span>
          <button
            disabled={page >= Math.ceil(total / 10)}
            onClick={() => setPage(page + 1)}
            style={{ border: 'none', background: 'none', cursor: page >= Math.ceil(total / 10) ? 'default' : 'pointer', color: page >= Math.ceil(total / 10) ? '#CBD5E1' : '#2563EB', padding: '4px 8px', fontFamily: 'inherit' }}
          >
            下一页
          </button>
        </div>
      )}
    </div>
  );
}
