import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../../../stores/auth';
import { actionInboxApi, type ActionItem, type WorkbenchStats } from '../../../../api/health/actionInbox';
import { pointsApi, type PersonalStats } from '../../../../api/health/points';

const RISK_BADGE: Record<string, { label: string; bg: string; color: string }> = {
  high: { label: '高', bg: '#FEF2F2', color: '#DC2626' },
  medium: { label: '中', bg: '#FFFBEB', color: '#D97706' },
  low: { label: '低', bg: '#F0F9FF', color: '#0284C7' },
};

const TYPE_TAG: Record<string, { label: string; bg: string; color: string }> = {
  alert: { label: '体征异常', bg: '#FEF2F2', color: '#DC2626' },
  ai_suggestion: { label: 'AI 建议', bg: '#F5F3FF', color: '#7C3AED' },
  followup: { label: '随访到期', bg: '#F0F9FF', color: '#0284C7' },
  data_anomaly: { label: '数据异常', bg: '#FFF7ED', color: '#EA580C' },
  consult: { label: '患者咨询', bg: '#F0F9FF', color: '#0284C7' },
};

function formatTime(dateStr: string): string {
  return new Date(dateStr).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}

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

export default function DoctorWorkbench() {
  const navigate = useNavigate();
  const user = useAuthStore((s) => s.user);
  const [suggestions, setSuggestions] = useState<ActionItem[]>([]);
  const [alerts, setAlerts] = useState<ActionItem[]>([]);
  const [stats, setStats] = useState<WorkbenchStats | null>(null);
  const [personalStats, setPersonalStats] = useState<PersonalStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      actionInboxApi.list({ status: 'pending', page: 1, page_size: 10 }),
      actionInboxApi.stats(),
      pointsApi.getPersonalStats().catch(() => null),
    ])
      .then(([res, s, ps]) => {
        const items = Array.isArray(res?.data) ? res.data : [];
        setSuggestions(items.filter((i) => i.action_type === 'ai_suggestion'));
        setAlerts(items.filter((i) => i.action_type === 'alert'));
        setStats(s ?? null);
        setPersonalStats(ps ?? null);
      })
      .finally(() => setLoading(false));
  }, []);

  const firstName = user?.display_name ?? user?.username ?? '医生';
  const now = new Date();
  const greeting = now.getHours() < 12 ? '上午好' : now.getHours() < 18 ? '下午好' : '晚上好';
  const dateStr = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`;

  const statCards = [
    { label: '危急值告警', value: stats?.urgent_alerts ?? alerts.length, color: '#DC2626', gradient: 'linear-gradient(90deg,#DC2626,#F87171)', sub: alerts.length > 0 ? `${alerts[0]?.patient_name ?? ''} · 血压异常` : '暂无', path: '/health/alert-dashboard' },
    { label: 'AI 建议待审', value: stats?.ai_suggestion_pending ?? suggestions.length, color: '#7C3AED', gradient: 'linear-gradient(90deg,#7C3AED,#A78BFA)', sub: `${suggestions.filter((s) => s.priority === 'urgent').length} 高风险`, path: '/health/ai-analysis' },
    { label: '本月咨询', value: personalStats?.consultations_this_month ?? 0, color: '#0284C7', gradient: 'linear-gradient(90deg,#0284C7,#38BDF8)', sub: `未回复 ${stats?.total_pending ?? 0}`, path: '/health/consultations' },
    { label: '今日预约', value: personalStats?.today_appointments ?? 0, color: '#16A34A', gradient: 'linear-gradient(90deg,#16A34A,#4ADE80)', sub: '查看详情', path: '/health/appointments' },
  ];

  // Focused patients from alerts + AI suggestions
  const focusedPatients = Array.from(
    new Map([...alerts, ...suggestions].map((i) => [i.patient_id, i])).values(),
  ).slice(0, 5);

  return (
    <div>
      {/* Greeting */}
      <div className="erp-fade-in" style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, margin: '0 0 4px' }}>
          {greeting}，{firstName.charAt(0)}医生
        </h1>
        <p style={{ color: '#94A3B8', fontSize: 13, margin: 0 }}>
          今天有 {stats?.ai_suggestion_pending ?? 0} 项 AI 建议待审、{stats?.urgent_alerts ?? 0} 条告警需处理 · {dateStr}
        </p>
      </div>

      {/* Stat Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        {statCards.map((card, i) => (
          <div
            key={card.label}
            className={`erp-fade-in erp-fade-in-delay-${i + 1}`}
            style={{
              background: 'var(--erp-bg-card, white)',
              borderRadius: 12,
              border: '1px solid var(--erp-border, #E2E8F0)',
              overflow: 'hidden',
              cursor: 'pointer',
              transition: 'all 0.2s',
            }}
            onClick={() => navigate(card.path)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === 'Enter') navigate(card.path); }}
            onMouseEnter={(e) => { e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}
          >
            <div style={{ height: 3, background: card.gradient }} />
            <div style={{ padding: '14px 18px' }}>
              <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 4 }}>{card.label}</div>
              <div style={{ fontSize: 26, fontWeight: 700, lineHeight: 1.2, color: card.color }}>{loading ? '—' : card.value}</div>
              <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 3 }}>{card.sub}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Two-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 20 }}>
        {/* Left: AI suggestions + Focused patients */}
        <div>
          {/* AI Suggestions */}
          <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ padding: '14px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>
                AI 建议待审 <span style={{ fontSize: 12, color: '#94A3B8', fontWeight: 400 }}>按风险排序</span>
              </h3>
            </div>
            <div>
              {loading ? (
                <div style={{ padding: 24, textAlign: 'center', color: '#94A3B8' }}>加载中...</div>
              ) : suggestions.length === 0 ? (
                <div style={{ padding: 24, textAlign: 'center', color: '#94A3B8' }}>暂无待审 AI 建议</div>
              ) : (
                suggestions.slice(0, 5).map((item) => {
                  const risk = getRisk(item.priority);
                  const badge = RISK_BADGE[risk] ?? RISK_BADGE.low;
                  const tag = TYPE_TAG[item.action_type];
                  return (
                    <div
                      key={item.id}
                      style={{ display: 'flex', gap: 12, padding: '12px 20px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer', transition: 'all 0.15s' }}
                      onClick={() => navigate('/health/ai-analysis')}
                      onMouseEnter={(e) => { e.currentTarget.style.background = '#EFF6FF'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                    >
                      <div style={{ width: 36, height: 36, borderRadius: 8, background: badge.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: badge.color, flexShrink: 0 }}>
                        {badge.label}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{item.title}</div>
                        <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2 }}>{item.summary ?? item.patient_name}</div>
                        <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
                          {tag && <span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 500, background: tag.bg, color: tag.color }}>{tag.label}</span>}
                        </div>
                      </div>
                      <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexShrink: 0 }}>
                        <button style={{ padding: '4px 10px', borderRadius: 4, fontSize: 11, border: '1px solid #2563EB', background: '#2563EB', color: 'white', cursor: 'pointer', fontFamily: 'inherit' }}>采纳</button>
                        <button style={{ padding: '4px 10px', borderRadius: 4, fontSize: 11, border: '1px solid #E2E8F0', background: 'white', cursor: 'pointer', fontFamily: 'inherit' }}>拒绝</button>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>

          {/* Focused Patients */}
          <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden' }}>
            <div style={{ padding: '14px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>重点关注患者</h3>
              <span style={{ fontSize: 11, color: '#2563EB', cursor: 'pointer' }} onClick={() => navigate('/health/patients')}>患者列表 →</span>
            </div>
            <div>
              {focusedPatients.length === 0 ? (
                <div style={{ padding: 24, textAlign: 'center', color: '#94A3B8' }}>暂无重点关注患者</div>
              ) : (
                focusedPatients.map((item) => {
                  const dotColor = item.priority === 'urgent' ? '#DC2626' : item.priority === 'high' ? '#D97706' : '#0284C7';
                  const tagBorder = item.priority === 'urgent' ? '#DC2626' : item.priority === 'high' ? '#D97706' : '#E2E8F0';
                  const tagColor = item.priority === 'urgent' ? '#DC2626' : item.priority === 'high' ? '#D97706' : '#475569';
                  const tagLabel = item.priority === 'urgent' ? '危急' : item.priority === 'high' ? '高关注' : '观察';
                  return (
                    <div
                      key={item.id}
                      style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer', transition: 'all 0.15s' }}
                      onClick={() => navigate(`/health/patients/${item.patient_id}`)}
                      onMouseEnter={(e) => { e.currentTarget.style.background = '#EFF6FF'; }}
                      onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                    >
                      <div style={{ width: 8, height: 8, borderRadius: '50%', background: dotColor, flexShrink: 0 }} />
                      <div style={{ fontSize: 13, fontWeight: 500, flexShrink: 0 }}>{item.patient_name}</div>
                      <div style={{ fontSize: 11, color: '#94A3B8', flex: 1, whiteSpace: 'nowrap' as const, overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.summary ?? item.title}</div>
                      <div style={{ fontSize: 10, padding: '2px 8px', borderRadius: 4, border: `1px solid ${tagBorder}`, color: tagColor, flexShrink: 0 }}>{tagLabel}</div>
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </div>

        {/* Right sidebar */}
        <div>
          {/* Today's Schedule */}
          <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ padding: '14px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>今日日程</h3>
              <span style={{ fontSize: 11, color: '#2563EB', cursor: 'pointer' }} onClick={() => navigate('/health/schedules')}>排班管理 →</span>
            </div>
            <div>
              {/* Use appointments data or static schedule */}
              <div style={{ padding: '10px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', gap: 12 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: '#2563EB', flexShrink: 0, width: 44 }}>门诊</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>今日预约 {personalStats?.today_appointments ?? 0} 位</div>
                  <div style={{ fontSize: 11, color: '#94A3B8' }}>点击查看详情</div>
                </div>
              </div>
              <div style={{ padding: '10px 16px', display: 'flex', gap: 12 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: '#2563EB', flexShrink: 0, width: 44 }}>待审</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>AI 建议 {stats?.ai_suggestion_pending ?? 0} 条</div>
                  <div style={{ fontSize: 11, color: '#94A3B8' }}>按风险排序</div>
                </div>
              </div>
            </div>
          </div>

          {/* Unreplied Consultations */}
          <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ padding: '14px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ color: '#0284C7' }}>●</span> 未回复咨询
              </h3>
              <span style={{ fontSize: 11, color: '#2563EB', cursor: 'pointer' }} onClick={() => navigate('/health/consultations')}>查看全部 →</span>
            </div>
            <div>
              {alerts.slice(0, 3).map((item) => (
                <div
                  key={item.id}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 16px', borderBottom: '1px solid #F1F5F9', cursor: 'pointer', transition: 'all 0.15s' }}
                  onClick={() => navigate('/health/consultations')}
                  onMouseEnter={(e) => { e.currentTarget.style.background = '#EFF6FF'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                >
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#2563EB', flexShrink: 0 }} />
                  <div style={{ fontSize: 12, fontWeight: 500, flexShrink: 0 }}>{item.patient_name}</div>
                  <div style={{ fontSize: 11, color: '#94A3B8', flex: 1, whiteSpace: 'nowrap' as const, overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.summary ?? item.title}</div>
                  <div style={{ fontSize: 10, color: '#94A3B8', flexShrink: 0 }}>{formatTime(item.created_at)}</div>
                </div>
              ))}
              {alerts.length === 0 && <div style={{ padding: 16, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>暂无未回复咨询</div>}
            </div>
          </div>

          {/* Quick Actions */}
          <div style={{ background: 'var(--erp-bg-card, white)', borderRadius: 12, border: '1px solid var(--erp-border, #E2E8F0)', padding: '14px 16px' }}>
            <h3 style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>快捷操作</h3>
            {[
              { icon: '🤖', bg: '#F5F3FF', color: '#7C3AED', text: 'AI 分析中心', sub: '查看全部分析结果', path: '/health/ai-analysis' },
              { icon: '⚠️', bg: '#FEF2F2', color: '#DC2626', text: '告警中心', sub: '处理体征异常告警', path: '/health/alert-dashboard' },
              { icon: '📋', bg: '#F0F9FF', color: '#0284C7', text: '患者查询', sub: '按姓名/编号搜索', path: '/health/patients' },
            ].map((action) => (
              <div
                key={action.path}
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, cursor: 'pointer', transition: 'all 0.15s', border: '1px solid #E2E8F0', marginBottom: 8 }}
                onClick={() => navigate(action.path)}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = '#2563EB'; e.currentTarget.style.background = '#EFF6FF'; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = '#E2E8F0'; e.currentTarget.style.background = 'transparent'; }}
              >
                <div style={{ width: 32, height: 32, borderRadius: 8, background: action.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15, flexShrink: 0 }}>{action.icon}</div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{action.text}</div>
                  <div style={{ fontSize: 11, color: '#94A3B8' }}>{action.sub}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
