import { useState, useRef, useCallback, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Send, Mic, Image, Sparkles, MicOff } from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { SpeechRecognitionService } from "@/utils/speechRecognition";

interface ChatInputProps {
  onSendMessage: (message: string) => void;
  onImageUpload?: (files: FileList) => void;
  isLoading?: boolean;
  placeholder?: string;
  disabled?: boolean;
}

export function ChatInput({ 
  onSendMessage,
  onImageUpload,
  isLoading = false, 
  placeholder = "输入您的问题...",
  disabled = false 
}: ChatInputProps) {
  const [message, setMessage] = useState("");
  const [isRecording, setIsRecording] = useState(false);
  const [interimText, setInterimText] = useState("");
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const speechServiceRef = useRef<SpeechRecognitionService | null>(null);

  // Initialize speech recognition service
  useEffect(() => {
    if (!SpeechRecognitionService.isSupported()) {
      console.log('Speech recognition not supported in this browser');
      return;
    }

    speechServiceRef.current = new SpeechRecognitionService(
      // onResult - when we get final text
      (text) => {
        console.log('语音识别最终结果:', text);
        setMessage(prev => prev + (prev ? ' ' : '') + text);
        setInterimText("");
      },
      // onError
      (error) => {
        console.error('Speech recognition error:', error);
        toast.error(error.message);
        setIsRecording(false);
        setInterimText("");
      },
      // onEnd
      () => {
        console.log('语音识别会话结束');
        setIsRecording(false);
        setInterimText("");
      },
      // onInterim - real-time interim results
      (text) => {
        console.log('语音识别临时结果:', text);
        setInterimText(text);
      }
    );

    return () => {
      speechServiceRef.current?.stopListening();
    };
  }, []);

  const handleSend = useCallback(() => {
    if (message.trim() && !isLoading && !disabled) {
      onSendMessage(message.trim());
      setMessage("");
      
      // Reset textarea height
      if (textareaRef.current) {
        textareaRef.current.style.height = "auto";
      }
    }
  }, [message, onSendMessage, isLoading, disabled]);

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

  const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setMessage(e.target.value);
    
    // Auto-resize textarea
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 120)}px`;
    }
  };

  const toggleRecording = useCallback(async () => {
    if (!SpeechRecognitionService.isSupported()) {
      toast.error("您的浏览器不支持语音输入，请使用 Chrome 或 Edge 浏览器");
      return;
    }

    if (!speechServiceRef.current) {
      toast.error("语音服务初始化失败");
      return;
    }

    if (isRecording) {
      speechServiceRef.current.stopListening();
      setIsRecording(false);
      setInterimText("");
      toast.success("语音输入已停止");
    } else {
      // Request microphone permission first
      try {
        await navigator.mediaDevices.getUserMedia({ audio: true });
        speechServiceRef.current.startListening();
        setIsRecording(true);
        toast.info("开始语音输入，请说话...");
      } catch (error) {
        console.error('Microphone permission denied:', error);
        toast.error("无法访问麦克风，请允许麦克风权限");
      }
    }
  }, [isRecording]);

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

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      // 检查文件类型
      const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
      const invalidFiles = Array.from(files).filter(file => !validTypes.includes(file.type));
      
      if (invalidFiles.length > 0) {
        toast.error("只支持上传 JPG、PNG、GIF、WEBP 格式的图片");
        return;
      }

      // 检查文件大小（最大10MB）
      const maxSize = 10 * 1024 * 1024;
      const oversizedFiles = Array.from(files).filter(file => file.size > maxSize);
      
      if (oversizedFiles.length > 0) {
        toast.error("图片大小不能超过10MB");
        return;
      }

      onImageUpload?.(files);
      toast.success(`已选择 ${files.length} 张图片`);
    }
    
    // 重置文件输入
    e.target.value = '';
  };

  const MAX_LEN = 1000;
  const overLimit = message.length > MAX_LEN;
  const canSend = message.trim().length > 0 && !isLoading && !disabled && !overLimit;
  const isVoiceSupported = SpeechRecognitionService.isSupported();

  return (
    <div className="border-t border-border/50 bg-background px-2 py-1.5">
      <div className="mx-auto w-full">
        <div className="relative flex items-center gap-1 px-1">
          {/* Image Upload Button */}
          <Button
            variant="ghost"
            size="icon"
            onClick={handleImageUpload}
            className="h-7 w-7 text-muted-foreground hover:text-foreground rounded-lg shrink-0"
            disabled={disabled}
            title="上传图片"
          >
            <Image className="h-4 w-4" />
          </Button>

          {/* Hidden File Input */}
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            multiple
            onChange={handleFileChange}
            className="hidden"
          />

          {/* Text Input */}
          <div className="relative flex-1">
            <Textarea
              ref={textareaRef}
              value={message}
              onChange={handleTextareaChange}
              onKeyDown={handleKeyDown}
              placeholder={isRecording ? "正在聆听..." : placeholder}
              disabled={disabled}
              className={cn(
                "min-h-[44px] max-h-[160px] resize-none border-0 bg-transparent px-1 py-2.5",
                "placeholder:text-muted-foreground/70 text-foreground text-sm leading-relaxed",
                "focus-visible:ring-0 focus-visible:ring-offset-0",
                "transition-all duration-200 scrollbar-none"
              )}
              rows={1}
            />
            {/* Interim text indicator */}
            {interimText && (
              <div className="absolute bottom-full left-0 mb-2 px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-lg text-sm text-primary animate-pulse">
                {interimText}
              </div>
            )}
          </div>

          {/* Voice Recording Button */}
          {isVoiceSupported && (
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleRecording}
              disabled={disabled}
              title={isRecording ? "停止语音输入" : "开始语音输入"}
              className={cn(
                "h-7 w-7 rounded-lg shrink-0",
                isRecording
                  ? "bg-destructive/10 text-destructive hover:bg-destructive/20"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              {isRecording ? (
                <MicOff className="h-4 w-4 animate-pulse" />
              ) : (
                <Mic className="h-4 w-4" />
              )}
            </Button>
          )}

          {/* Send Button - only when input has content */}
          {canSend && (
            <Button
              onClick={handleSend}
              className="h-7 w-7 rounded-lg shrink-0 bg-primary hover:bg-primary-hover text-primary-foreground"
              size="icon"
            >
              <Send className="h-4 w-4" />
            </Button>
          )}
        </div>

        {/* Recording indicator */}
        {isRecording && (
          <div className="flex items-center justify-center mt-1.5">
            <div className="flex items-center gap-2 text-xs text-destructive">
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-destructive opacity-75"></span>
                <span className="relative inline-flex rounded-full h-2 w-2 bg-destructive"></span>
              </span>
              正在录音，请说话...
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
