'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { 
  AlertTriangle, Clock, Search, Send, FileImage, 
  MessageSquare, CheckCircle2, AlertCircle, Loader2, Image as ImageIcon, ShieldAlert
} from 'lucide-react';

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string; icon: any }> = {
  PENDING: { label: 'Chờ phân hồi', color: 'text-red-400', bg: 'bg-red-500/10', icon: AlertTriangle },
  WAITING_BUYER: { label: 'Chờ người mua', color: 'text-yellow-400', bg: 'bg-yellow-500/10', icon: Clock },
  REVIEWING: { label: 'Đang xem xét', color: 'text-purple-400', bg: 'bg-purple-500/10', icon: Search },
  RESOLVED: { label: 'Đã xử lý', color: 'text-green-400', bg: 'bg-green-500/10', icon: CheckCircle2 },
};

export default function SellerComplaintsPage() {
  const [stats, setStats] = useState({ TOTAL: 0, WAITING_SELLER: 0, WAITING_BUYER: 0, REVIEWING: 0, RESOLVED: 0 });
  const [disputes, setDisputes] = useState<any[]>([]);
  const [selectedDisputeId, setSelectedDisputeId] = useState<string | null>(null);
  const [disputeDetail, setDisputeDetail] = useState<any | null>(null);
  
  const [filterStatus, setFilterStatus] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  
  const [replyContent, setReplyContent] = useState('');
  const [loading, setLoading] = useState(true);
  const [replying, setReplying] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [evidenceUrls, setEvidenceUrls] = useState<string[]>([]);
  
  const user = useAuthStore(s => s.user);

  useEffect(() => {
    fetchStats();
    fetchDisputes();
  }, [filterStatus]);

  const fetchStats = async () => {
    try {
      const res = await api.get('/disputes/seller/stats');
      setStats(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const fetchDisputes = async () => {
    try {
      setLoading(true);
      const res = await api.get(`/disputes/seller?status=${filterStatus}&q=${searchQuery}`);
      setDisputes(res.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    fetchDisputes();
  };

  const selectDispute = async (id: string) => {
    setSelectedDisputeId(id);
    setDisputeDetail(null);
    try {
      const res = await api.get(`/disputes/${id}`);
      setDisputeDetail(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || e.target.files.length === 0) return;
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      setUploading(true);
      const res = await api.post('/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      setEvidenceUrls(prev => [...prev, res.data.url]);
    } catch (err) {
      console.error('Lỗi upload', err);
    } finally {
      setUploading(false);
    }
  };

  const removeEvidence = (index: number) => {
    setEvidenceUrls(prev => prev.filter((_, i) => i !== index));
  };

  const submitReply = async () => {
    if (!replyContent.trim() && evidenceUrls.length === 0) return;
    if (!selectedDisputeId) return;

    try {
      setReplying(true);
      await api.post(`/disputes/${selectedDisputeId}/reply`, {
        content: replyContent,
        evidenceUrls
      });
      setReplyContent('');
      setEvidenceUrls([]);
      // Tải lại chi tiết
      selectDispute(selectedDisputeId);
      fetchStats();
      fetchDisputes();
    } catch (err) {
      console.error('Lỗi phản hồi', err);
    } finally {
      setReplying(false);
    }
  };

  return (
    <div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden">
      {/* Header Info */}
      <div className="p-6 pb-0 flex-shrink-0">
        <div>
          <h1 className="text-2xl font-bold text-white">Khiếu nại</h1>
          <p className="text-sm text-gray-500 mt-1">Phản hồi khiếu nại của người mua và gửi bằng chứng.</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mt-6">
          <div className="bg-[#15161a] border border-white/5 rounded-xl p-4">
            <div className="text-gray-400 text-xs mb-2">Tổng khiếu nại</div>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-blue-500/10 flex items-center justify-center">
                <MessageSquare className="w-4 h-4 text-blue-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{stats.TOTAL}</div>
              </div>
            </div>
          </div>
          
          <div className="bg-[#15161a] border border-red-500/20 rounded-xl p-4 shadow-[0_0_15px_rgba(239,68,68,0.1)]">
            <div className="text-red-400 text-xs mb-2 font-medium">Cần phản hồi</div>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-red-500/10 flex items-center justify-center">
                <AlertTriangle className="w-4 h-4 text-red-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-red-400">{stats.WAITING_SELLER}</div>
              </div>
            </div>
          </div>

          <div className="bg-[#15161a] border border-white/5 rounded-xl p-4">
            <div className="text-yellow-400 text-xs mb-2">Chờ người mua</div>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-yellow-500/10 flex items-center justify-center">
                <Clock className="w-4 h-4 text-yellow-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-yellow-400">{stats.WAITING_BUYER}</div>
              </div>
            </div>
          </div>

          <div className="bg-[#15161a] border border-white/5 rounded-xl p-4">
            <div className="text-purple-400 text-xs mb-2">Đang xem xét</div>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-purple-500/10 flex items-center justify-center">
                <Search className="w-4 h-4 text-purple-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-purple-400">{stats.REVIEWING}</div>
              </div>
            </div>
          </div>

          <div className="bg-[#15161a] border border-white/5 rounded-xl p-4">
            <div className="text-green-400 text-xs mb-2">Đã xử lý</div>
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-lg bg-green-500/10 flex items-center justify-center">
                <CheckCircle2 className="w-4 h-4 text-green-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-green-400">{stats.RESOLVED}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-3 mt-6 mb-4">
          <div className="flex-1 max-w-md relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input 
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Tìm mã đơn hàng, lý do..."
              className="w-full pl-10 pr-4 py-2 bg-[#15161a] border border-white/10 rounded-lg text-sm text-white focus:outline-none focus:border-primary"
            />
          </div>
          <select 
            value={filterStatus}
            onChange={e => setFilterStatus(e.target.value)}
            className="bg-[#15161a] border border-white/10 rounded-lg px-4 py-2 text-sm text-white focus:outline-none focus:border-primary"
          >
            <option value="all">Tất cả trạng thái</option>
            <option value="PENDING">Cần phản hồi</option>
            <option value="WAITING_BUYER">Chờ người mua</option>
            <option value="REVIEWING">Đang xem xét</option>
            <option value="RESOLVED">Đã xử lý</option>
          </select>
          <button 
            onClick={handleSearch}
            className="px-6 py-2 bg-primary text-primary-foreground font-medium rounded-lg text-sm hover:bg-primary/90 transition-colors"
          >
            Áp dụng
          </button>
        </div>
      </div>

      {/* Main Content Split */}
      <div className="flex-1 flex overflow-hidden border-t border-white/5">
        
        {/* Left Pane - List */}
        <div className="w-full lg:w-[60%] flex flex-col border-r border-white/5 bg-[#0a0a0a]">
          <div className="flex-1 overflow-auto p-4">
            <div className="bg-[#15161a] border border-white/5 rounded-xl overflow-hidden">
              <table className="w-full text-left text-sm text-gray-400">
                <thead className="text-xs uppercase bg-white/5 text-gray-500 border-b border-white/5">
                  <tr>
                    <th className="px-4 py-3">Mã đơn</th>
                    <th className="px-4 py-3">Trạng thái</th>
                    <th className="px-4 py-3">Lý do</th>
                    <th className="px-4 py-3">Giá trị</th>
                    <th className="px-4 py-3">Cập nhật</th>
                  </tr>
                </thead>
                <tbody>
                  {loading ? (
                    <tr>
                      <td colSpan={5} className="text-center py-10">
                        <Loader2 className="w-6 h-6 animate-spin mx-auto text-primary" />
                      </td>
                    </tr>
                  ) : disputes.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="text-center py-10 text-gray-500">
                        Chưa có khiếu nại phù hợp
                      </td>
                    </tr>
                  ) : (
                    disputes.map(d => {
                      const st = STATUS_CONFIG[d.status] || STATUS_CONFIG.PENDING;
                      const isSelected = selectedDisputeId === d.id;
                      return (
                        <tr 
                          key={d.id} 
                          onClick={() => selectDispute(d.id)}
                          className={`border-b border-white/5 cursor-pointer transition-colors ${
                            isSelected ? 'bg-primary/10 border-l-2 border-l-primary' : 'hover:bg-white/[0.02]'
                          }`}
                        >
                          <td className="px-4 py-4 font-mono text-white text-xs">{d.orderId.substring(0, 8)}...</td>
                          <td className="px-4 py-4">
                            <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[10px] font-bold ${st.bg} ${st.color}`}>
                              <st.icon className="w-3 h-3" /> {st.label}
                            </span>
                          </td>
                          <td className="px-4 py-4 max-w-[150px] truncate text-gray-300">{d.reason}</td>
                          <td className="px-4 py-4 font-bold text-red-400">
                            {Number(d.order.totalAmount).toLocaleString('vi-VN')}₫
                          </td>
                          <td className="px-4 py-4 text-xs">
                            {new Date(d.updatedAt).toLocaleDateString('vi-VN')}
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Right Pane - Detail */}
        <div className="hidden lg:flex w-[40%] flex-col bg-[#0f0f0f]">
          {!selectedDisputeId ? (
            <div className="flex-1 flex flex-col items-center justify-center p-8 text-center">
              <div className="w-16 h-16 rounded-full bg-white/5 flex items-center justify-center mb-4">
                <MessageSquare className="w-8 h-8 text-gray-600" />
              </div>
              <h3 className="text-lg font-medium text-white mb-2">Chọn một khiếu nại</h3>
              <p className="text-sm text-gray-500">Chọn một khiếu nại trong bảng bên trái để xem chi tiết và phản hồi.</p>
            </div>
          ) : !disputeDetail ? (
            <div className="flex-1 flex items-center justify-center">
              <Loader2 className="w-8 h-8 animate-spin text-primary" />
            </div>
          ) : (
            <>
              {/* Detail Header */}
              <div className="p-4 border-b border-white/5 bg-[#15161a]">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-bold text-white text-lg">Chi tiết khiếu nại</h3>
                  {(() => {
                    const st = STATUS_CONFIG[disputeDetail.status] || STATUS_CONFIG.PENDING;
                    return (
                      <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-bold ${st.bg} ${st.color}`}>
                        {st.label}
                      </span>
                    );
                  })()}
                </div>
                <div className="grid grid-cols-2 gap-4 text-sm mt-4">
                  <div>
                    <span className="text-gray-500 text-xs block">Mã đơn hàng</span>
                    <span className="text-white font-mono text-xs">{disputeDetail.orderId}</span>
                  </div>
                  <div>
                    <span className="text-gray-500 text-xs block">Người mua</span>
                    <span className="text-white">{disputeDetail.buyer.name || disputeDetail.buyer.email}</span>
                  </div>
                  <div className="col-span-2">
                    <span className="text-gray-500 text-xs block">Lý do khiếu nại ban đầu</span>
                    <span className="text-gray-300 block bg-white/5 p-2 rounded mt-1 border border-white/10">{disputeDetail.reason}</span>
                  </div>
                </div>
              </div>

              {/* Chat History */}
              <div className="flex-1 overflow-auto p-4 space-y-4">
                {disputeDetail.messages.map((msg: any) => {
                  const isMe = msg.senderId === user?.id;
                  const isAdmin = msg.sender?.role?.name === 'ADMIN' || msg.sender?.role?.name === 'SUPER_ADMIN';
                  const isVerdict = msg.content?.includes('PHÁN QUYẾT CHÍNH THỨC');

                  // Tin nhắn phán quyết hiển thị riêng biệt, nổi bật
                  if (isVerdict) {
                    return (
                      <div key={msg.id} className="my-4">
                        <div className="border border-yellow-500/40 bg-yellow-500/5 rounded-2xl p-4">
                          <div className="flex items-center gap-2 mb-3 pb-3 border-b border-yellow-500/20">
                            <ShieldAlert className="w-5 h-5 text-yellow-400 flex-shrink-0" />
                            <span className="text-yellow-400 font-black text-sm uppercase tracking-wider">Thông báo chính thức từ Ban Quản trị</span>
                            <span className="ml-auto text-[10px] text-gray-500">{new Date(msg.createdAt).toLocaleString('vi-VN')}</span>
                          </div>
                          <pre className="text-gray-200 text-xs leading-relaxed whitespace-pre-wrap font-sans">{msg.content}</pre>
                        </div>
                      </div>
                    );
                  }
                  
                  return (
                    <div key={msg.id} className={`flex flex-col ${isMe ? 'items-end' : 'items-start'}`}>
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-xs font-medium text-gray-400">
                          {isAdmin ? 'Quản trị viên' : isMe ? 'Bạn' : 'Người mua'}
                        </span>
                        <span className="text-[10px] text-gray-600">
                          {new Date(msg.createdAt).toLocaleString('vi-VN')}
                        </span>
                      </div>
                      
                      <div className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm ${
                        isAdmin ? 'bg-purple-600 text-white' 
                        : isMe ? 'bg-primary text-primary-foreground' 
                        : 'bg-[#1e1f23] text-white border border-white/10'
                      }`}>
                        {msg.content}
                      </div>

                      {/* Evidence Images */}
                      {msg.evidenceUrls && msg.evidenceUrls.length > 0 && (
                        <div className="flex gap-2 mt-2 flex-wrap justify-end">
                          {msg.evidenceUrls.map((url: string, i: number) => (
                            <a key={i} href={url} target="_blank" rel="noreferrer" className="block w-20 h-20 rounded-lg overflow-hidden border border-white/10 hover:opacity-80 transition-opacity">
                              <img src={url} alt="Evidence" className="w-full h-full object-cover" />
                            </a>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Reply Box */}
              {disputeDetail.status !== 'RESOLVED' && (
                <div className="p-4 bg-[#15161a] border-t border-white/5">
                  
                  {/* Attached Images Preview */}
                  {evidenceUrls.length > 0 && (
                    <div className="flex gap-2 mb-3 overflow-x-auto pb-2">
                      {evidenceUrls.map((url, i) => (
                        <div key={i} className="relative w-16 h-16 shrink-0 rounded-md overflow-hidden group">
                          <img src={url} className="w-full h-full object-cover" />
                          <button onClick={() => removeEvidence(i)} className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center text-white text-xs font-bold transition-opacity">
                            XÓA
                          </button>
                        </div>
                      ))}
                    </div>
                  )}

                  <div className="flex gap-2">
                    <div className="relative">
                      <input 
                        type="file" 
                        accept="image/*" 
                        className="hidden" 
                        id="evidence-upload"
                        onChange={handleFileUpload}
                        disabled={uploading || replying}
                      />
                      <label 
                        htmlFor="evidence-upload" 
                        className={`w-10 h-10 flex items-center justify-center rounded-lg border border-white/10 bg-white/5 text-gray-400 hover:text-white cursor-pointer transition-colors ${uploading ? 'opacity-50' : ''}`}
                      >
                        {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileImage className="w-4 h-4" />}
                      </label>
                    </div>
                    
                    <input 
                      type="text" 
                      value={replyContent}
                      onChange={e => setReplyContent(e.target.value)}
                      onKeyDown={e => e.key === 'Enter' && submitReply()}
                      placeholder="Nhập nội dung phản hồi..."
                      className="flex-1 bg-white/5 border border-white/10 rounded-lg px-4 text-sm text-white focus:outline-none focus:border-primary"
                      disabled={replying}
                    />
                    
                    <button 
                      onClick={submitReply}
                      disabled={replying || (!replyContent.trim() && evidenceUrls.length === 0)}
                      className="w-10 h-10 flex items-center justify-center rounded-lg bg-primary text-primary-foreground disabled:opacity-50 hover:bg-primary/90 transition-colors"
                    >
                      {replying ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                    </button>
                  </div>
                  <div className="text-[10px] text-gray-500 mt-2">
                    Gửi ảnh bằng chứng hoặc cung cấp thông tin giao hàng để được hỗ trợ. 
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
