import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Spin } from 'antd';
import {
  RobotOutlined,
  SearchOutlined,
  FormOutlined,
  PhoneOutlined,
  AlertOutlined,
  MedicineBoxOutlined,
} from '@ant-design/icons';
import { actionInboxApi, type ActionItem, type WorkbenchStats } from '../../../../api/health/actionInbox';

const RISK_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  high: { label: '高风险', color: '#DC2626', bg: '#FEF2F2' },
  medium: { label: '中风险', color: '#D97706', bg: '#FFFBEB' },
  low: { label: '低风险', color: '#16A34A', bg: '#F0FDF4' },
};

function getRiskFromPriority(priority: string) {
  if (priority === 'urgent') return 'high';
  if (priority === 'high') return 'medium';
  return 'low';
}

export default function AiInsightPanel() {
  const [stats, setStats] = useState<WorkbenchStats | null>(null);
  const [insights, setInsights] = useState<ActionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    Promise.all([
      actionInboxApi.stats(),
      actionInboxApi.list({ status: 'pending', page: 1, page_size: 3 }),
    ])
      .then(([s, res]) => {
        setStats(s);
        setInsights(res.data.filter((i) => i.action_type === 'ai_suggestion' || i.action_type === 'alert'));
      })
      .finally(() => setLoading(false));
  }, []);

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

  return (
    <div>
      {/* AI 洞察卡片 */}
      <div style={{
        background: 'var(--erp-bg-card, white)',
        borderRadius: 12,
        border: '1px solid var(--erp-border, #E2E8F0)',
        overflow: 'hidden',
        marginBottom: 16,
      }}>
        {/* 卡片头 */}
        <div style={{
          padding: '16px 20px',
          borderBottom: '1px solid #F1F5F9',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
        }}>
          <div style={{
            width: 28,
            height: 28,
            borderRadius: 8,
            background: 'linear-gradient(135deg, #7C3AED, #2563EB)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            fontSize: 14,
            fontWeight: 700,
          }}>
            AI
          </div>
          <span style={{ fontSize: 14, fontWeight: 600 }}>智能洞察</span>
          {stats && stats.total_pending > 0 && (
            <span style={{
              marginLeft: 'auto',
              fontSize: 10,
              background: '#F0FDF4',
              color: '#16A34A',
              padding: '2px 8px',
              borderRadius: 4,
            }}>
              {stats.ai_suggestion_pending} 条新建议
            </span>
          )}
        </div>

        {/* 洞察列表 */}
        {insights.length === 0 ? (
          <div style={{ padding: '24px 20px', textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>
            暂无 AI 洞察
          </div>
        ) : (
          insights.map((item, idx) => {
            const risk = getRiskFromPriority(item.priority);
            const riskCfg = RISK_CONFIG[risk];
            return (
              <div key={item.id} style={{
                padding: '14px 20px',
                borderBottom: idx < insights.length - 1 ? '1px solid #F1F5F9' : 'none',
              }}>
                <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>
                  {item.patient_name}
                </div>
                <div style={{ fontSize: 12, color: '#475569', lineHeight: 1.6 }}>
                  {item.summary}
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <span style={{
                    padding: '2px 8px',
                    borderRadius: 4,
                    fontSize: 10,
                    fontWeight: 600,
                    background: riskCfg.bg,
                    color: riskCfg.color,
                  }}>
                    {riskCfg.label}
                  </span>
                  <span style={{
                    padding: '2px 8px',
                    borderRadius: 4,
                    fontSize: 10,
                    fontWeight: 500,
                    background: item.action_type === 'ai_suggestion' ? '#F5F3FF' : '#FEF2F2',
                    color: item.action_type === 'ai_suggestion' ? '#7C3AED' : '#DC2626',
                  }}>
                    {item.action_type === 'ai_suggestion' ? 'AI 分析' : '告警'}
                  </span>
                </div>

                {/* 第一条洞察的快捷操作 */}
                {idx === 0 && (
                  <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                    <button style={{
                      flex: 1, padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
                      background: 'white', textAlign: 'center', cursor: 'pointer',
                      fontFamily: 'inherit', fontSize: 11, color: '#475569',
                    }}>
                      <PhoneOutlined style={{ fontSize: 16, display: 'block', marginBottom: 4 }} />
                      联系患者
                    </button>
                    <button style={{
                      flex: 1, padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
                      background: 'white', textAlign: 'center', cursor: 'pointer',
                      fontFamily: 'inherit', fontSize: 11, color: '#475569',
                    }}>
                      <AlertOutlined style={{ fontSize: 16, display: 'block', marginBottom: 4 }} />
                      安排急诊
                    </button>
                    <button style={{
                      flex: 1, padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
                      background: 'white', textAlign: 'center', cursor: 'pointer',
                      fontFamily: 'inherit', fontSize: 11, color: '#475569',
                    }}>
                      <MedicineBoxOutlined style={{ fontSize: 16, display: 'block', marginBottom: 4 }} />
                      调整用药
                    </button>
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>

      {/* 快捷操作 */}
      <div style={{
        background: 'var(--erp-bg-card, white)',
        borderRadius: 12,
        border: '1px solid var(--erp-border, #E2E8F0)',
        padding: '16px 20px',
      }}>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>快捷操作</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          <button onClick={() => navigate('/health/patients')} style={{
            padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
            background: 'white', textAlign: 'center', cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
            <SearchOutlined style={{ fontSize: 18, display: 'block', marginBottom: 4, color: '#475569' }} />
            <span style={{ fontSize: 11, color: '#475569' }}>查询患者</span>
          </button>
          <button onClick={() => navigate('/health/follow-ups')} style={{
            padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
            background: 'white', textAlign: 'center', cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
            <FormOutlined style={{ fontSize: 18, display: 'block', marginBottom: 4, color: '#475569' }} />
            <span style={{ fontSize: 11, color: '#475569' }}>新建随访</span>
          </button>
          <button onClick={() => navigate('/health/ai-analysis')} style={{
            padding: 8, borderRadius: 10, border: '1px solid #E2E8F0',
            background: 'white', textAlign: 'center', cursor: 'pointer',
            fontFamily: 'inherit',
          }}>
            <RobotOutlined style={{ fontSize: 18, display: 'block', marginBottom: 4, color: '#475569' }} />
            <span style={{ fontSize: 11, color: '#475569' }}>AI 分析</span>
          </button>
        </div>
      </div>
    </div>
  );
}
