import { useEffect, useState } from 'react';
import { Button, Skeleton, message, Space } from 'antd';
import { useWorkbenchStore } from '../../../../stores/workbenchStore';
import {
  actionInboxApi,
  type ThreadResponse,
  type ActionDefinition,
  type ActionType,
} from '../../../../api/health/actionInbox';
import client from '../../../../api/client';

const TYPE_BADGE: 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 formatTimeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes} 分钟前`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours} 小时前`;
  return `${Math.floor(hours / 24)} 天前`;
}

export default function TaskDetail() {
  const { tasks, selectedTaskId, completeTask, refreshTasks } =
    useWorkbenchStore();
  const [thread, setThread] = useState<ThreadResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  const selectedTask = tasks.find((t) => t.id === selectedTaskId);

  useEffect(() => {
    if (!selectedTask?.id) {
      setThread(null);
      return;
    }
    setLoading(true);
    actionInboxApi
      .getThread(selectedTask.id)
      .then((resp) => setThread(resp ?? null))
      .catch(() => setThread(null))
      .finally(() => setLoading(false));
  }, [selectedTask?.id]);

  const handleAction = async (endpoint: string) => {
    if (!selectedTask) return;
    setActionLoading(true);
    try {
      const uuid = selectedTask.source_ref;
      await client.post(endpoint.replace(':id', uuid));
      message.success('操作成功');
      completeTask(selectedTask.id);
      refreshTasks();
    } catch {
      message.error('操作失败');
    } finally {
      setActionLoading(false);
    }
  };

  if (!selectedTask) {
    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100%',
          color: '#94A3B8',
        }}
      >
        <div style={{ fontSize: 40, marginBottom: 12, opacity: 0.3 }}>
          📋
        </div>
        <div>从左侧选择一个任务开始处理</div>
      </div>
    );
  }

  const typeBadge = TYPE_BADGE[selectedTask.action_type];
  const actions = thread?.available_actions ?? [];

  const renderFallbackButtons = () => {
    if (actions.length > 0) return null;
    switch (selectedTask.action_type) {
      case 'alert':
        return (
          <Button
            type="primary"
            danger
            loading={actionLoading}
            onClick={() =>
              handleAction('/health/alerts/:id/acknowledge')
            }
          >
            立即处理
          </Button>
        );
      case 'ai_suggestion':
        return (
          <Space>
            <Button
              type="primary"
              loading={actionLoading}
              onClick={() =>
                handleAction(
                  '/health/ai-analysis/:id/review?action=approve',
                )
              }
            >
              采纳建议
            </Button>
            <Button
              danger
              loading={actionLoading}
              onClick={() =>
                handleAction(
                  '/health/ai-analysis/:id/review?action=reject',
                )
              }
            >
              拒绝
            </Button>
          </Space>
        );
      case 'followup':
        return (
          <Button
            type="primary"
            loading={actionLoading}
            onClick={() =>
              handleAction('/health/follow-up/:id/complete')
            }
          >
            完成随访
          </Button>
        );
      default:
        return (
          <Button type="primary" loading={actionLoading}>
            查看详情
          </Button>
        );
    }
  };

  return (
    <div
      style={{
        flex: 1,
        overflow: 'auto',
        padding: '24px 28px',
        background: '#F8FAFC',
      }}
    >
      {/* Patient Bar */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          marginBottom: 20,
          padding: '16px 20px',
          background: '#fff',
          borderRadius: 12,
          border: '1px solid #E2E8F0',
        }}
      >
        <div
          style={{
            width: 40,
            height: 40,
            borderRadius: '50%',
            background: '#EFF6FF',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#2563EB',
            fontWeight: 700,
            fontSize: 16,
          }}
        >
          {(selectedTask.patient_name ?? '患').charAt(0)}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600 }}>
            {selectedTask.patient_name ?? '未知患者'}
          </div>
          <div
            style={{
              fontSize: 12,
              color: '#94A3B8',
              marginTop: 2,
            }}
          >
            {selectedTask.patient_id
              ? `患者编号 ${selectedTask.patient_id.slice(0, 8)}`
              : ''}
          </div>
        </div>
        {typeBadge && (
          <span
            style={{
              padding: '3px 10px',
              background: typeBadge.bg,
              color: typeBadge.color,
              borderRadius: 4,
              fontSize: 11,
              fontWeight: 600,
            }}
          >
            {typeBadge.label}
          </span>
        )}
        {selectedTask.priority === 'urgent' ? (
          <span
            style={{
              padding: '3px 10px',
              background: '#FFFBEB',
              color: '#D97706',
              borderRadius: 4,
              fontSize: 11,
              fontWeight: 600,
            }}
          >
            超时 {formatTimeAgo(selectedTask.created_at)}
          </span>
        ) : null}
      </div>

      {loading ? (
        <Skeleton active paragraph={{ rows: 8 }} />
      ) : (
        <>
          {/* AI Suggestion Card */}
          {(selectedTask.action_type === 'ai_suggestion' ||
            selectedTask.action_type === 'alert') && (
            <div
              style={{
                background: '#fff',
                borderRadius: 12,
                border: '1px solid #E2E8F0',
                marginBottom: 16,
                overflow: 'hidden',
              }}
            >
              <div
                style={{
                  padding: '16px 20px',
                  borderBottom: '1px solid #F1F5F9',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>
                  {selectedTask.action_type === 'ai_suggestion'
                    ? 'AI 分析建议'
                    : '异常体征数据'}
                </h3>
                <span
                  style={{
                    fontSize: 11,
                    color:
                      selectedTask.priority === 'urgent'
                        ? '#DC2626'
                        : '#94A3B8',
                    fontWeight: 600,
                  }}
                >
                  上报于{' '}
                  {new Date(selectedTask.created_at).toLocaleTimeString(
                    'zh-CN',
                    { hour: '2-digit', minute: '2-digit' },
                  )}
                </span>
              </div>
              <div style={{ padding: '16px 20px' }}>
                <div
                  style={{
                    padding: '14px 20px',
                    background:
                      selectedTask.action_type === 'ai_suggestion'
                        ? '#F5F3FF'
                        : '#FEF2F2',
                    borderRadius: 10,
                    marginBottom: 12,
                  }}
                >
                  <div
                    style={{
                      fontSize: 11,
                      color:
                        selectedTask.action_type === 'ai_suggestion'
                          ? '#7C3AED'
                          : '#DC2626',
                      fontWeight: 600,
                      marginBottom: 4,
                    }}
                  >
                    {selectedTask.action_type === 'ai_suggestion'
                      ? '风险评估'
                      : '异常提示'}
                  </div>
                  <div
                    style={{
                      fontSize: 13,
                      color: '#1E293B',
                      lineHeight: 1.6,
                    }}
                  >
                    {selectedTask.summary ?? selectedTask.title}
                  </div>
                </div>
                <div
                  style={{
                    padding: '14px 20px',
                    background: '#F0F9FF',
                    borderRadius: 10,
                  }}
                >
                  <div
                    style={{
                      fontSize: 11,
                      color: '#0284C7',
                      fontWeight: 600,
                      marginBottom: 4,
                    }}
                  >
                    建议措施
                  </div>
                  <div
                    style={{
                      fontSize: 13,
                      color: '#1E293B',
                      lineHeight: 1.6,
                    }}
                  >
                    请根据患者实际情况，联系患者确认病情并安排相应处理。
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Thread Timeline */}
          {thread?.thread && thread.thread.length > 0 && (
            <div
              style={{
                background: '#fff',
                borderRadius: 12,
                border: '1px solid #E2E8F0',
                marginBottom: 16,
                overflow: 'hidden',
              }}
            >
              <div
                style={{
                  padding: '16px 20px',
                  borderBottom: '1px solid #F1F5F9',
                }}
              >
                <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>
                  处理记录
                </h3>
              </div>
              <div>
                {thread.thread.map((evt, i) => (
                  <div
                    key={i}
                    style={{
                      padding: '10px 20px',
                      borderBottom:
                        i < thread.thread.length - 1
                          ? '1px solid #F1F5F9'
                          : undefined,
                    }}
                  >
                    <div style={{ fontSize: 12, color: '#94A3B8' }}>
                      {evt.label}
                    </div>
                    {evt.detail && (
                      <div
                        style={{
                          fontSize: 13,
                          color: '#475569',
                          marginTop: 2,
                        }}
                      >
                        {evt.detail}
                      </div>
                    )}
                    {evt.timestamp && (
                      <div
                        style={{
                          fontSize: 11,
                          color: '#94A3B8',
                          marginTop: 2,
                        }}
                      >
                        {evt.timestamp}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Summary Card for non-AI/alert tasks */}
          {selectedTask.action_type !== 'ai_suggestion' &&
            selectedTask.action_type !== 'alert' && (
              <div
                style={{
                  background: '#fff',
                  borderRadius: 12,
                  border: '1px solid #E2E8F0',
                  marginBottom: 16,
                  overflow: 'hidden',
                }}
              >
                <div
                  style={{
                    padding: '16px 20px',
                    borderBottom: '1px solid #F1F5F9',
                  }}
                >
                  <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0 }}>
                    任务摘要
                  </h3>
                </div>
                <div style={{ padding: '12px 20px' }}>
                  <div style={{ fontSize: 13, color: '#475569' }}>
                    {selectedTask.summary ?? selectedTask.title}
                  </div>
                  <div
                    style={{
                      fontSize: 11,
                      color: '#94A3B8',
                      marginTop: 8,
                    }}
                  >
                    创建于{' '}
                    {new Date(selectedTask.created_at).toLocaleString(
                      'zh-CN',
                    )}
                  </div>
                </div>
              </div>
            )}

          {/* Action Buttons */}
          <div style={{ display: 'flex', gap: 10, padding: '8px 0' }}>
            {actions.length > 0
              ? actions.map((action: ActionDefinition) => (
                  <Button
                    key={action.key}
                    type={action.variant === 'primary' ? 'primary' : 'default'}
                    danger={action.variant === 'danger'}
                    loading={actionLoading}
                    onClick={() =>
                      action.api_endpoint &&
                      handleAction(action.api_endpoint)
                    }
                  >
                    {action.label}
                  </Button>
                ))
              : renderFallbackButtons()}
            <Button
              style={{ marginLeft: 'auto' }}
              onClick={() => {
                useWorkbenchStore.getState().selectTask(null);
              }}
            >
              稍后处理
            </Button>
          </div>
        </>
      )}
    </div>
  );
}
