import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../../../stores/auth';
import { actionInboxApi, type WorkbenchStats, type ActionItem } from '../../../../api/health/actionInbox';
import { useStatsData } from '../../StatisticsDashboard/useStatsData';
import {
  dashboardApi,
  type PointsActivityItem,
  type ArticleStatsResp,
} from '../../../../api/health/dashboard';

const TYPE_ICON: Record<string, { icon: string; bg: string; color: string }> = {
  ai_suggestion: { icon: '🤖', bg: '#F0F9FF', color: '#0284C7' },
  alert: { icon: '⚠️', bg: '#FFF1F2', color: '#E11D48' },
  followup: { icon: '📋', bg: '#F0FDF4', color: '#16A34A' },
  data_anomaly: { icon: '📊', bg: '#F5F3FF', color: '#7C3AED' },
};

const PRIORITY_LABEL: Record<string, string> = {
  urgent: '紧急', high: '高', medium: '中', low: '低',
};

export default function OperatorWorkbench() {
  const navigate = useNavigate();
  const user = useAuthStore((s) => s.user);
  const [stats, setStats] = useState<WorkbenchStats | null>(null);
  const [actionItems, setActionItems] = useState<ActionItem[]>([]);
  const [pointsActivity, setPointsActivity] = useState<PointsActivityItem[]>([]);
  const [articleStats, setArticleStats] = useState<ArticleStatsResp | null>(null);
  const statsData = useStatsData();

  useEffect(() => {
    actionInboxApi.stats()
      .then((s) => setStats(s ?? null))
      .catch((err) => console.warn('[OperatorWorkbench] 获取行动收件箱统计失败:', err));

    actionInboxApi.list({ status: 'pending', page: 1, page_size: 5 })
      .then((r) => setActionItems(r.data))
      .catch((err) => console.warn('[OperatorWorkbench] 获取行动列表失败:', err));

    dashboardApi.getPointsRecentActivity()
      .then((d) => setPointsActivity(d ?? []))
      .catch((err) => console.warn('[OperatorWorkbench] 获取积分活动失败:', err));

    dashboardApi.getArticleStats()
      .then((d) => setArticleStats(d ?? null))
      .catch((err) => console.warn('[OperatorWorkbench] 获取文章统计失败:', err));
  }, []);

  const firstName = user?.display_name ?? user?.username ?? '运营';
  const now = new Date();
  const greeting = now.getHours() < 12 ? '早上好' : now.getHours() < 18 ? '下午好' : '晚上好';

  const vitalRate = statsData.healthDataStats?.vital_signs_report_rate?.report_rate;
  const formattedVitalRate = vitalRate != null ? Math.round(vitalRate * 100) / 100 : 0;

  const statCards = [
    { label: '今日活跃用户', value: statsData.pointsStats?.active_accounts ?? 0, color: '#2563EB', trend: '', trendDir: '' },
    { label: '科普阅读量', value: articleStats?.total_views ?? 0, color: '#16A34A', trend: '', trendDir: 'up' },
    { label: '积分发放', value: statsData.pointsStats?.total_issued ?? 0, color: '#EA580C', trend: '', trendDir: 'down' },
    { label: '待审核订单', value: stats?.total_pending ?? 0, color: '#E11D48', trend: '', trendDir: 'down' },
  ];

  return (
    <div>
      {/* AI Hero Card */}
      <div style={{
        background: 'linear-gradient(135deg, #EA580C 0%, #C2410C 50%, #9A3412 100%)',
        borderRadius: 16,
        padding: '24px 28px',
        marginBottom: 24,
        color: 'white',
        position: 'relative',
        overflow: 'hidden',
      } as React.CSSProperties}
      className="erp-fade-in">
        <div style={{ position: 'absolute', top: -30, right: -30, width: 150, height: 150, background: 'rgba(255,255,255,0.06)', borderRadius: '50%' }} />
        <div style={{ position: 'absolute', bottom: -50, left: '25%', width: 200, height: 200, background: 'rgba(255,255,255,0.04)', borderRadius: '50%' }} />
        <div style={{ fontSize: 14, opacity: 0.85, marginBottom: 4, position: 'relative', zIndex: 1 }}>{greeting}，{firstName}。AI 帮你梳理了今天的运营重点：</div>
        <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 14, position: 'relative', zIndex: 1 }}>{stats?.total_pending ?? 0} 个运营洞察需要关注</div>
        <div style={{ fontSize: 13, lineHeight: 2, opacity: 0.92, position: 'relative', zIndex: 1 }}>
          <b style={{ color: '#FED7AA', fontWeight: 600 }}>1. 积分兑换活动数据</b> — 今日发放 {statsData.pointsStats?.total_issued ?? 0} 积分，消费 {statsData.pointsStats?.total_spent ?? 0}。<br />
          <b style={{ color: '#FED7AA', fontWeight: 600 }}>2. 患者活跃度</b> — 体征上报率 {formattedVitalRate}%，持续关注沉默用户。<br />
          <b style={{ color: '#FED7AA', fontWeight: 600 }}>3. 待处理任务</b> — {stats?.total_pending ?? 0} 项任务待处理，其中 {stats?.urgent_alerts ?? 0} 项需优先关注。
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 16, position: 'relative', zIndex: 1, flexWrap: 'wrap' as const }}>
          <button onClick={() => navigate('/health/points-orders')} style={{ padding: '7px 16px', borderRadius: 6, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: 'none', fontFamily: 'inherit', background: 'white', color: '#EA580C' }}>审核积分订单</button>
          <button onClick={() => navigate('/health/articles/new')} style={{ padding: '7px 16px', borderRadius: 6, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: '1px solid rgba(255,255,255,0.25)', fontFamily: 'inherit', background: 'rgba(255,255,255,0.15)', color: 'white' }}>发布新文章</button>
          <button onClick={() => navigate('/health/offline-events')} style={{ padding: '7px 16px', borderRadius: 6, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: '1px solid rgba(255,255,255,0.25)', fontFamily: 'inherit', background: 'rgba(255,255,255,0.15)', color: 'white' }}>推送活动提醒</button>
        </div>
      </div>

      {/* Stat Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
        {statCards.map((card) => (
          <div key={card.label} style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', padding: '14px 18px' }}>
            <div style={{ fontSize: 11, color: '#94A3B8', marginBottom: 2 }}>{card.label}</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: card.color }}>{card.value.toLocaleString()}</div>
          </div>
        ))}
      </div>

      {/* Two-column: Todos + Points/Content */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
        {/* Today's Todos */}
        <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>今日待办</h3>
            <span style={{ fontSize: 11, color: '#2563EB', cursor: 'pointer' }} onClick={() => navigate('/health/action-inbox')}>全部 →</span>
          </div>
          <div>
            {actionItems.length === 0 ? (
              <div style={{ padding: 20, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>暂无待办事项</div>
            ) : (
              actionItems.map((item) => {
                const cfg = TYPE_ICON[item.action_type] ?? TYPE_ICON.alert;
                return (
                  <div
                    key={item.id}
                    style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 18px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer', transition: 'all 0.15s' }}
                    onClick={() => navigate('/health/action-inbox')}
                    onMouseEnter={(e) => { e.currentTarget.style.background = '#EFF6FF'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                  >
                    <div style={{ width: 28, height: 28, borderRadius: 6, background: cfg.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0 }}>{cfg.icon}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{item.title}</div>
                      <div style={{ fontSize: 11, color: '#94A3B8' }}>{item.patient_name} · {item.summary}</div>
                    </div>
                    <div style={{ fontSize: 11, padding: '3px 10px', borderRadius: 4, border: '1px solid #E2E8F0', color: '#475569', cursor: 'pointer', flexShrink: 0 }}>{PRIORITY_LABEL[item.priority] ?? '处理'}</div>
                  </div>
                );
              })
            )}
          </div>
        </div>

        {/* Points Activity + Content Matrix */}
        <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>积分动态</h3>
            <span style={{ fontSize: 11, color: '#2563EB', cursor: 'pointer' }} onClick={() => navigate('/health/points-orders')}>积分管理 →</span>
          </div>
          <div>
            {pointsActivity.length === 0 ? (
              <div style={{ padding: 20, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>暂无积分动态</div>
            ) : (
              pointsActivity.slice(0, 5).map((item, i) => {
                const avatarColors = ['#FEF2F2', '#F0F9FF', '#F0FDF4', '#F5F3FF', '#F0FDFA'];
                const avatarTextColors = ['#DC2626', '#0284C7', '#16A34A', '#7C3AED', '#0D9488'];
                return (
                  <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 18px', borderBottom: i < Math.min(pointsActivity.length, 5) - 1 ? '1px solid #F1F5F9' : undefined }}>
                    <div style={{ width: 28, height: 28, borderRadius: '50%', background: avatarColors[i % 5], display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600, color: avatarTextColors[i % 5], flexShrink: 0 }}>{item.user_name.charAt(0)}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12, fontWeight: 500 }}>{item.user_name}</div>
                      <div style={{ fontSize: 11, color: '#94A3B8' }}>{item.detail}</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: item.type === 'earn' ? '#16A34A' : '#EA580C' }}>{item.amount}</div>
                  </div>
                );
              })
            )}
          </div>

          {/* Content Matrix */}
          <div style={{ padding: '16px 18px', borderTop: '1px solid #F1F5F9' }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>内容矩阵</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
              <div style={{ padding: '10px 14px', background: '#EFF6FF', borderRadius: 10 }}>
                <div style={{ fontSize: 11, color: '#94A3B8' }}>已发布</div>
                <div style={{ fontSize: 18, fontWeight: 700, color: '#2563EB' }}>{articleStats?.published ?? 0}</div>
              </div>
              <div style={{ padding: '10px 14px', background: '#F0FDF4', borderRadius: 10 }}>
                <div style={{ fontSize: 11, color: '#94A3B8' }}>草稿箱</div>
                <div style={{ fontSize: 18, fontWeight: 700, color: '#16A34A' }}>{articleStats?.draft ?? 0}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
