import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Layout, Typography, Spin, Button, Card, Tooltip, message, Modal, Select, Input, Space } from 'antd';
import { LoadingOutlined, WarningOutlined, SaveOutlined, EditOutlined, CheckOutlined, RobotOutlined, PlayCircleOutlined } from '@ant-design/icons';

const { Content } = Layout;
const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface SmartCanvasProps {
  content: string;
  streaming: boolean;
  annotations?: any[];
  onStartGenerate?: () => void;
  onStartWriting?: () => void;
  onContentChange?: (content: string) => void;
  onContentSave?: (content: string) => void;
  onAIAssist?: (content: string, options?: AIAssistOptions) => void;
  episodeTitle?: string;
  episodeNumber?: number | null;
  episodeStatus?: 'pending' | 'draft' | 'writing' | 'completed';
  availableSkills?: any[];
  projectId?: string;
  onTitleChange?: (title: string) => void;
  onConfirmComplete?: () => void;
}

interface AIAssistOptions {
  skills?: any[];
  customPrompt?: string;
  injectAgent?: boolean;
}

export const SmartCanvas: React.FC<SmartCanvasProps> = ({
  content,
  streaming,
  annotations = [],
  onStartGenerate,
  onStartWriting,
  onContentChange,
  onContentSave,
  onAIAssist,
  episodeTitle = '未命名草稿',
  episodeNumber = null,
  episodeStatus = 'pending',
  availableSkills = [],
  projectId,
  onTitleChange,
  onConfirmComplete
}) => {
  // 移除编辑模式切换，内容始终可编辑
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [editTitle, setEditTitle] = useState(episodeTitle);
  const [editContent, setEditContent] = useState(content);
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [selectedText, setSelectedText] = useState('');
  const [showAIAssistModal, setShowAIAssistModal] = useState(false);
  const [selectedSkills, setSelectedSkills] = useState<any[]>([]);
  const [customPrompt, setCustomPrompt] = useState('');
  const [injectAgent, setInjectAgent] = useState(true);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 显示标题处理 - 与侧边栏保持一致，直接显示剧集标题（如"第1集"）
  const displayTitle = useMemo(() => {
    // 优先使用传入的 episodeTitle（来自数据库的剧集标题）
    if (episodeTitle && episodeTitle !== '未命名草稿') {
      // 如果 episodeTitle 本身不包含 "第X集"，且有 episodeNumber，则组合
      if (episodeNumber !== null && !episodeTitle.includes(`第${episodeNumber}集`)) {
        return `第${episodeNumber}集：${episodeTitle}`;
      }
      return episodeTitle;
    }
    // 如果没有 episodeTitle，根据 episodeNumber 生成默认标题（与侧边栏一致）
    if (episodeNumber !== null && episodeNumber !== undefined) {
      return `第${episodeNumber}集`;
    }
    return '请选择剧集';
  }, [episodeNumber, episodeTitle]);

  // Update editContent and editTitle when props change
  useEffect(() => {
    // 自动清理内容中的重复标题
    let cleaned = content?.trim() || '';
    if (episodeNumber !== null) {
      const titlePrefixPattern = new RegExp(`^第\\s*${episodeNumber}\\s*集[:：\\s]*.*?(?:\\n|$)`, 'i');
      cleaned = cleaned.replace(titlePrefixPattern, '').trim();
    }
    if (episodeTitle && episodeTitle !== '未命名草稿') {
      const escapedTitle = episodeTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const titlePattern = new RegExp(`^${escapedTitle}[:：\\s]*(?:\\n|$)`, 'i');
      cleaned = cleaned.replace(titlePattern, '').trim();
    }
    setEditContent(cleaned);
  }, [content, episodeNumber, episodeTitle]);

  useEffect(() => {
    // 使用 displayTitle 作为编辑标题的初始值
    setEditTitle(displayTitle);
  }, [displayTitle]);

  const handleSave = () => {
    if (onContentSave) {
      onContentSave(editContent);
      message.success('内容已保存');
    }
  };

  const handleTextSelection = () => {
    const selection = window.getSelection();
    const text = selection?.toString() || '';
    setSelectedText(text);

    if (text.length > 0) {
      setShowSaveModal(true);
    }
  };

  const handleInsertReference = () => {
    // This will be handled by parent component through callback
    setShowSaveModal(false);
    // Notify parent to insert reference into chat
    if (onContentChange) {
      onContentChange(`【引用】: ${selectedText}`);
    }
    message.info('已复制到剪贴板，可以在对话框中粘贴引用');
    navigator.clipboard.writeText(selectedText);
  };

  const handleAIAssist = () => {
    if (onAIAssist) {
      setShowAIAssistModal(true);
    }
  };

  const handleAIAssistConfirm = () => {
    if (onAIAssist) {
      onAIAssist(editContent || content, {
        skills: selectedSkills,
        customPrompt: customPrompt || undefined,
        injectAgent
      });
      setShowAIAssistModal(false);
    }
  };

  return (
    <Content style={{
      padding: '32px 48px',
      background: '#fff',
      height: '100%',
      position: 'relative',
      display: 'flex',
      flexDirection: 'column'
    }}>
      <div style={{ flex: 1, maxWidth: '900px', margin: '0 auto', width: '100%', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
        {/* 标题区域 */}
        <div style={{ textAlign: 'center', marginBottom: '32px', position: 'relative' }}>
          {isEditingTitle ? (
            <Space direction="vertical" align="center">
              <Space>
                <Input
                  value={editTitle}
                  onChange={(e) => setEditTitle(e.target.value)}
                  onPressEnter={() => {
                    setIsEditingTitle(false);
                    const titleOnly = editTitle.replace(/^第\s*\d+\s*集/, '');
                    onTitleChange?.(titleOnly || editTitle);
                  }}
                  style={{
                    width: '320px',
                    fontSize: '18px',
                    fontWeight: 'bold',
                    borderRadius: '8px',
                    border: '2px solid #667eea'
                  }}
                  placeholder="输入剧集名称"
                />
                <Button
                  type="primary"
                  size="small"
                  icon={<CheckOutlined />}
                  onClick={() => {
                    setIsEditingTitle(false);
                    const titleOnly = editTitle.replace(/^第\s*\d+\s*集/, '');
                    onTitleChange?.(titleOnly || editTitle);
                  }}
                  style={{ borderRadius: '6px' }}
                >
                  保存
                </Button>
                <Button
                  size="small"
                  onClick={() => {
                    setIsEditingTitle(false);
                    setEditTitle(displayTitle);
                  }}
                  style={{ borderRadius: '6px' }}
                >
                  取消
                </Button>
              </Space>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                提示：只需输入剧集名称，"第X集"会自动添加
              </Text>
            </Space>
          ) : (
            <div style={{ display: 'inline-block', position: 'relative' }}>
              <Title level={3} style={{
                display: 'inline-block',
                margin: 0,
                color: '#1a1a1a',
                paddingRight: '40px',
                fontWeight: 600
              }}>
                {displayTitle}
              </Title>
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => {
                  const titleOnly = displayTitle.replace(/^第\s*\d+\s*集/, '');
                  setEditTitle(titleOnly || displayTitle);
                  setIsEditingTitle(true);
                }}
                style={{
                  position: 'absolute',
                  right: '0',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  color: '#999'
                }}
              />
            </div>
          )}
        </div>

        {/* 操作按钮 */}
        {!streaming && content && (
          <div style={{
            position: 'absolute',
            top: '32px',
            right: '48px',
            display: 'flex',
            gap: '8px',
            zIndex: 10,
            flexWrap: 'wrap',
            justifyContent: 'flex-end'
          }}>
            {onAIAssist && (
              <Tooltip title="AI 辅助修改">
                <Button
                  type="default"
                  size="small"
                  icon={<RobotOutlined />}
                  onClick={handleAIAssist}
                  style={{ borderRadius: '6px' }}
                >
                  AI 辅助
                </Button>
              </Tooltip>
            )}
            <Tooltip title="保存到草稿">
              <Button
                type="primary"
                size="small"
                icon={<SaveOutlined />}
                onClick={handleSave}
                style={{ borderRadius: '6px' }}
              >
                保存
              </Button>
            </Tooltip>
          </div>
        )}

        <>
          {/* 始终显示可编辑的文本区域 */}
          <div style={{ position: 'relative', width: '100%' }}>
            <textarea
              ref={textareaRef}
              value={editContent}
              onChange={(e) => {
                setEditContent(e.target.value);
                if (onContentChange) {
                  onContentChange(e.target.value);
                }
              }}
              placeholder={episodeStatus === 'pending' ? '等待开始创作...' : '在此编辑剧集内容...'}
              style={{
                width: '100%',
                minHeight: '500px',
                height: '100%',
                padding: '24px',
                fontSize: '16px',
                lineHeight: '1.8',
                color: '#1a1a1a',
                fontFamily: "'Merriweather', 'Georgia', serif",
                border: '1px solid #e8e8e8',
                borderRadius: '12px',
                resize: 'vertical',
                outline: 'none',
                whiteSpace: 'pre-wrap',
                backgroundColor: '#fafafa',
                transition: 'all 0.2s',
                boxSizing: 'border-box'
              }}
              onFocus={(e) => {
                e.currentTarget.style.borderColor = '#667eea';
                e.currentTarget.style.backgroundColor = '#fff';
                e.currentTarget.style.boxShadow = '0 0 0 3px rgba(102, 126, 234, 0.1)';
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = '#e8e8e8';
                e.currentTarget.style.backgroundColor = '#fafafa';
                e.currentTarget.style.boxShadow = 'none';
              }}
              onMouseUp={handleTextSelection}
            />
            {streaming && (
              <div style={{
                position: 'absolute',
                top: '16px',
                right: '16px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: '#fff',
                padding: '6px 16px',
                borderRadius: '20px',
                fontSize: '13px',
                fontWeight: 500,
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                boxShadow: '0 4px 12px rgba(102, 126, 234, 0.3)'
              }}>
                <Spin indicator={<LoadingOutlined style={{ fontSize: 12 }} spin />} />
                AI 正在创作中...
              </div>
            )}
          </div>

          {/* 编辑台下方操作按钮 - 固定在编辑区域底部 */}
          {!streaming && (
            <div style={{
              marginTop: 'auto',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              gap: '16px',
              padding: '16px 0',
              borderTop: '1px solid #f0f0f0',
              background: '#fff',
              boxShadow: '0 -2px 8px rgba(0, 0, 0, 0.06)',
              position: 'sticky',
              bottom: '0'
            }}>
              {/* 左侧：创作按钮 */}
              <div style={{ display: 'flex', justifyContent: 'center', gap: '16px', flexWrap: 'wrap' }}>
                {/* 当没有内容时显示开始创作按钮 */}
                {!content && (
                  <Space size="middle">
                    <Button
                      size="large"
                      icon={<RobotOutlined />}
                      onClick={onStartGenerate}
                      style={{
                        minWidth: '140px',
                        borderRadius: '8px',
                        height: '44px'
                      }}
                    >
                      生成大纲
                    </Button>
                    <Button
                      type="primary"
                      size="large"
                      icon={<PlayCircleOutlined />}
                      onClick={onStartWriting}
                      style={{
                        minWidth: '140px',
                        borderRadius: '8px',
                        height: '44px',
                        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                        border: 'none'
                      }}
                    >
                      开始创作
                    </Button>
                  </Space>
                )}
                {/* 当有内容且状态为草稿或创作中时显示确认按钮 */}
                {content && (episodeStatus === 'draft' || episodeStatus === 'writing') && onConfirmComplete && (
                  <Button
                    type="primary"
                    size="large"
                    icon={<CheckOutlined />}
                    onClick={onConfirmComplete}
                    style={{
                      backgroundColor: '#52c41a',
                      borderColor: '#52c41a',
                      minWidth: '180px',
                      borderRadius: '8px',
                      height: '44px',
                      fontSize: '16px'
                    }}
                  >
                    确认剧集内容
                  </Button>
                )}
              </div>

              {/* 右侧：保存按钮 */}
              <Button
                type="primary"
                size="large"
                icon={<SaveOutlined />}
                onClick={handleSave}
                style={{
                  minWidth: '140px',
                  borderRadius: '8px',
                  height: '44px'
                }}
              >
                保存剧集内容
              </Button>
            </div>
          )}
        </>
      </div>

      {/* Annotations Sidebar */}
      {annotations.length > 0 && (
        <div style={{ width: '250px', borderLeft: '1px solid #f0f0f0', paddingLeft: '16px' }}>
          <Title level={5} style={{ fontSize: '14px', marginBottom: '16px' }}>批注 (Annotations)</Title>
          {annotations.map((note, idx) => (
            <Card
              key={idx}
              size="small"
              style={{ marginBottom: '8px', borderColor: '#ffccc7', background: '#fff1f0' }}
              title={<span style={{ color: '#cf1322', fontSize: '12px' }}><WarningOutlined /> {note.type || 'Review Issue'}</span>}
            >
              <Text style={{ fontSize: '12px' }}>{note.content || note.description}</Text>
              {note.suggestion && (
                <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
                  建议: {note.suggestion}
                </div>
              )}
            </Card>
          ))}
        </div>
      )}

      {/* 悬浮状态指示 */}
      {streaming && (
        <div style={{
          position: 'absolute',
          top: '20px',
          right: '20px',
          background: 'rgba(24, 144, 255, 0.1)',
          padding: '4px 12px',
          borderRadius: '14px',
          color: '#1890ff',
          display: 'flex',
          alignItems: 'center'
        }}>
          <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} style={{ marginRight: '8px' }} />
          正在实时生成...
        </div>
      )}

      {/* 文本引用模态框 */}
      <Modal
        title="引用文本"
        open={showSaveModal}
        onOk={handleInsertReference}
        onCancel={() => setShowSaveModal(false)}
        okText="复制并引用"
        cancelText="取消"
      >
        <p style={{ marginBottom: '8px', color: '#666' }}>选中的文本：</p>
        <div style={{
          padding: '12px',
          background: '#f5f5f5',
          borderRadius: '4px',
          maxHeight: '200px',
          overflow: 'auto',
          fontSize: '14px',
          lineHeight: '1.6'
        }}>
          {selectedText}
        </div>
        <p style={{ marginTop: '12px', color: '#999', fontSize: '12px' }}>
          点击"复制并引用"将复制到剪贴板，可以在对话框中粘贴使用
        </p>
      </Modal>

      {/* AI 辅助配置模态框 */}
      <Modal
        title="AI 辅助修改配置"
        open={showAIAssistModal}
        onOk={handleAIAssistConfirm}
        onCancel={() => setShowAIAssistModal(false)}
        okText="开始优化"
        cancelText="取消"
        width={600}
      >
        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
            选择 Skills（可选）：
          </label>
          <Select
            mode="multiple"
            placeholder="选择要应用的 Skills"
            style={{ width: '100%' }}
            value={selectedSkills}
            onChange={setSelectedSkills}
            options={availableSkills.map((skill: any) => ({
              label: skill.name,
              value: skill.id,
              description: skill.description
            }))}
            optionRender={(option) => (
              <div>
                <div>{option.data.label}</div>
                <div style={{ fontSize: '12px', color: '#999' }}>
                  {option.data.description}
                </div>
              </div>
            )}
          />
          <p style={{ marginTop: '4px', fontSize: '12px', color: '#999' }}>
            选择的 Skills 将融入 AI 辅助修改的行为指导中
          </p>
        </div>

        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
            自定义提示词（可选）：
          </label>
          <TextArea
            placeholder="输入自定义的修改要求或指导..."
            value={customPrompt}
            onChange={(e) => setCustomPrompt(e.target.value)}
            rows={3}
            maxLength={500}
            showCount
          />
        </div>

        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={injectAgent}
              onChange={(e) => setInjectAgent(e.target.checked)}
              style={{ marginRight: '8px' }}
            />
            <span>
              启用 Agent 注入
            </span>
          </label>
          <p style={{ marginTop: '4px', marginLeft: '24px', fontSize: '12px', color: '#999' }}>
            开启后，AI 将使用 Agent 模式进行后台优化，优化过程对用户透明
          </p>
        </div>

        <div style={{ padding: '12px', background: '#f0f5ff', borderRadius: '4px', border: '1px solid #adc6ff' }}>
          <div style={{ fontSize: '13px', color: '#333' }}>
            <strong>功能说明：</strong>
            <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
              <li>AI 将分析当前内容并给出优化建议</li>
              <li>支持的 Skills 会自动融入修改指导</li>
              <li>Agent 注入模式确保优化过程对用户透明</li>
              <li>优化后的内容将直接更新到画布上</li>
            </ul>
          </div>
        </div>
      </Modal>
    </Content>
  );
};
