import { useEffect, useState, useCallback } from 'react';
import { Card, Spin, Empty, Progress, Tag } from 'antd';
import {
  TeamOutlined,
  BellOutlined,
  WarningOutlined,
  ThunderboltOutlined,
  RobotOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import TodoList from './TodoList';
import AiInsightPanel from './AiInsightPanel';
import ActionDetailDrawer from './ActionDetailDrawer';
import {
  actionInboxApi,
  type ActionItem,
  type WorkbenchStats,
  type NursePatientSummary,
} from '../../../../api/health/actionInbox';

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

export default function NurseWorkbench() {
  const navigate = useNavigate();
  const [stats, setStats] = useState<WorkbenchStats | null>(null);
  const [patients, setPatients] = useState<NursePatientSummary[]>([]);
  const [loadingStats, setLoadingStats] = useState(true);
  const [loadingPatients, setLoadingPatients] = useState(true);
  const [drawerItem, setDrawerItem] = useState<ActionItem | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const fetchStats = useCallback(async () => {
    try {
      const data = await actionInboxApi.stats({ assigned_to_me: true });
      setStats(data);
    } finally {
      setLoadingStats(false);
    }
  }, []);

  const fetchPatients = useCallback(async () => {
    try {
      const data = await actionInboxApi.myPatients();
      setPatients(data);
    } finally {
      setLoadingPatients(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
    fetchPatients();
  }, [fetchStats, fetchPatients]);

  const completedToday = stats
    ? stats.total_pending > 0
      ? Math.round(((stats.total_pending - (stats.followup_due + stats.ai_suggestion_pending + stats.urgent_alerts)) / stats.total_pending) * 100)
      : 100
    : 0;

  const greeting = () => {
    const h = new Date().getHours();
    if (h < 6) return '夜班辛苦了';
    if (h < 12) return '早上好';
    if (h < 14) return '中午好';
    if (h < 18) return '下午好';
    return '晚上好';
  };

  const shiftLabel = () => {
    const h = new Date().getHours();
    if (h >= 8 && h < 16) return '白班';
    if (h >= 16 && h < 24) return '晚班';
    return '夜班';
  };

  const statCards = [
    { label: '今日待办', value: stats?.total_pending ?? 0, icon: <TeamOutlined />, color: '#2563EB' },
    { label: 'AI建议待审', value: stats?.ai_suggestion_pending ?? 0, icon: <RobotOutlined />, color: '#7C3AED' },
    { label: '危急告警', value: stats?.urgent_alerts ?? 0, icon: <WarningOutlined />, color: '#DC2626' },
    { label: '我的随访', value: stats?.followup_due ?? 0, icon: <BellOutlined />, color: '#0284C7' },
  ];

  return (
    <div>
      {/* 问候行 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
        <span style={{ fontSize: 20, fontWeight: 600 }}>{greeting()}，护理团队</span>
        <Tag color="blue" style={{ fontSize: 13, padding: '2px 10px' }}>{shiftLabel()}</Tag>
        <span style={{ marginLeft: 'auto', color: 'var(--erp-text-secondary)', fontSize: 13 }}>
          {new Date().toLocaleDateString('zh-CN', { month: 'long', day: 'numeric', weekday: 'long' })}
        </span>
      </div>

      {/* 统计卡片 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 20 }}>
        {statCards.map((card) => (
          <Card
            key={card.label}
            size="small"
            style={{ borderRadius: 10, border: '1px solid var(--erp-border, #E2E8F0)' }}
            loading={loadingStats}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 8,
                background: `${card.color}14`, color: card.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
              }}>
                {card.icon}
              </div>
              <div>
                <div style={{ fontSize: 20, fontWeight: 700, color: card.color }}>{card.value}</div>
                <div style={{ fontSize: 12, color: 'var(--erp-text-secondary)' }}>{card.label}</div>
              </div>
            </div>
          </Card>
        ))}
      </div>

      {/* 双栏布局 */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 20 }}>
        {/* 左栏 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* 班次患者 */}
          <Card
            title={<span style={{ fontSize: 15, fontWeight: 600 }}><TeamOutlined style={{ marginRight: 6 }} />我的班次患者</span>}
            size="small"
            style={{ borderRadius: 10 }}
          >
            {loadingPatients ? (
              <div style={{ textAlign: 'center', padding: 20 }}><Spin /></div>
            ) : patients.length === 0 ? (
              <Empty description="今日无班次患者" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {patients.map((p) => (
                  <div
                    key={p.patient_id}
                    onClick={() => navigate(`/health/patients/${p.patient_id}`)}
                    style={{
                      display: 'flex', alignItems: 'center', padding: '10px 12px',
                      borderRadius: 8, cursor: 'pointer',
                      border: '1px solid var(--erp-border, #E2E8F0)',
                      transition: 'border-color 0.2s',
                    }}
                    onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--erp-primary)'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--erp-border, #E2E8F0)'; }}
                    role="button"
                    tabIndex={0}
                    onKeyDown={(e) => { if (e.key === 'Enter') navigate(`/health/patients/${p.patient_id}`); }}
                  >
                    <span
                      style={{
                        width: 8, height: 8, borderRadius: '50%',
                        background: PRIORITY_COLORS[p.highest_priority] || '#94A3B8',
                        marginRight: 10, flexShrink: 0,
                      }}
                    />
                    <span style={{ fontWeight: 500, flex: 1 }}>{p.patient_name}</span>
                    <Tag color={p.pending_actions > 0 ? 'blue' : 'default'} style={{ margin: 0 }}>
                      {p.pending_actions} 项待办
                    </Tag>
                  </div>
                ))}
              </div>
            )}
          </Card>

          {/* 待办事项 */}
          <Card
            title={<span style={{ fontSize: 15, fontWeight: 600 }}><ThunderboltOutlined style={{ marginRight: 6 }} />待办事项</span>}
            size="small"
            style={{ borderRadius: 10 }}
          >
            <TodoList onItemClick={(item) => { setDrawerItem(item); setDrawerOpen(true); }} />
          </Card>
        </div>

        {/* 右栏 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* 快捷操作 */}
          <Card
            title={<span style={{ fontSize: 15, fontWeight: 600 }}>快捷操作</span>}
            size="small"
            style={{ borderRadius: 10 }}
          >
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {[
                { label: '开始随访', icon: '📋', path: '/health/follow-up' },
                { label: '录入体征', icon: '📊', path: '/health/vital-signs' },
                { label: '查看AI分析', icon: '🤖', path: '/health/action-inbox' },
                { label: '联系患者', icon: '📞', path: '/health/consultation' },
              ].map((action) => (
                <div
                  key={action.label}
                  onClick={() => navigate(action.path)}
                  style={{
                    padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                    border: '1px solid var(--erp-border, #E2E8F0)',
                    display: 'flex', alignItems: 'center', gap: 8,
                    transition: 'background 0.2s',
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--erp-bg-hover, #F8FAFC)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                  role="button"
                  tabIndex={0}
                  onKeyDown={(e) => { if (e.key === 'Enter') navigate(action.path); }}
                >
                  <span style={{ fontSize: 16 }}>{action.icon}</span>
                  <span style={{ fontSize: 13 }}>{action.label}</span>
                </div>
              ))}
            </div>
          </Card>

          {/* 今日进度 */}
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <CheckCircleOutlined style={{ color: '#16A34A' }} />
                <span style={{ fontSize: 15, fontWeight: 600 }}>今日进度</span>
              </div>
            }
            size="small"
            style={{ borderRadius: 10 }}
          >
            <Progress
              percent={completedToday}
              strokeColor={{ '0%': '#22C55E', '100%': '#16A34A' }}
              style={{ marginBottom: 8 }}
            />
            <div style={{ fontSize: 12, color: 'var(--erp-text-secondary)', textAlign: 'center' }}>
              {stats ? `${stats.total_pending} 项待处理` : '加载中...'}
            </div>
          </Card>

          {/* AI 洞察 */}
          <AiInsightPanel />
        </div>
      </div>

      {/* Action Detail Drawer */}
      <ActionDetailDrawer
        open={drawerOpen}
        item={drawerItem}
        onClose={() => { setDrawerOpen(false); setDrawerItem(null); }}
        onRefresh={() => { fetchStats(); }}
      />
    </div>
  );
}
