'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, 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 BuyerComplaintsPage() {
  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(() => {
    fetchDisputes();
  }, [filterStatus]);

  const fetchDisputes = async () => {
    try {
      setLoading(true);
      const res = await api.get(`/disputes/buyer?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([]);
      selectDispute(selectedDisputeId);
      fetchDisputes();
    } catch (err) {
      console.error('Lỗi phản hồi', err);
    } finally {
      setReplying(false);
    }
  };

  return (
    <div className="max-w-6xl mx-auto px-4 py-8 h-[calc(100vh-80px)] flex flex-col">
      {/* Header Info */}
      <div className="pb-4 flex-shrink-0">
        <div>
          <h1 className="text-2xl font-black text-white uppercase tracking-tight">Khiếu nại của tôi</h1>
          <p className="text-sm text-gray-500 mt-1">Theo dõi quá trình xử lý khiếu nại và trò chuyện với người bán hoặc Admin.</p>
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-3 mt-6 mb-2">
          <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-[#141414] border border-white/10 rounded-xl text-sm text-white focus:outline-none focus:border-red-500"
            />
          </div>
          <select 
            value={filterStatus}
            onChange={e => setFilterStatus(e.target.value)}
            className="bg-[#141414] border border-white/10 rounded-xl px-4 py-2 text-sm text-white focus:outline-none focus:border-red-500"
          >
            <option value="all">Tất cả trạng thái</option>
            <option value="PENDING">Chờ phản hồi</option>
            <option value="WAITING_BUYER">Cần bạn trả lời</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-red-600 text-white font-bold rounded-xl text-sm hover:bg-red-700 transition-colors"
          >
            Áp dụng
          </button>
        </div>
      </div>

      {/* Main Content Split */}
      <div className="flex-1 flex overflow-hidden border border-white/5 bg-[#141414] rounded-2xl shadow-2xl">
        
        {/* Left Pane - List */}
        <div className="w-full md:w-[45%] lg:w-[40%] flex flex-col border-r border-white/5">
          <div className="flex-1 overflow-auto">
            {loading ? (
              <div className="flex justify-center items-center h-full">
                <Loader2 className="w-6 h-6 animate-spin text-red-500" />
              </div>
            ) : disputes.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full p-8 text-center">
                <AlertCircle className="w-12 h-12 text-gray-700 mb-3" />
                <p className="text-gray-500 text-sm">Bạn chưa có khiếu nại nào.</p>
              </div>
            ) : (
              <div className="divide-y divide-white/5">
                {disputes.map(d => {
                  const st = STATUS_CONFIG[d.status] || STATUS_CONFIG.PENDING;
                  const isSelected = selectedDisputeId === d.id;
                  return (
                    <div 
                      key={d.id} 
                      onClick={() => selectDispute(d.id)}
                      className={`p-4 cursor-pointer transition-colors ${
                        isSelected ? 'bg-red-500/10 border-l-4 border-l-red-500' : 'hover:bg-white/[0.02] border-l-4 border-l-transparent'
                      }`}
                    >
                      <div className="flex justify-between items-start mb-2">
                        <span className="font-mono text-white text-xs font-bold">#{d.orderId.substring(0, 8)}</span>
                        <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold ${st.bg} ${st.color}`}>
                          {st.label}
                        </span>
                      </div>
                      <p className="text-sm text-gray-400 line-clamp-2 mb-2">{d.reason}</p>
                      <div className="flex justify-between items-center text-xs">
                        <span className="text-red-400 font-bold">{Number(d.order.totalAmount).toLocaleString('vi-VN')}₫</span>
                        <span className="text-gray-600">{new Date(d.updatedAt).toLocaleDateString('vi-VN')}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* Right Pane - Detail */}
        <div className="hidden md:flex flex-1 flex-col bg-[#0a0a0a]">
          {!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 ở danh sách bên trái để xem chi tiết và trao đổi.</p>
            </div>
          ) : !disputeDetail ? (
            <div className="flex-1 flex items-center justify-center">
              <Loader2 className="w-8 h-8 animate-spin text-red-500" />
            </div>
          ) : (
            <>
              {/* Detail Header */}
              <div className="p-4 border-b border-white/5 bg-[#141414]">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-bold text-white">Chi tiết khiếu nại</h3>
                </div>
                <div className="grid grid-cols-2 gap-4 text-sm mt-3">
                  <div>
                    <span className="text-gray-500 text-xs block uppercase font-bold tracking-wider mb-1">Mã đơn hàng</span>
                    <span className="text-white font-mono text-xs bg-white/5 px-2 py-1 rounded">{disputeDetail.orderId}</span>
                  </div>
                  <div>
                    <span className="text-gray-500 text-xs block uppercase font-bold tracking-wider mb-1">Người bán</span>
                    <span className="text-white text-xs">{disputeDetail.seller.name || disputeDetail.seller.email}</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');

                  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-bold ${isAdmin ? 'text-purple-400' : isMe ? 'text-red-400' : 'text-gray-400'}`}>
                          {isAdmin ? 'Quản trị viên' : isMe ? 'Bạn' : 'Người bán'}
                        </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-500/20 text-purple-100 border border-purple-500/30' 
                        : isMe ? 'bg-red-600 text-white shadow-[0_0_15px_rgba(220,38,38,0.2)]' 
                        : '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-[#141414] 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 border border-white/10">
                          <img src={url} className="w-full h-full object-cover" />
                          <button onClick={() => removeEvidence(i)} className="absolute inset-0 bg-red-500/80 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-11 h-11 flex items-center justify-center rounded-xl border border-white/10 bg-white/5 text-gray-400 hover:text-white cursor-pointer transition-colors hover:bg-white/10 ${uploading ? 'opacity-50' : ''}`}
                      >
                        {uploading ? <Loader2 className="w-5 h-5 animate-spin" /> : <FileImage className="w-5 h-5" />}
                      </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-xl px-4 text-sm text-white focus:outline-none focus:border-red-500 transition-colors"
                      disabled={replying}
                    />
                    
                    <button 
                      onClick={submitReply}
                      disabled={replying || (!replyContent.trim() && evidenceUrls.length === 0)}
                      className="w-11 h-11 flex items-center justify-center rounded-xl bg-red-600 text-white disabled:opacity-50 hover:bg-red-700 shadow-[0_0_15px_rgba(220,38,38,0.3)] transition-all"
                    >
                      {replying ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />}
                    </button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
