'use client';

import { useState, useEffect, useRef } from 'react';
import api from '@/lib/api';
import { X, Send, User, Headset, Paperclip, Loader2, Clock, CheckCircle, AlertCircle, XCircle } from 'lucide-react';

// 定义工单类型（需导出给列表页使用）
export interface UserTicket {
  id: number;
  order_id: string;
  type: string;
  status: string;
  reason: string;
  admin_comment?: string;
  created_at: string;
}

interface Message {
  id: number;
  ticket_id: number;
  sender_type: 'user' | 'admin' | 'system';
  content: string;
  created_at: string;
}

interface UserTicketDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  ticket: UserTicket | null;
}

export default function UserTicketDetailModal({ isOpen, onClose, ticket }: UserTicketDetailModalProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loadingMsg, setLoadingMsg] = useState(false);
  const [replyContent, setReplyContent] = useState('');
  const [sending, setSending] = useState(false);
  
  // 滚动到底部的引用
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 1. 初始化加载消息
  useEffect(() => {
    if (isOpen && ticket) {
      fetchMessages();
      // 可选：设置轮询，每10秒获取新消息
      // const interval = setInterval(fetchMessages, 10000);
      // return () => clearInterval(interval);
    }
  }, [isOpen, ticket]);

  // 2. 滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const fetchMessages = async () => {
    if (!ticket) return;
    try {
      setLoadingMsg(true);
      // API: GET /api/vas/tickets/fetch_message?ticket_id=123&page=1&size=50
      const res = await api.get('/api/vas/tickets/fetch_message', {
        params: { 
          ticket_id: ticket.id,
          page: 1,
          size: 100 // 获取最近的100条
        }
      });
      
      const items = res.data.data?.items || [];
      // 确保按时间正序排列 (旧 -> 新)
      const sorted = items.sort((a: Message, b: Message) => 
        new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
      );
      setMessages(sorted);
    } catch (error) {
      console.error("Fetch messages failed", error);
    } finally {
      setLoadingMsg(false);
    }
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!replyContent.trim() || !ticket) return;

    setSending(true);
    try {
      // API: POST /api/vas/tickets/send_message?ticket_id=123
      await api.post(`/api/vas/tickets/send_message`, {
        content: replyContent,
        attachments: null // 暂不支持附件，留空
      }, {
        params: { ticket_id: ticket.id }
      });

      setReplyContent('');
      fetchMessages(); // 发送成功后刷新列表
    } catch (error) {
      console.error("Send message failed", error);
      alert("发送失败，请稍后重试");
    } finally {
      setSending(false);
    }
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 辅助函数：渲染状态
  const renderStatus = (status: string) => {
    const map: any = {
      pending: { color: 'text-yellow-600 bg-yellow-50', icon: Clock, text: '待处理' },
      info_required: { color: 'text-orange-600 bg-orange-50', icon: AlertCircle, text: '需补充资料' },
      resolved: { color: 'text-green-600 bg-green-50', icon: CheckCircle, text: '已解决' },
      rejected: { color: 'text-red-600 bg-red-50', icon: XCircle, text: '已拒绝' },
    };
    const conf = map[status] || { color: 'text-gray-600 bg-gray-50', icon: Clock, text: status };
    const Icon = conf.icon;
    
    return (
      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${conf.color}`}>
        <Icon size={12} /> {conf.text}
      </span>
    );
  };

  if (!isOpen || !ticket) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
      {/* 遮罩层 */}
      <div className="fixed inset-0 bg-black/50 backdrop-blur-sm transition-opacity" onClick={onClose} />

      {/* 弹窗主体 */}
      <div className="relative w-full max-w-2xl h-[80vh] bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col animate-in zoom-in duration-200">
        
        {/* 1. 顶部 Header */}
        <div className="px-6 py-4 border-b bg-gray-50 flex justify-between items-center flex-shrink-0">
          <div>
            <div className="flex items-center gap-3">
              <h3 className="font-bold text-gray-900 text-lg">
                工单 #{ticket.id}
              </h3>
              {renderStatus(ticket.status)}
            </div>
            <p className="text-xs text-gray-500 mt-1">
              关联订单: <span className="font-mono">{ticket.order_id}</span>
            </p>
          </div>
          <button onClick={onClose} className="p-2 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition">
            <X size={20} />
          </button>
        </div>

        {/* 2. 中间：消息列表 (Scrollable) */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 bg-slate-50 space-y-6">
          
          {/* 原始工单描述 (作为第一条展示) */}
          <div className="flex justify-center">
            <div className="bg-white border border-gray-200 text-gray-600 text-xs px-4 py-2 rounded-full shadow-sm">
              工单创建于 {new Date(ticket.created_at).toLocaleString()}
            </div>
          </div>
          <div className="flex justify-end">
            <div className="flex flex-row-reverse items-end gap-2 max-w-[85%]">
               <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                 <User size={14} className="text-blue-600" />
               </div>
               <div>
                  <div className="bg-blue-600 text-white px-4 py-3 rounded-2xl rounded-tr-none shadow-sm text-sm">
                    <p className="font-bold text-xs text-blue-100 mb-1 border-b border-blue-500 pb-1">工单描述</p>
                    {ticket.reason}
                  </div>
               </div>
            </div>
          </div>

          {/* 会话记录 */}
          {loadingMsg ? (
            <div className="flex justify-center py-8"><Loader2 className="animate-spin text-gray-400" /></div>
          ) : (
            messages.map((msg) => {
              const isMe = msg.sender_type === 'user';
              const isSystem = msg.sender_type === 'system';

              if (isSystem) {
                return (
                  <div key={msg.id} className="flex justify-center my-4">
                    <span className="text-[10px] text-gray-400 bg-gray-100 px-2 py-1 rounded">
                      系统消息: {msg.content} - {new Date(msg.created_at).toLocaleTimeString()}
                    </span>
                  </div>
                );
              }

              return (
                <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                  <div className={`flex items-end gap-2 max-w-[80%] ${isMe ? 'flex-row-reverse' : 'flex-row'}`}>
                    
                    {/* 头像 */}
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                      isMe ? 'bg-blue-100' : 'bg-purple-100'
                    }`}>
                      {isMe ? <User size={14} className="text-blue-600" /> : <Headset size={14} className="text-purple-600" />}
                    </div>

                    {/* 气泡 */}
                    <div className={`flex flex-col ${isMe ? 'items-end' : 'items-start'}`}>
                      <div className={`px-4 py-2 text-sm shadow-sm ${
                        isMe 
                          ? 'bg-blue-600 text-white rounded-2xl rounded-tr-none' 
                          : 'bg-white text-gray-800 border border-gray-100 rounded-2xl rounded-tl-none'
                      }`}>
                        {msg.content}
                      </div>
                      <span className="text-[10px] text-gray-400 mt-1 px-1">
                        {isMe ? '我' : '客服'} • {new Date(msg.created_at).toLocaleString([], {month:'numeric', day:'numeric', hour:'2-digit', minute:'2-digit'})}
                      </span>
                    </div>

                  </div>
                </div>
              );
            })
          )}
          
          <div ref={messagesEndRef} />
        </div>

        {/* 3. 底部：输入框 */}
        <div className="p-4 bg-white border-t border-gray-100 flex-shrink-0">
          <form onSubmit={handleSend} className="flex items-end gap-2">
            <button type="button" className="p-3 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-50 transition" title="上传附件(暂不可用)">
              <Paperclip size={20} />
            </button>
            <div className="flex-1 bg-gray-50 rounded-xl border border-gray-200 focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500 focus-within:bg-white transition-all">
              <textarea
                value={replyContent}
                onChange={(e) => setReplyContent(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    handleSend(e);
                  }
                }}
                placeholder="请输入回复内容..."
                rows={1}
                className="w-full bg-transparent border-0 focus:ring-0 p-3 text-sm resize-none max-h-32 min-h-[44px]"
                style={{ height: 'auto', overflowY: 'hidden' }} 
                // 简单的自动高度调整，实际项目中可使用 text-area-autosize 库
              />
            </div>
            <button 
              type="submit" 
              disabled={sending || !replyContent.trim()}
              className="p-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed shadow-md transition-all flex items-center justify-center"
            >
              {sending ? <Loader2 className="animate-spin w-5 h-5" /> : <Send size={20} />}
            </button>
          </form>
          <div className="text-center mt-2">
             <p className="text-[10px] text-gray-400">如需紧急处理，请发送邮件至 support@visafly.com</p>
          </div>
        </div>

      </div>
    </div>
  );
}