'use client';

import React, { useState, useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { IconButton } from '@/components/ui/button';
import { useAtomValue, useSetAtom } from 'jotai';
import { isSendGiftsDrawerOpenAtom, createDrawerOpenState } from '@/atoms/chat';
import { useNimChat, useNimMsgContext } from '@/context/NimChat/useNimChat';
import { selectedConversationIdAtom, isWaitingForReplyAtom, isCoinInsufficientAtom } from '@/atoms/im';
import { Textarea } from '@/components/ui/textarea';
import { useS3Upload } from '@/hooks/useS3Upload';
import { BizTypeEnum } from '@/services/common/types';
import ChatImagePreview from './ChatImagePreview';
import { useGetTextFromAsrVoice } from '@/hooks/useIm';
import { VoiceWaveAnimation } from '@/components/ui/voice-wave-animation';
import { CustomMessageType } from '@/types/im';
import ChatActionPlus from './ChatActionPlus';
import AiReplySuggestions from './AiReplySuggestions';
import { useAiReplySuggestions } from '@/hooks/useAiReplySuggestions';
import { useChatConfig } from '../../context/chatConfig/useChatConfig';
import { toast } from 'sonner';
import CoinInsufficientDialog from '@/components/features/coin-insufficient-dialog';
import { ChatPriceType, useGetWalletBalance, useUpdateWalletBalance } from '@/hooks/useWallet';
import { PriceType } from '@/services/wallet';
import { useSearchParams } from 'next/navigation';

interface ChatInputProps {
  onSendMessage?: (message: string, images?: File[]) => void;
  onSendVoice?: (audioBlob: Blob) => void;
  userAvatar?: string;
  className?: string;
  placeholder?: string;
}

interface ImageError {
  type: 'format' | 'size';
  message: string;
}

interface ImageInfo {
  url: string;
  width: number;
  height: number;
  file?: File;
}

const ChatInput: React.FC<ChatInputProps> = ({
  onSendMessage,
  onSendVoice,
  userAvatar,
  className,
  placeholder = "Chat",
}) => {
  const searchParams = useSearchParams();
  const [message, setMessage] = useState('');
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [imageInfo, setImageInfo] = useState<ImageInfo | null>(null);
  const [imageError, setImageError] = useState<ImageError | null>(null);
  const [isRecording, setIsRecording] = useState(false);
  const [isListening, setIsListening] = useState(false);
  const [isProcessingAudio, setIsProcessingAudio] = useState(false); // 音频处理状态（上传+ASR）
  const [isComposing, setIsComposing] = useState(false); // 中文输入法组合输入状态
  const fileInputRef = useRef<HTMLInputElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const isRecordingRef = useRef<boolean>(false);
  const isCancelledRef = useRef<boolean>(false);
  const recordingStartTimeRef = useRef<number>(0); // 录音开始时间
  const recordingTimerRef = useRef<NodeJS.Timeout | null>(null); // 60秒定时器
  const setDrawerState = useSetAtom(isSendGiftsDrawerOpenAtom);
  const setIsSendGiftsDrawerOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open));
  const { sendMessageActive, audioPlayer } = useNimMsgContext();
  const { nim } = useNimChat();
  const selectedConversationId = useAtomValue(selectedConversationIdAtom);
  // const isWaitingForReply = useAtomValue(isWaitingForReplyAtom);
  const isWaitingForReply = false;
  const { mutateAsync: getTextFromAsrVoice, isPending: isTextFromAsrVoicePending } = useGetTextFromAsrVoice();
  const { aiId, handleUserMessage } = useChatConfig();
  const { checkSufficientByType } = useUpdateWalletBalance();
  const setIsCoinInsufficient = useSetAtom(isCoinInsufficientAtom);

  // AI建议回复相关状态
  const {
    suggestions,
    currentPage,
    totalPages,
    isLoading: suggestionsLoading,
    isVisible: suggestionsVisible,
    showSuggestions,
    hideSuggestions,
    handlePageChange,
  } = useAiReplySuggestions({ 
    aiId: Number(aiId)
  });

  // S3上传钩子
  const { 
    uploading: imageUploading, 
    uploadFile, 
    cancelUpload,
    error: uploadError,
    progress: uploadProgress 
  } = useS3Upload({
    bizType: BizTypeEnum.IM,
    onSuccess: (url) => {
      console.log('Image uploaded successfully:', url);
    },
    onError: (error) => {
      console.error('Image upload failed:', error);
      setImageError({ type: 'size', message: 'Image upload failed, please try again' });
    }
  });

  // 自动调整 Textarea 高度的函数
  const adjustTextareaHeight = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      // 重置高度以获得准确的 scrollHeight
      textarea.style.height = 'auto';
      
      // 计算内容高度，但限制最大高度为视口的40%以防止过度扩展
      const maxHeight = Math.min(textarea.scrollHeight, window.innerHeight * 0.4);
      textarea.style.height = maxHeight + 'px';
    }
  };

  // 重置 Textarea 高度到初始状态
  const resetTextareaHeight = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = '32px'; // 设置为最小高度
    }
  };

  // 监听 message 变化，自动调整高度
  useEffect(() => {
    adjustTextareaHeight();
  }, [message]);

  // 从 URL 参数中获取 text 并填充到输入框
  useEffect(() => {
    const textFromUrl = searchParams.get('text');
    if (textFromUrl) {
      setMessage(textFromUrl);
      // 聚焦到输入框
      if (textareaRef.current) {
        textareaRef.current.focus();
      }
    } else {
      if (textareaRef.current) {
        textareaRef.current.focus();
      }
    }
  }, [searchParams]);

  // 音频上传的S3配置
  const { 
    uploadFile: uploadAudioFile
  } = useS3Upload({
    bizType: BizTypeEnum.SOUND_PATH,
  });
  
  // 获取图片尺寸信息
  const getImageDimensions = (file: File): Promise<{ width: number; height: number }> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      const url = URL.createObjectURL(file);
      
      img.onload = () => {
        URL.revokeObjectURL(url);
        resolve({
          width: img.naturalWidth,
          height: img.naturalHeight
        });
      };
      
      img.onerror = () => {
        URL.revokeObjectURL(url);
        reject(new Error('Failed to load image'));
      };
      
      img.src = url;
    });
  };
  
  // 验证图片格式和大小
  const validateImage = (file: File): ImageError | null => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    const maxSize = 10 * 1024 * 1024; // 10MB
    
    if (!allowedTypes.includes(file.type)) {
      return {
        type: 'format',
        message: 'Supported formats: JPG, JPEG, PNG'
      };
    }
    
    if (file.size > maxSize) {
      return {
        type: 'size',
        message: 'Image size must be less than 10MB'
      };
    }
    
    return null;
  };
  
  // 处理发送消息
  const handleSend = () => {
    if (isRecording) {
      // 手动停止录音时，也需要检查时长
      mediaRecorderRef.current?.stop();
      setIsRecording(false);
      isRecordingRef.current = false;
      return;
    }
    
    // 如果正在等待回复或正在上传图片，禁止发送新消息
    if (isWaitingForReply || imageUploading || isProcessingAudio) {
      return;
    }
    
    // 如果有图片，必须同时有文字内容
    if (imageInfo && !message.trim()) {
      return;
    }

    if (!checkSufficientByType(ChatPriceType.TEXT)) {
      setIsCoinInsufficient(true);
      return;
    }
    
    // 必须有文字内容或者同时有图片和文字
    if (message.trim() || (imageInfo && message.trim())) {
      let msg;
      
      if (imageInfo) {
        // 创建图文消息（自定义消息）
        const customContent = {
          type: CustomMessageType.IMAGE,
          url: `${imageInfo.url}`,
          width: imageInfo.width,
          height: imageInfo.height
        };
        
        msg = nim.V2NIMMessageCreator.createCustomMessage(
          message.trim(), // text字段
          JSON.stringify(customContent) // custom字段
        );
      } else {
        // 纯文本消息
        msg = nim.V2NIMMessageCreator.createTextMessage(message.trim());
      }
      
      sendMessageActive({
        msg,
        conversationId: selectedConversationId || '',
      });
      
      // 通知用户发送了消息，重置自动聊天定时器
      handleUserMessage();
      
      // 清空输入
      setMessage('');
      setSelectedImage(null);
      setImageInfo(null);
      setImageError(null);
      
      // 重置 Textarea 高度
      resetTextareaHeight();
    }
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey && !isComposing) {
      e.preventDefault();
      handleSend();
    }
  };

  // 处理中文输入法组合事件
  const handleCompositionStart = () => {
    setIsComposing(true);
  };

  const handleCompositionEnd = () => {
    setIsComposing(false);
  };

  // 处理图片选择
  const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const error = validateImage(file);
      if (error) {
        setImageError(error);
        setSelectedImage(null);
        setImageInfo(null);
      } else {
        setSelectedImage(file);
        setImageError(null);
        
        try {
          // 获取图片尺寸
          const dimensions = await getImageDimensions(file);
          
          // 开始上传
          const uploadedUrl = await uploadFile(file);
          console.log('uploadedUrl', uploadedUrl);
          
          if (uploadedUrl) {
            setImageInfo({
              url: `${uploadedUrl}`,
              width: dimensions.width,
              height: dimensions.height,
              file
            });
          }
        } catch (error) {
          console.error('处理图片失败:', error);
          setImageError({ type: 'size', message: 'Image processing failed, please try again' });
          setSelectedImage(null);
        }
      }
    }
    // 清空input的值，允许重新选择同一个文件
    e.target.value = '';
  };

  // 取消录音
  const handleCancelRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      // 标记为取消状态，防止在onstop中处理音频
      isCancelledRef.current = true;
      
      // 清除60秒定时器
      if (recordingTimerRef.current) {
        clearTimeout(recordingTimerRef.current);
        recordingTimerRef.current = null;
      }
      
      mediaRecorderRef.current.stop();
      // 获取所有音频轨道并停止
      if (mediaRecorderRef.current.stream) {
        mediaRecorderRef.current.stream.getTracks().forEach(track => track.stop());
      }
      setIsRecording(false);
      isRecordingRef.current = false;
      setIsListening(false);
      setIsProcessingAudio(false); // 重置音频处理状态
      audioChunksRef.current = [];
      recordingStartTimeRef.current = 0;
    }
  };

  // 处理语音录制
  const handleVoiceRecord = async () => {
    if (!checkSufficientByType(ChatPriceType.VOICE)) {
      setIsCoinInsufficient(true);
      return;
    }
    audioPlayer?.stop();
    
    if (!isRecording) {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        const mediaRecorder = new MediaRecorder(stream);
        mediaRecorderRef.current = mediaRecorder;
        audioChunksRef.current = [];

        // 添加音频上下文来检测音量
        const audioContext = new AudioContext();
        const analyser = audioContext.createAnalyser();
        const microphone = audioContext.createMediaStreamSource(stream);
        microphone.connect(analyser);
        
        analyser.smoothingTimeConstant = 0.8;
        analyser.fftSize = 1024;
        
        const bufferLength = analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);
        
        mediaRecorder.ondataavailable = (event) => {
          audioChunksRef.current.push(event.data);
        };

        mediaRecorder.onstop = async () => {
          const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/webm' });
          stream.getTracks().forEach(track => track.stop());
          audioContext.close();

          setIsListening(false);
          isRecordingRef.current = false;

          // 清除60秒定时器
          if (recordingTimerRef.current) {
            clearTimeout(recordingTimerRef.current);
            recordingTimerRef.current = null;
          }

          // 如果是取消录音，直接返回，不处理音频
          if (isCancelledRef.current) {
            isCancelledRef.current = false; // 重置取消状态
            recordingStartTimeRef.current = 0;
            return;
          }

          // 检查录音时长
          const recordingDuration = Date.now() - recordingStartTimeRef.current;
          if (recordingDuration < 1000) {
            // 录音时间少于1秒，显示提示
            toast.error("Voice too short");
            recordingStartTimeRef.current = 0;
            return;
          }

          // 开始音频处理（上传+ASR）
          setIsProcessingAudio(true);

          try {
            // 将 Blob 转换为 base64
            const base64Data = await new Promise<string>((resolve, reject) => {
              const reader = new FileReader();
              reader.onload = () => {
                const result = reader.result as string;
                console.log('result', result);
                // 移除 data:audio/mp3;base64, 前缀
                const base64 = result.split(',')[1];
                resolve(base64);
              };
              reader.onerror = reject;
              reader.readAsDataURL(audioBlob);
            });
            
            // 调用ASR接口获取文字
            const resp = await getTextFromAsrVoice({
              data: base64Data,
              aiId: Number(aiId),
            });
            const text = resp?.content;
            const trimmedText = text?.trim();
            if (trimmedText) {
              // 纯文本消息
              const msg = nim.V2NIMMessageCreator.createTextMessage(trimmedText);
              sendMessageActive({
                msg,
                conversationId: selectedConversationId || '',
              });
              
              // 通知用户发送了消息，重置自动聊天定时器
              handleUserMessage();
              
              // 重置 Textarea 高度（虽然语音消息不会改变输入框内容，但为了保持一致性）
              resetTextareaHeight();
            }
          } catch (error) {
            console.error('音频上传或转换失败:', error);
            // 可以在这里添加错误提示给用户
          } finally {
            // 完成音频处理
            setIsProcessingAudio(false);
            recordingStartTimeRef.current = 0;
          }
        };

        mediaRecorder.start();
        setIsRecording(true);
        isRecordingRef.current = true;
        isCancelledRef.current = false; // 重置取消状态
        
        // 记录录音开始时间
        recordingStartTimeRef.current = Date.now();
        
        // 设置60秒定时器，自动停止录音
        recordingTimerRef.current = setTimeout(() => {
          if (mediaRecorderRef.current && isRecordingRef.current) {
            mediaRecorderRef.current.stop();
            setIsRecording(false);
            isRecordingRef.current = false;
          }
        }, 60000); // 60秒

        // 检测音量的函数
        const checkVolume = () => {
          if (isRecordingRef.current) {
            analyser.getByteFrequencyData(dataArray);
            const volume = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
            setIsListening(volume > 10); // 设置音量阈值
            requestAnimationFrame(checkVolume);
          }
        };
        
        // 确保在设置录音状态后再开始检测音量
        checkVolume();
      } catch (error) {
        console.error('Error accessing microphone:', error);
      }
    } else {
      // 发送动作改在发送消息的按钮上
      return;

      // 手动停止录音时，也需要检查时长
      mediaRecorderRef.current?.stop();
      setIsRecording(false);
      isRecordingRef.current = false;
    }
  };

  // 移除选中的图片
  const removeImage = () => {
    // 如果正在上传，取消上传
    if (imageUploading) {
      cancelUpload();
    }
    
    setSelectedImage(null);
    setImageInfo(null);
    setImageError(null);
  };

  // 处理AI建议编辑（放到输入框）
  const handleSuggestionEdit = (suggestion: any) => {
    setMessage(suggestion.text);
    hideSuggestions();
  };

  // 处理AI建议发送（直接发送消息）
  const handleSuggestionSend = (suggestion: any) => {
    // 直接发送建议内容作为消息
    if (suggestion.text.trim()) {
      const msg = nim.V2NIMMessageCreator.createTextMessage(suggestion.text.trim());
      
      sendMessageActive({
        msg,
        conversationId: selectedConversationId || '',
      });
      
      // 通知用户发送了消息，重置自动聊天定时器
      handleUserMessage();
      
      hideSuggestions();
      // 重置 Textarea 高度
      resetTextareaHeight();
    }
  };

  return (
    <div className={cn("relative flex flex-col w-full", className)}>
      {/* AI建议回复面板 */}
      {suggestionsVisible && (
        <div className="mb-4 rounded-xl px-16 pt-6">
          <AiReplySuggestions
            suggestions={suggestions}
            currentPage={currentPage}
            totalPages={totalPages}
            isLoading={suggestionsLoading}
            onSuggestionEdit={handleSuggestionEdit}
            onSuggestionSend={handleSuggestionSend}
            onPageChange={handlePageChange}
            onClose={hideSuggestions}
          />
        </div>
      )}

      {/* 错误提示 */}
      {imageError && (
        <div className="mx-3 mb-2 px-3 py-2 bg-red-500/20 border border-red-500/30 rounded-lg">
          <p className="text-red-400 text-sm">{imageError.message}</p>
        </div>
      )}

      {/* 输入区域 */}
      <div className="flex items-end gap-3">
        <IconButton onClick={() => setIsSendGiftsDrawerOpen(true)}>
          <i className="iconfont icon-gift-border" />
        </IconButton>

        {/* 输入框容器 */}
        <div className="flex-1 relative">
          {isRecording ? (
            /* 录音状态界面 - 按照Figma设计稿样式 */
            <div className="backdrop-blur backdrop-filter bg-[rgba(255,255,255,0.15)] box-border flex gap-4 items-center justify-start overflow-clip p-2 rounded-3xl min-h-[48px]">
              {/* 左侧语音按钮 */}
              <IconButton
                variant="ghost"
                size="small"
                onClick={handleVoiceRecord}
                className="flex-shrink-0 bg-transparent"
              >
                <i className="iconfont icon-voice_msg text-white" />
              </IconButton>

              {/* 中间声波纹 */}
              <div className="flex-1 flex items-center justify-center px-4">
                <VoiceWaveAnimation 
                  animated={isListening} 
                  barCount={40} 
                  className="w-full max-w-[316px]"
                />
              </div>

              {/* 右侧删除按钮 */}
              <IconButton
                variant="tertiary"
                size="small"
                onClick={handleCancelRecording}
              >
                <i className="iconfont icon-close" />
              </IconButton>
            </div>
          ) : (
            /* 正常输入状态界面 */
            <div className={cn(
              "relative flex items-end min-h-[48px] bg-surface-element-light-press backdrop-blur-sm rounded-xl p-2",
              isWaitingForReply && "opacity-60",
            )}>
              {/* 语音录制按钮 */}
              <IconButton
                variant="ghost"
                size="small"
                onClick={handleVoiceRecord}
                className="flex-shrink-0"
              >
                <i className="iconfont icon-voice_msg" />
              </IconButton>

              {/* 文本输入 */}
              <div className={cn(
                "w-full",
              )}>
                <ChatImagePreview
                  selectedImage={selectedImage}
                  imageUploading={imageUploading}
                  removeImage={removeImage}
                />
                {/* 输入框 */}
                <Textarea
                  ref={textareaRef}
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  onKeyDown={handleKeyPress}
                  onCompositionStart={handleCompositionStart}
                  onCompositionEnd={handleCompositionEnd}
                  placeholder={placeholder}
                  // placeholder={isWaitingForReply ? "等待AI回复中..." : placeholder}
                  // disabled={isWaitingForReply}
                  className="flex-1 bg-transparent border-none outline-none resize-none text-txt-primary-normal placeholder:text-txt-tertiary-normal txt-body-l min-h-[24px] max-h-none py-1 overflow-hidden break-all"
                  rows={1}
                  maxLength={500}
                  style={{
                    height: 'auto',
                    minHeight: '32px',
                    wordBreak: 'break-word',
                    whiteSpace: 'pre-wrap',
                  }}
                  onInput={adjustTextareaHeight}
                />
              </div>

              {/* 右侧按钮组 */}
              <div className="flex items-center gap-2 ml-2">
                {/* 提示词提示按钮 */}
                <IconButton
                  variant="ghost"
                  size="small"
                  onClick={() => {
                    if (!checkSufficientByType(ChatPriceType.TEXT)) {
                      setIsCoinInsufficient(true);
                      return;
                    }
                    if (suggestionsVisible) {
                      hideSuggestions();
                    } else {
                      showSuggestions();
                    }
                  }}
                  className={cn(
                    suggestionsVisible && "bg-surface-element-hover"
                  )}
                >
                  <i className="iconfont icon-prompt" />
                </IconButton>
                <ChatActionPlus onUploadImage={() => fileInputRef.current?.click()} />
              </div>
            </div>
          )}
        </div>

        {(
          /* 发送按钮 */
          <IconButton
            variant="default"
            size="large"
            loading={isProcessingAudio}
            onClick={() => handleSend()}
            disabled={!isRecording && ((!message.trim() && !imageInfo) || (imageInfo && !message.trim()) || isWaitingForReply || imageUploading)}
            className="flex-shrink-0"
          >
            <i className="iconfont icon-icon-send" />
          </IconButton>
        )}

        {/* 隐藏的文件输入 */}
        <input
          ref={fileInputRef}
          type="file"
          accept="image/jpeg,image/jpg,image/png"
          onChange={handleImageSelect}
          className="hidden"
        />
      </div>
    </div>
  );
};

export default ChatInput;
