import { useState, useRef, useEffect, KeyboardEvent, ChangeEvent, ClipboardEvent, DragEvent } from 'react';
import { Send, Paperclip, X, Image, FileText, Loader2, Upload } from 'lucide-react';
import { clsx } from 'clsx';
import { FileAttachment } from '../stores/chatStore';

interface PendingFile {
  id: string;
  file: File;
  preview?: string;
  type: 'image' | 'document' | 'other';
}

interface InputAreaProps {
  onSend: (message: string, attachments?: FileAttachment[]) => void;
  disabled?: boolean;
  onFilesSelected?: (files: File[]) => void;
  pendingFiles?: PendingFile[];
  onRemoveFile?: (id: string) => void;
  isUploading?: boolean;
  uploadProgress?: Record<string, { progress: number; status: string }>;
}

// 允许上传的文件类型
const ALLOWED_TYPES = [
  'image/jpeg',
  'image/png',
  'image/gif',
  'image/webp',
  'image/svg+xml',
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'text/plain',
  'text/csv',
  'text/markdown',
];

const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

export function InputArea({
  onSend,
  disabled,
  onFilesSelected,
  pendingFiles = [],
  onRemoveFile,
  isUploading,
  uploadProgress = {},
}: InputAreaProps) {
  const [message, setMessage] = useState('');
  const [isDragging, setIsDragging] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dropZoneRef = useRef<HTMLDivElement>(null);

  // Auto-resize textarea
  useEffect(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      // 重置高度以获取正确的scrollHeight
      textarea.style.height = 'auto';
      // 设置新高度，最小44px（单行），最大200px
      const newHeight = Math.max(44, Math.min(textarea.scrollHeight, 200));
      textarea.style.height = `${newHeight}px`;
      // 只有当内容超过最大高度时才显示滚动条
      textarea.style.overflowY = textarea.scrollHeight > 200 ? 'auto' : 'hidden';
    }
  }, [message]);

  const handleSubmit = () => {
    const trimmedMessage = message.trim();
    if ((trimmedMessage || pendingFiles.length > 0) && !disabled && !isUploading) {
      onSend(trimmedMessage);
      setMessage('');
    }
  };

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

  const handleFileSelect = (e: ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    const validFiles: File[] = [];
    Array.from(files).forEach((file) => {
      if (!ALLOWED_TYPES.includes(file.type)) {
        console.warn(`不支持的文件类型: ${file.type}`);
        return;
      }
      if (file.size > MAX_FILE_SIZE) {
        console.warn(`文件过大: ${file.name}`);
        return;
      }
      validFiles.push(file);
    });

    if (validFiles.length > 0) {
      onFilesSelected?.(validFiles);
    }

    // 清空 input 以允许重复选择同一文件
    e.target.value = '';
  };

  const openFilePicker = () => {
    fileInputRef.current?.click();
  };

  // 处理文件验证和添加
  const processFiles = (files: File[]) => {
    const validFiles: File[] = [];
    files.forEach((file) => {
      if (!ALLOWED_TYPES.includes(file.type)) {
        console.warn(`不支持的文件类型: ${file.type}`);
        return;
      }
      if (file.size > MAX_FILE_SIZE) {
        console.warn(`文件过大: ${file.name}`);
        return;
      }
      validFiles.push(file);
    });

    if (validFiles.length > 0) {
      onFilesSelected?.(validFiles);
    }
  };

  // 处理粘贴事件
  const handlePaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
    const items = e.clipboardData?.items;
    if (!items) return;

    const files: File[] = [];
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.kind === 'file') {
        const file = item.getAsFile();
        if (file) {
          files.push(file);
        }
      }
    }

    if (files.length > 0) {
      e.preventDefault(); // 阻止默认粘贴行为
      processFiles(files);
    }
  };

  // 拖放事件处理
  const handleDragEnter = (e: DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!disabled && !isUploading) {
      setIsDragging(true);
    }
  };

  const handleDragLeave = (e: DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    // 只有当离开整个drop zone时才取消高亮
    if (dropZoneRef.current && !dropZoneRef.current.contains(e.relatedTarget as Node)) {
      setIsDragging(false);
    }
  };

  const handleDragOver = (e: DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = (e: DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    if (disabled || isUploading) return;

    const files = Array.from(e.dataTransfer?.files || []);
    if (files.length > 0) {
      processFiles(files);
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <div
      ref={dropZoneRef}
      className={clsx(
        'space-y-3 relative rounded-xl transition-all',
        isDragging && 'ring-2 ring-primary-500 ring-offset-2 bg-primary-50',
      )}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {/* 拖放提示层 */}
      {isDragging && (
        <div className="absolute inset-0 z-10 flex items-center justify-center bg-primary-50/90 rounded-xl border-2 border-dashed border-primary-400">
          <div className="flex flex-col items-center gap-2 text-primary-600">
            <Upload className="w-8 h-8" />
            <span className="font-medium">释放以添加文件</span>
          </div>
        </div>
      )}

      {/* 文件预览区域 */}
      {pendingFiles.length > 0 && (
        <div className="flex flex-wrap gap-2 px-1">
          {pendingFiles.map((pf) => (
            <div
              key={pf.id}
              className="relative group flex items-center gap-2 px-3 py-2 bg-secondary-50 rounded-lg border border-secondary-200"
            >
              {/* 文件图标或预览 */}
              {pf.type === 'image' && pf.preview ? (
                <img
                  src={pf.preview}
                  alt={pf.file.name}
                  className="w-10 h-10 object-cover rounded"
                />
              ) : pf.type === 'image' ? (
                <Image className="w-5 h-5 text-blue-500" />
              ) : (
                <FileText className="w-5 h-5 text-orange-500" />
              )}

              {/* 文件信息 */}
              <div className="flex flex-col">
                <span className="text-sm text-secondary-700 max-w-[150px] truncate">
                  {pf.file.name}
                </span>
                <span className="text-xs text-secondary-400">
                  {formatFileSize(pf.file.size)}
                </span>
              </div>

              {/* 上传进度 */}
              {uploadProgress[pf.id] && (
                <div className="ml-2">
                  {uploadProgress[pf.id].status === 'uploading' ? (
                    <div className="flex items-center gap-1">
                      <Loader2 className="w-4 h-4 animate-spin text-primary-500" />
                      <span className="text-xs text-primary-500">
                        {uploadProgress[pf.id].progress}%
                      </span>
                    </div>
                  ) : uploadProgress[pf.id].status === 'error' ? (
                    <span className="text-xs text-red-500">失败</span>
                  ) : null}
                </div>
              )}

              {/* 删除按钮 */}
              {!isUploading && (
                <button
                  onClick={() => onRemoveFile?.(pf.id)}
                  className="absolute -top-1 -right-1 p-0.5 bg-secondary-200 rounded-full opacity-0 group-hover:opacity-100 transition-opacity hover:bg-secondary-300"
                >
                  <X className="w-3 h-3 text-secondary-600" />
                </button>
              )}
            </div>
          ))}
        </div>
      )}

      {/* 输入区域 */}
      <div className="flex items-center gap-3">
        {/* 文件上传按钮 */}
        <button
          onClick={openFilePicker}
          disabled={disabled || isUploading}
          className={clsx(
            'p-2.5 rounded-xl transition-all flex-shrink-0',
            disabled || isUploading
              ? 'bg-secondary-100 text-secondary-400 cursor-not-allowed'
              : 'bg-secondary-100 text-secondary-600 hover:bg-secondary-200',
          )}
          title="添加图片或文件"
        >
          <Paperclip className="w-5 h-5" />
        </button>

        {/* 隐藏的文件输入 */}
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept={ALLOWED_TYPES.join(',')}
          onChange={handleFileSelect}
          className="hidden"
        />

        {/* 文本输入 */}
        <div className="flex-1 relative">
          <textarea
            ref={textareaRef}
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            onPaste={handlePaste}
            placeholder={
              pendingFiles.length > 0
                ? '添加说明文字（可选），或直接发送...'
                : '输入您的问题，可粘贴或拖放图片...'
            }
            disabled={disabled || isUploading}
            rows={1}
            className={clsx(
              'w-full resize-none overflow-hidden rounded-xl border border-secondary-200 bg-white px-4 py-3 pr-12',
              'text-secondary-900 placeholder:text-secondary-400',
              'focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent',
              'disabled:bg-secondary-50 disabled:cursor-not-allowed',
              'transition-all',
            )}
          />
          <button
            onClick={handleSubmit}
            disabled={disabled || isUploading || (!message.trim() && pendingFiles.length === 0)}
            className={clsx(
              'absolute right-2 top-1/2 -translate-y-1/2 p-2 rounded-lg transition-all',
              (message.trim() || pendingFiles.length > 0) && !disabled && !isUploading
                ? 'bg-primary-600 text-white hover:bg-primary-700'
                : 'bg-secondary-100 text-secondary-400 cursor-not-allowed',
            )}
          >
            {isUploading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Send className="w-4 h-4" />
            )}
          </button>
        </div>
      </div>

      {/* 提示文字 */}
      <p className="text-xs text-secondary-400 text-center">
        支持粘贴、拖放图片 (JPEG, PNG, GIF) 和文档 (PDF, Word, Excel)，最大 50MB
      </p>
    </div>
  );
}
