import { useEffect } from 'react';
import { Skeleton, Empty } from 'antd';
import { useWorkbenchStore } from '../../../../stores/workbenchStore';
import type { ActionItem, ActionPriority, ActionType } from '../../../../api/health/actionInbox';

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

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

function formatTime(dateStr: string): string {
  const d = new Date(dateStr);
  const h = d.getHours().toString().padStart(2, '0');
  const m = d.getMinutes().toString().padStart(2, '0');
  return `${h}:${m}`;
}

function TaskItem({
  item,
  selected,
  onClick,
}: {
  item: ActionItem;
  selected: boolean;
  onClick: () => void;
}) {
  const tag = TYPE_TAG[item.action_type];

  return (
    <div
      onClick={onClick}
      style={{
        display: 'flex',
        gap: 10,
        padding: '12px 16px',
        cursor: 'pointer',
        background: selected ? '#EFF6FF' : 'transparent',
        borderLeft: selected ? '3px solid #2563EB' : '3px solid transparent',
        borderBottom: '1px solid #F1F5F9',
        transition: 'all 0.15s',
      }}
      onMouseEnter={(e) => {
        if (!selected) e.currentTarget.style.background = '#EFF6FF';
      }}
      onMouseLeave={(e) => {
        if (!selected) e.currentTarget.style.background = 'transparent';
      }}
    >
      <div
        style={{
          width: 8,
          height: 8,
          borderRadius: '50%',
          background: PRIORITY_DOT[item.priority] ?? PRIORITY_DOT.low,
          marginTop: 5,
          flexShrink: 0,
        }}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.3 }}>
          {item.title}
        </div>
        <div
          style={{
            fontSize: 11,
            color: '#94A3B8',
            marginTop: 3,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {item.summary ?? item.patient_name}
        </div>
        <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
          {tag && (
            <span
              style={{
                padding: '1px 6px',
                borderRadius: 3,
                fontSize: 10,
                fontWeight: 500,
                background: tag.bg,
                color: tag.color,
              }}
            >
              {tag.label}
            </span>
          )}
        </div>
      </div>
      <div
        style={{
          fontSize: 10,
          color: '#94A3B8',
          whiteSpace: 'nowrap',
          marginTop: 2,
        }}
      >
        {formatTime(item.created_at)}
      </div>
    </div>
  );
}

export default function TaskQueue() {
  const { tasks, selectedTaskId, tab, loading, stats, selectTask, setTab } =
    useWorkbenchStore();

  useEffect(() => {
    const { refreshTasks, refreshStats } = useWorkbenchStore.getState();
    refreshTasks();
    refreshStats();
  }, []);

  return (
    <div
      style={{
        width: 340,
        background: '#fff',
        borderRight: '1px solid #E2E8F0',
        display: 'flex',
        flexDirection: 'column',
        flexShrink: 0,
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: '16px 20px',
          borderBottom: '1px solid #E2E8F0',
        }}
      >
        <h2 style={{ fontSize: 16, fontWeight: 700, margin: 0 }}>
          今日任务流
        </h2>
        <div
          style={{
            display: 'flex',
            gap: 12,
            marginTop: 8,
            fontSize: 11,
            color: '#94A3B8',
          }}
        >
          <span>
            待处理{' '}
            <b style={{ color: '#DC2626' }}>
              {stats?.total_pending ?? tasks.length}
            </b>
          </span>
          {stats && (
            <span>
              已完成{' '}
              <b style={{ color: '#16A34A' }}>{stats.completion_rate ?? 0}</b>
            </span>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div
        style={{
          display: 'flex',
          borderBottom: '1px solid #E2E8F0',
        }}
      >
        {(['pending', 'completed'] as const).map((t) => (
          <div
            key={t}
            onClick={() => setTab(t)}
            style={{
              flex: 1,
              padding: 10,
              textAlign: 'center',
              fontSize: 12,
              fontWeight: 500,
              cursor: 'pointer',
              color: tab === t ? '#2563EB' : '#94A3B8',
              borderBottom: tab === t ? '2px solid #2563EB' : '2px solid transparent',
              transition: 'all 0.15s',
            }}
          >
            {t === 'pending' ? '待处理' : '已完成'}
            {t === 'pending' && stats?.total_pending != null && stats.total_pending > 0 && (
              <span
                style={{
                  display: 'inline-block',
                  background: '#DC2626',
                  color: 'white',
                  fontSize: 9,
                  padding: '0px 5px',
                  borderRadius: 8,
                  marginLeft: 4,
                  fontWeight: 600,
                }}
              >
                {stats.total_pending}
              </span>
            )}
          </div>
        ))}
      </div>

      {/* Task List */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {loading ? (
          <div style={{ padding: 16 }}>
            <Skeleton active paragraph={{ rows: 6 }} />
          </div>
        ) : tasks.length === 0 ? (
          <Empty
            description={
              tab === 'pending'
                ? '所有任务已处理完毕'
                : '暂无已完成任务'
            }
            style={{ marginTop: 48 }}
          />
        ) : (
          tasks.map((item) => (
            <TaskItem
              key={item.id}
              item={item}
              selected={selectedTaskId === item.id}
              onClick={() => selectTask(item.id)}
            />
          ))
        )}
      </div>
    </div>
  );
}
