'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Send, 
  Image, 
  Paperclip, 
  Loader2, 
  User,
  Headphones,
  FileText,
  Download,
  X,
  ZoomIn
} from 'lucide-react';

interface Message {
  id: string;
  order_id: string;
  sender_type: 'customer' | 'admin';
  sender_id: string;
  sender_name: string | null;
  message_type: 'text' | 'image' | 'file';
  content: string | null;
  file_url: string | null;
  file_name: string | null;
  file_size: string | null;
  created_at: string;
}

interface ChatBoxProps {
  orderId: string;
  onMessageSent?: () => void;
}

export default function ChatBox({ orderId, onMessageSent }: ChatBoxProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSending, setIsSending] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [textMessage, setTextMessage] = useState('');
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);

  // 获取消息列表
  const fetchMessages = async () => {
    try {
      const response = await fetch(`/api/orders/${orderId}/messages`);
      const data = await response.json();
      if (response.ok) {
        setMessages(data.messages || []);
      }
    } catch (error) {
      console.error('Error fetching messages:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchMessages();
    // 每10秒刷新一次消息
    const interval = setInterval(fetchMessages, 10000);
    return () => clearInterval(interval);
  }, [orderId]);

  // 滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 发送文字消息
  const handleSendText = async () => {
    if (!textMessage.trim() || isSending) return;

    setIsSending(true);
    try {
      const response = await fetch(`/api/orders/${orderId}/messages/send`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messageType: 'text',
          content: textMessage.trim(),
        }),
      });

      const data = await response.json();
      if (response.ok) {
        setMessages([...messages, data.message]);
        setTextMessage('');
        onMessageSent?.();
      } else {
        alert(data.error || '发送失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('发送失败，请重试');
    } finally {
      setIsSending(false);
    }
  };

  // 上传文件
  const handleUpload = async (file: File, type: 'image' | 'file') => {
    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', type);

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();
      if (response.ok) {
        // 发送消息
        const msgResponse = await fetch(`/api/orders/${orderId}/messages/send`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            messageType: type,
            content: type === 'image' ? '发送了一张图片' : `发送了一个文件: ${data.fileName}`,
            fileUrl: data.fileUrl,
            fileName: data.fileName,
            fileSize: String(data.fileSize),
          }),
        });

        const msgData = await msgResponse.json();
        if (msgResponse.ok) {
          setMessages([...messages, msgData.message]);
          onMessageSent?.();
        } else {
          alert(msgData.error || '发送失败');
        }
      } else {
        alert(data.error || '上传失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('上传失败，请重试');
    } finally {
      setIsUploading(false);
    }
  };

  // 处理图片选择
  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleUpload(file, 'image');
    }
    e.target.value = '';
  };

  // 处理文件选择
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleUpload(file, 'file');
    }
    e.target.value = '';
  };

  // 格式化时间
  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 格式化文件大小
  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';
  };

  // 下载文件
  const handleDownload = async (url: string, fileName: string) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const blobUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = fileName;
      link.click();
      window.URL.revokeObjectURL(blobUrl);
    } catch (error) {
      console.error('Download error:', error);
      alert('下载失败');
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-10">
        <Loader2 className="w-6 h-6 text-blue-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="flex flex-col bg-white rounded-xl border border-gray-200 overflow-hidden">
      {/* 聊天头部 */}
      <div className="flex items-center gap-3 px-4 py-3 bg-gray-50 border-b border-gray-200">
        <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
          <Headphones className="w-4 h-4 text-blue-600" />
        </div>
        <div>
          <h4 className="text-sm font-medium text-gray-900">在线客服</h4>
          <p className="text-xs text-gray-500">有关订单问题可在此咨询</p>
        </div>
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-[300px] max-h-[400px]">
        {messages.length === 0 ? (
          <div className="text-center py-10">
            <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
              <Send className="w-6 h-6 text-gray-300" />
            </div>
            <p className="text-gray-400 text-sm">暂无消息，开始聊天吧</p>
          </div>
        ) : (
          messages.map((message) => {
            const isCustomer = message.sender_type === 'customer';
            
            return (
              <div
                key={message.id}
                className={`flex gap-2 ${isCustomer ? 'justify-end' : 'justify-start'}`}
              >
                {/* 头像 */}
                {!isCustomer && (
                  <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <Headphones className="w-4 h-4 text-blue-600" />
                  </div>
                )}
                
                {/* 消息内容 */}
                <div className={`max-w-[70%] ${isCustomer ? 'items-end' : 'items-start'}`}>
                  <div className={`flex items-center gap-2 mb-1 ${isCustomer ? 'justify-end' : 'justify-start'}`}>
                    <span className="text-xs text-gray-400">
                      {message.sender_name || (isCustomer ? '我' : '客服')}
                    </span>
                    <span className="text-xs text-gray-300">
                      {formatTime(message.created_at)}
                    </span>
                  </div>
                  
                  {/* 文字消息 */}
                  {message.message_type === 'text' && (
                    <div className={`px-4 py-2.5 rounded-2xl text-sm whitespace-pre-wrap ${
                      isCustomer 
                        ? 'bg-blue-600 text-white rounded-br-md' 
                        : 'bg-gray-100 text-gray-800 rounded-bl-md'
                    }`}>
                      {message.content}
                    </div>
                  )}
                  
                  {/* 图片消息 */}
                  {message.message_type === 'image' && message.file_url && (
                    <div className="relative group">
                      <img
                        src={message.file_url}
                        alt="图片"
                        className="max-w-full rounded-lg cursor-pointer hover:opacity-90"
                        style={{ maxHeight: '200px' }}
                        onClick={() => setPreviewImage(message.file_url)}
                      />
                      <button
                        onClick={() => setPreviewImage(message.file_url)}
                        className="absolute top-2 right-2 p-1.5 bg-black/50 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        <ZoomIn className="w-4 h-4 text-white" />
                      </button>
                    </div>
                  )}
                  
                  {/* 文件消息 */}
                  {message.message_type === 'file' && message.file_url && (
                    <div className={`flex items-center gap-3 px-4 py-3 rounded-xl border ${
                      isCustomer 
                        ? 'bg-blue-50 border-blue-100' 
                        : 'bg-gray-50 border-gray-200'
                    }`}>
                      <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center border border-gray-200">
                        <FileText className="w-5 h-5 text-gray-400" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-700 truncate">
                          {message.file_name}
                        </p>
                        {message.file_size && (
                          <p className="text-xs text-gray-400">
                            {formatFileSize(parseInt(message.file_size))}
                          </p>
                        )}
                      </div>
                      <button
                        onClick={() => handleDownload(message.file_url!, message.file_name || 'file')}
                        className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      >
                        <Download className="w-5 h-5" />
                      </button>
                    </div>
                  )}
                </div>
                
                {/* 用户头像 */}
                {isCustomer && (
                  <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <User className="w-4 h-4 text-gray-500" />
                  </div>
                )}
              </div>
            );
          })
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="border-t border-gray-200 p-3">
        {/* 上传进度 */}
        {isUploading && (
          <div className="flex items-center gap-2 px-3 py-2 mb-2 bg-blue-50 text-blue-600 text-sm rounded-lg">
            <Loader2 className="w-4 h-4 animate-spin" />
            <span>正在上传...</span>
          </div>
        )}
        
        <div className="flex items-end gap-2">
          {/* 工具栏 */}
          <div className="flex items-center gap-1">
            <input
              ref={imageInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleImageSelect}
            />
            <button
              onClick={() => imageInputRef.current?.click()}
              disabled={isUploading || isSending}
              className="p-2.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50"
              title="发送图片"
            >
              <Image className="w-5 h-5" />
            </button>
            
            <input
              ref={fileInputRef}
              type="file"
              className="hidden"
              onChange={handleFileSelect}
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploading || isSending}
              className="p-2.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50"
              title="发送文件"
            >
              <Paperclip className="w-5 h-5" />
            </button>
          </div>
          
          {/* 输入框 */}
          <div className="flex-1 relative">
            <textarea
              value={textMessage}
              onChange={(e) => setTextMessage(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  handleSendText();
                }
              }}
              placeholder="输入消息，按回车发送..."
              rows={1}
              className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
              disabled={isUploading || isSending}
            />
          </div>
          
          {/* 发送按钮 */}
          <button
            onClick={handleSendText}
            disabled={!textMessage.trim() || isSending || isUploading}
            className="p-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isSending ? (
              <Loader2 className="w-5 h-5 animate-spin" />
            ) : (
              <Send className="w-5 h-5" />
            )}
          </button>
        </div>
      </div>

      {/* 图片预览 */}
      {previewImage && (
        <div 
          className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
          onClick={() => setPreviewImage(null)}
        >
          <button
            onClick={() => setPreviewImage(null)}
            className="absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full transition-colors"
          >
            <X className="w-6 h-6 text-white" />
          </button>
          <img
            src={previewImage}
            alt="预览"
            className="max-w-full max-h-full object-contain"
            onClick={(e) => e.stopPropagation()}
          />
        </div>
      )}
    </div>
  );
}
