import { useState, useRef, useEffect, useCallback } from 'react';
import {
  Drawer,
  Input,
  Button,
  Space,
  Typography,
  Spin,
  Tag,
  Card,
  theme,
} from 'antd';
import {
  SendOutlined,
  RobotOutlined,
  DeleteOutlined,
  WarningOutlined,
  SafetyCertificateOutlined,
} from '@ant-design/icons';
import { useLocation } from 'react-router-dom';
import { aiChatApi, type ChatHistoryItem, type DisplayHint } from '../../api/ai/chat';
import { analysisApi, type HealthSummaryResponse } from '../../api/ai/analysis';
import { useAuthStore } from '../../stores/auth';
import RichMessage from './RichMessage';

const { Text } = Typography;
const { TextArea } = Input;

interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  displayHints?: DisplayHint[];
}

function extractPatientId(pathname: string): string | null {
  const match = pathname.match(/\/health\/patients\/([0-9a-f-]+)/i);
  return match?.[1] ?? null;
}

const RISK_CONFIG: Record<string, { color: string; label: string }> = {
  low: { color: 'green', label: '低风险' },
  medium: { color: 'orange', label: '中风险' },
  high: { color: 'red', label: '高风险' },
  critical: { color: '#cf1322', label: '严重' },
};

export default function AiSidebar({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [summary, setSummary] = useState<HealthSummaryResponse | null>(null);
  const [summaryLoading, setSummaryLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const location = useLocation();
  const { token } = theme.useToken();

  const patientId = extractPatientId(location.pathname);
  const permissions = useAuthStore((s) => s.permissions);
  const canChat = permissions.includes('ai.chat.send');
  const canViewSummary = permissions.includes('ai.analysis.list');

  // 欢迎消息
  useEffect(() => {
    if (open && messages.length === 0) {
      setMessages([
        {
          id: 'welcome',
          role: 'assistant',
          content: patientId
            ? '你好！我是 AI 健康助手。当前已关联患者档案，你可以问我关于该患者的体征、化验报告、用药等信息。'
            : '你好！我是 AI 健康助手。你可以向我咨询健康相关问题，或打开患者详情页查看患者数据。',
        },
      ]);
    }
  }, [open]); // eslint-disable-line react-hooks/exhaustive-deps

  // 自动加载患者健康摘要
  useEffect(() => {
    if (!open || !patientId || !canViewSummary) {
      setSummary(null);
      return;
    }
    let cancelled = false;
    setSummaryLoading(true);
    analysisApi
      .getHealthSummary(patientId)
      .then((data) => {
        if (!cancelled) setSummary(data);
      })
      .catch(() => {
        if (!cancelled) setSummary(null);
      })
      .finally(() => {
        if (!cancelled) setSummaryLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open, patientId, canViewSummary]);

  const scrollToBottom = useCallback(() => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  const handleSend = async () => {
    const text = input.trim();
    if (!text || loading || !canChat) return;

    const userMsg: ChatMessage = {
      id: `u-${Date.now()}`,
      role: 'user',
      content: text,
    };

    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput('');
    setLoading(true);

    try {
      const history: ChatHistoryItem[] = newMessages
        .filter((m) => m.id !== 'welcome')
        .map((m) => ({
          role: m.role,
          content: m.content,
        }));

      const resp = await aiChatApi.sendMessage(
        text,
        history,
        patientId ?? undefined
      );

      setMessages((prev) => [
        ...prev,
        {
          id: resp.message_id,
          role: 'assistant' as const,
          content: resp.reply,
          displayHints: resp.display_hints,
        },
      ]);
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          id: `err-${Date.now()}`,
          role: 'assistant',
          content: '抱歉，AI 服务暂时不可用，请稍后再试。',
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleClear = () => {
    setMessages([
      {
        id: 'welcome',
        role: 'assistant',
        content: '对话已清空。有什么可以帮你的？',
      },
    ]);
  };

  const riskInfo = summary ? RISK_CONFIG[summary.risk_level] ?? RISK_CONFIG.low : null;

  return (
    <Drawer
      title={
        <Space>
          <RobotOutlined style={{ color: token.colorPrimary }} />
          <span>AI 健康助手</span>
          {patientId && (
            <Tag color="blue" style={{ marginLeft: 8, fontSize: 11 }}>
              已关联患者
            </Tag>
          )}
        </Space>
      }
      placement="right"
      size={400}
      open={open}
      onClose={onClose}
      styles={{
        body: { display: 'flex', flexDirection: 'column', padding: 0 },
      }}
      extra={
        <Button
          size="small"
          icon={<DeleteOutlined />}
          onClick={handleClear}
          title="清空对话"
        />
      }
    >
      {/* 患者健康摘要卡片 */}
      {patientId && canViewSummary && (
        <div style={{ padding: '12px 16px 0' }}>
          {summaryLoading ? (
            <Card size="small" style={{ textAlign: 'center' }}>
              <Spin size="small" /> <Text type="secondary">加载健康摘要...</Text>
            </Card>
          ) : summary ? (
            <Card
              size="small"
              title={
                <Space size={4}>
                  <SafetyCertificateOutlined />
                  <span style={{ fontSize: 13 }}>健康摘要</span>
                  {riskInfo && (
                    <Tag
                      color={riskInfo.color}
                      style={{ marginLeft: 4, fontSize: 11 }}
                    >
                      {riskInfo.label}
                    </Tag>
                  )}
                </Space>
              }
              style={{ marginBottom: 4 }}
              styles={{ body: { padding: '8px 12px' } }}
            >
              <div style={{ fontSize: 12, color: token.colorTextSecondary }}>
                <div style={{ marginBottom: 4 }}>
                  活跃洞察 {summary.active_insights_count} 项
                  {summary.recent_analyses_count > 0 &&
                    ` | 近期分析 ${summary.recent_analyses_count} 次`}
                </div>
                {summary.summary_items.length > 0 && (
                  <div>
                    {summary.summary_items.slice(0, 3).map((item, i) => (
                      <div key={i} style={{ marginTop: 3 }}>
                        <Tag
                          color={
                            item.severity === 'high'
                              ? 'red'
                              : item.severity === 'medium'
                                ? 'orange'
                                : 'blue'
                          }
                          style={{ fontSize: 10, marginRight: 4 }}
                        >
                          {item.category}
                        </Tag>
                        <span>{item.title}</span>
                      </div>
                    ))}
                    {summary.summary_items.length > 3 && (
                      <Text
                        type="secondary"
                        style={{ fontSize: 11, marginTop: 2, display: 'block' }}
                      >
                        还有 {summary.summary_items.length - 3} 项...
                      </Text>
                    )}
                  </div>
                )}
                {summary.latest_insight_title && (
                  <div
                    style={{
                      marginTop: 4,
                      paddingTop: 4,
                      borderTop: `1px solid ${token.colorBorderSecondary}`,
                    }}
                  >
                    <WarningOutlined style={{ marginRight: 4, color: token.colorWarning }} />
                    最新: {summary.latest_insight_title}
                  </div>
                )}
              </div>
            </Card>
          ) : null}
        </div>
      )}

      {/* 消息列表 */}
      <div
        style={{
          flex: 1,
          overflowY: 'auto',
          padding: '12px 16px',
          background: token.colorBgLayout,
        }}
      >
        {messages.map((msg) => (
          <div
            key={msg.id}
            style={{
              display: 'flex',
              justifyContent:
                msg.role === 'user' ? 'flex-end' : 'flex-start',
              marginBottom: 12,
            }}
          >
            <div
              style={{
                maxWidth: '85%',
                padding: '8px 12px',
                borderRadius: 12,
                fontSize: 14,
                lineHeight: 1.6,
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word',
                background:
                  msg.role === 'user'
                    ? token.colorPrimary
                    : token.colorBgContainer,
                color:
                  msg.role === 'user'
                    ? token.colorTextLightSolid
                    : token.colorText,
                borderBottomRightRadius: msg.role === 'user' ? 4 : 12,
                borderBottomLeftRadius: msg.role === 'assistant' ? 4 : 12,
              }}
            >
              {msg.content}
              {msg.displayHints && msg.displayHints.length > 0 && (
                <RichMessage hints={msg.displayHints} />
              )}
            </div>
          </div>
        ))}
        {loading && (
          <div
            style={{
              display: 'flex',
              justifyContent: 'flex-start',
              marginBottom: 12,
            }}
          >
            <div
              style={{
                padding: '8px 16px',
                borderRadius: 12,
                borderBottomLeftRadius: 4,
                background: token.colorBgContainer,
              }}
            >
              <Spin size="small" />{' '}
              <Text type="secondary">思考中...</Text>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div
        style={{
          padding: 12,
          borderTop: `1px solid ${token.colorBorderSecondary}`,
          background: token.colorBgContainer,
        }}
      >
        <Space.Compact style={{ width: '100%' }}>
          <TextArea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={
              canChat
                ? '输入消息... (Enter 发送, Shift+Enter 换行)'
                : '无 AI 聊天权限'
            }
            disabled={loading || !canChat}
            autoSize={{ minRows: 1, maxRows: 4 }}
            style={{ borderRadius: '8px 0 0 8px' }}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            loading={loading}
            disabled={!input.trim() || !canChat}
            style={{
              height: 'auto',
              borderRadius: '0 8px 8px 0',
              minHeight: 40,
            }}
          />
        </Space.Compact>
        {!canChat && (
          <Text
            type="warning"
            style={{ fontSize: 12, marginTop: 4, display: 'block' }}
          >
            你没有 AI 聊天权限，请联系管理员开通。
          </Text>
        )}
      </div>
    </Drawer>
  );
}
