'use client';

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

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string; icon: any }> = {
  PENDING: { label: 'Chờ Seller', color: 'text-red-400', bg: 'bg-red-500/10', icon: AlertTriangle },
  WAITING_BUYER: { label: 'Chờ Buyer', 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: 'Đã phân xử', color: 'text-green-400', bg: 'bg-green-500/10', icon: CheckCircle2 },
};

export default function AdminDisputesPage() {
  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 [resolving, setResolving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [evidenceUrls, setEvidenceUrls] = useState<string[]>([]);
  const [confirmModal, setConfirmModal] = useState<{ winner: 'BUYER' | 'SELLER' } | null>(null);
  const [toast, setToast] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 3500);
  };

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

  const fetchDisputes = async () => {
    try {
      setLoading(true);
      const res = await api.get(`/disputes/admin?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);
    }
  };

  const handleResolveClick = (winner: 'BUYER' | 'SELLER') => {
    if (!selectedDisputeId) return;
    setConfirmModal({ winner });
  };

  const confirmResolve = async () => {
    if (!confirmModal || !selectedDisputeId) return;
    const { winner } = confirmModal;
    setConfirmModal(null);
    try {
      setResolving(true);
      await api.post(`/disputes/admin/${selectedDisputeId}/resolve`, { winner });
      showToast('Phân xử thành công! Tiền đã được chuyển.');
      selectDispute(selectedDisputeId);
      fetchDisputes();
    } catch (err: any) {
      showToast(err.response?.data?.message || 'Có lỗi xảy ra khi phân xử', 'error');
    } finally {
      setResolving(false);
    }
  };

  const summary = {
    total: disputes.length,
    unresolved: disputes.filter((d) => d.status !== 'RESOLVED').length,
    resolved: disputes.filter((d) => d.status === 'RESOLVED').length,
  };

  return (
    <div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden">
      <div className="p-6 pb-4 flex-shrink-0">
        <div>
          <h1 className="text-2xl font-black text-white uppercase tracking-tight">Quản trị Khiếu nại</h1>
          <p className="text-sm text-gray-500 mt-1">Giám sát, phân xử và xử lý dòng tiền cho các khiếu nại phát sinh trên sàn.</p>
        </div>

        <div className="grid gap-4 md:grid-cols-3 mt-6">
          {[{ label: 'Tổng khiếu nại', value: summary.total, icon: FileText }, { label: 'Chưa xử lý', value: summary.unresolved, icon: AlertTriangle }, { label: 'Đã xử lý', value: summary.resolved, icon: CheckCircle2 }].map((item, index) => {
            const Icon = item.icon;
            return (
              <div key={index} className="rounded-2xl border border-white/10 bg-[#141414] p-4">
                <div className="flex items-center justify-between">
                  <p className="text-sm text-gray-500">{item.label}</p>
                  <Icon className="h-4 w-4 text-gray-400" />
                </div>
                <p className="mt-3 text-2xl font-black text-white">{item.value}</p>
              </div>
            );
          })}
        </div>

        <div className="flex flex-col sm:flex-row gap-3 mt-6">
          <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 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-purple-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-purple-500">
            <option value="all">Tất cả trạng thái</option>
            <option value="PENDING">Chờ Seller</option>
            <option value="WAITING_BUYER">Chờ Buyer</option>
            <option value="REVIEWING">Đang xem xét (Cần Admin)</option>
            <option value="RESOLVED">Đã phân xử</option>
          </select>
          <button onClick={handleSearch} className="px-6 py-2 bg-purple-600 text-white font-bold rounded-xl text-sm hover:bg-purple-700 transition-colors">Áp dụng</button>
        </div>
      </div>

      <div className="flex-1 flex overflow-hidden border-t border-white/5 bg-[#0a0a0a]">
        <div className="w-full md:w-[45%] lg:w-[40%] flex flex-col border-r border-white/5">
          <div className="flex-1 overflow-auto p-4">
            {loading ? (
              <div className="flex justify-center items-center h-full"><Loader2 className="w-6 h-6 animate-spin text-purple-500" /></div>
            ) : disputes.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full p-8 text-center bg-[#141414] rounded-2xl border border-white/5"><ShieldAlert className="w-12 h-12 text-gray-700 mb-3" /><p className="text-gray-500 text-sm">Chưa có khiếu nại nào.</p></div>
            ) : (
              <div className="flex flex-col gap-2">
                {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 rounded-xl border ${isSelected ? 'bg-purple-500/10 border-purple-500' : 'bg-[#141414] border-white/5 hover:border-white/20'}`}>
                      <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-green-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>

        <div className="hidden md:flex flex-1 flex-col bg-[#111111]">
          {!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"><ShieldAlert 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">Xem xét bằng chứng từ cả hai phía và đưa ra phán quyết.</p>
            </div>
          ) : !disputeDetail ? (
            <div className="flex-1 flex items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-purple-500" /></div>
          ) : (
            <>
              <div className="p-4 border-b border-white/5 bg-[#141414]">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="font-bold text-white uppercase tracking-wider text-sm">Thông tin khiếu nại</h3>
                  <div className="text-right">
                    <span className="block text-xs text-gray-500">Giá trị tranh chấp</span>
                    <span className="text-green-400 font-black text-xl">{Number(disputeDetail.order.totalAmount).toLocaleString('vi-VN')}₫</span>
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="bg-white/5 p-3 rounded-lg border border-white/5"><span className="text-gray-500 text-xs block uppercase font-bold tracking-wider mb-1">Người Mua (Buyer)</span><span className="text-white text-sm font-medium">{disputeDetail.buyer.name || disputeDetail.buyer.email}</span></div>
                  <div className="bg-white/5 p-3 rounded-lg border border-white/5"><span className="text-gray-500 text-xs block uppercase font-bold tracking-wider mb-1">Người Bán (Seller)</span><span className="text-white text-sm font-medium">{disputeDetail.seller.name || disputeDetail.seller.email}</span></div>
                </div>
              </div>

              <div className="flex-1 overflow-auto p-4 space-y-4">
                {disputeDetail.messages.map((msg: any) => {
                  const isAdmin = msg.sender?.role?.name === 'ADMIN' || msg.sender?.role?.name === 'SUPER_ADMIN';
                  const isBuyer = msg.senderId === disputeDetail.buyerId;
                  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 text-sm">
                          <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" />
                            <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 ${isAdmin ? 'items-end' : 'items-start'}`}>
                      <div className="flex items-center gap-2 mb-1">
                        <span className={`text-xs font-bold ${isAdmin ? 'text-purple-400' : isBuyer ? 'text-blue-400' : 'text-orange-400'}`}>{isAdmin ? 'Bạn (Admin)' : isBuyer ? 'Người Mua' : '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-600 text-white shadow-[0_0_15px_rgba(147,51,234,0.2)]' : isBuyer ? 'bg-blue-500/20 text-blue-100 border border-blue-500/30' : 'bg-orange-500/20 text-orange-100 border border-orange-500/30'}`}>{msg.content}</div>
                      {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>

              {disputeDetail.status !== 'RESOLVED' && (
                <div className="p-4 bg-[#141414] border-t border-white/5 flex flex-col gap-3">
                  <div className="flex gap-3 bg-yellow-500/5 p-3 rounded-xl border border-yellow-500/20">
                    <button onClick={() => handleResolveClick('BUYER')} disabled={resolving} className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-bold text-sm transition-colors disabled:opacity-50">{resolving ? <Loader2 className="w-4 h-4 animate-spin" /> : <DollarSign className="w-4 h-4" />}Người Mua thắng (Hoàn tiền)</button>
                    <button onClick={() => handleResolveClick('SELLER')} disabled={resolving} className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg bg-orange-600 hover:bg-orange-700 text-white font-bold text-sm transition-colors disabled:opacity-50">{resolving ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle2 className="w-4 h-4" />}Người Bán thắng (Trả tiền)</button>
                  </div>
                  <div className="flex items-center gap-2"><div className="h-px bg-white/5 flex-1"></div><span className="text-xs text-gray-600 font-bold uppercase tracking-widest">Hoặc nhắn tin yêu cầu</span><div className="h-px bg-white/5 flex-1"></div></div>
                  {evidenceUrls.length > 0 && <div className="flex gap-2 overflow-x-auto pb-1">{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-admin" onChange={handleFileUpload} disabled={uploading || replying} /><label htmlFor="evidence-upload-admin" 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="Gửi tin nhắn cho cả hai bên..." className="flex-1 bg-white/5 border border-white/10 rounded-xl px-4 text-sm text-white focus:outline-none focus:border-purple-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-purple-600 text-white disabled:opacity-50 hover:bg-purple-700 transition-all">{replying ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />}</button></div>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {confirmModal && <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"><div className="bg-[#1a1b1e] border border-white/10 rounded-2xl w-full max-w-md p-6 shadow-2xl"><h3 className="text-xl font-black text-white mb-3 flex items-center gap-2"><ShieldAlert className="w-6 h-6 text-yellow-400" />Xác nhận phân xử</h3>{confirmModal.winner === 'BUYER' ? <><p className="text-gray-300 text-sm mb-1">Bạn sắp phán quyết <span className="text-blue-400 font-bold">Người Mua thắng</span>.</p><p className="text-gray-400 text-sm mb-6">Tiền sẽ được <span className="text-green-400 font-bold">hoàn lại (Refund)</span> cho Người Mua. Đơn hàng bị hủy. <span className="text-red-400 font-bold">Hành động không thể hoàn tác!</span></p></> : <><p className="text-gray-300 text-sm mb-1">Bạn sắp phán quyết <span className="text-orange-400 font-bold">Người Bán thắng</span>.</p><p className="text-gray-400 text-sm mb-6">Tiền sẽ được <span className="text-green-400 font-bold">giải ngân (Escrow Release)</span> cho Người Bán. Đơn hàng hoàn tất. <span className="text-red-400 font-bold">Hành động không thể hoàn tác!</span></p></>}<div className="flex gap-3 justify-end"><button onClick={() => setConfirmModal(null)} className="px-5 py-2.5 rounded-xl bg-white/5 text-gray-300 font-bold text-sm hover:bg-white/10 transition-colors">Hủy bỏ</button><button onClick={confirmResolve} className={`px-5 py-2.5 rounded-xl text-white font-bold text-sm transition-colors ${confirmModal.winner === 'BUYER' ? 'bg-blue-600 hover:bg-blue-700' : 'bg-orange-600 hover:bg-orange-700'}`}>Xác nhận phán quyết</button></div></div></div>}

      {toast && <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-3 px-5 py-3 rounded-2xl shadow-2xl text-white font-medium text-sm ${toast.type === 'success' ? 'bg-green-600' : 'bg-red-600'}`}><CheckCircle2 className="w-5 h-5" />{toast.msg}</div>}
    </div>
  );
}
