'use client';

import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';
import {
  Landmark, Clock, CheckCircle2, XCircle, Loader2,
  User, CreditCard, Building2, AlertCircle, RefreshCw,
  ChevronLeft, ChevronRight, Search, Eye, ArrowRightLeft,
  Wallet
} from 'lucide-react';

interface Withdrawal {
  id: string;
  amount: number;
  status: string;
  createdAt: string;
  bankName?: string;
  bankAccount?: string;
  accountName?: string;
  note?: string;
  seller?: {
    id: string;
    name: string;
    email: string;
  };
}

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  PENDING: { label: 'Chờ duyệt', color: 'orange', icon: Clock },
  APPROVED: { label: 'Đã duyệt · chờ chuyển', color: 'blue', icon: ArrowRightLeft },
  COMPLETED: { label: 'Đã hoàn tất', color: 'teal', icon: CheckCircle2 },
  REJECTED: { label: 'Đã từ chối', color: 'red', icon: XCircle },
};

export default function AdminWithdrawalsPage() {
  const [withdrawals, setWithdrawals] = useState<Withdrawal[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState('PENDING');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [selectedWithdrawalId, setSelectedWithdrawalId] = useState<string | null>(null);
  const [toast, setToast] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);
  const LIMIT = 15;

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

  const normalizeStatus = (status?: string) => {
    const normalized = (status || 'PENDING').toUpperCase();
    if (['DONE', 'SUCCESS', 'COMPLETED'].includes(normalized)) return 'COMPLETED';
    if (['REJECTED', 'DECLINED', 'CANCELLED', 'FAILED'].includes(normalized)) return 'REJECTED';
    return normalized;
  };

  const getErrorMessage = (error: unknown) => {
    if (typeof error === 'object' && error !== null && 'response' in error) {
      const response = (error as { response?: { data?: { message?: string } } }).response;
      if (response?.data?.message) return response.data.message;
    }
    if (error instanceof Error) return error.message;
    return 'Có lỗi xảy ra';
  };

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const res = await api.get('/admin/withdrawals', {
        params: { page, limit: LIMIT, status: statusFilter || undefined },
      });
      const data = Array.isArray(res.data?.data) ? res.data.data : Array.isArray(res.data) ? res.data : [];
      const normalizedData = data.map((item: Withdrawal) => ({ ...item, status: normalizeStatus(item.status) }));
      const filtered = search
        ? normalizedData.filter((w: Withdrawal) => `${w.seller?.name || ''} ${w.seller?.email || ''} ${w.bankName || ''}`.toLowerCase().includes(search.toLowerCase()))
        : normalizedData;
      setWithdrawals(filtered);
      setTotal(res.data?.total || normalizedData.length || 0);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [page, statusFilter, search]);

  useEffect(() => {
    let isMounted = true;

    void (async () => {
      try {
        await fetchData();
      } catch (error) {
        if (isMounted) {
          console.error('Failed to load withdrawals', error);
        }
      }
    })();

    return () => {
      isMounted = false;
    };
  }, [fetchData]);

  const handleApprove = async (id: string) => {
    if (!confirm('Xác nhận DUYỆT yêu cầu rút tiền này?')) return;
    try {
      setActionLoading(id + '_approve');
      await api.patch(`/admin/withdrawals/${id}/approve`);
      showToast('success', '✅ Đã duyệt thành công!');
      fetchData();
    } catch (error: unknown) {
      showToast('error', getErrorMessage(error));
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (id: string) => {
    if (!confirm('Xác nhận TỪ CHỐI? Tiền sẽ được HOÀN LẠI cho người dùng.')) return;
    try {
      setActionLoading(id + '_reject');
      await api.patch(`/admin/withdrawals/${id}/reject`);
      showToast('success', '🔄 Đã từ chối và hoàn tiền!');
      fetchData();
    } catch (error: unknown) {
      showToast('error', getErrorMessage(error));
    } finally {
      setActionLoading(null);
    }
  };

  const handleComplete = async (id: string) => {
    if (!confirm('Chỉ xác nhận khi đã chuyển khoản thực tế cho Seller. Hoàn tất giao dịch này?')) return;
    try {
      setActionLoading(id + '_complete');
      await api.patch(`/admin/withdrawals/${id}/complete`);
      showToast('success', 'Đã xác nhận chuyển khoản và hoàn tất yêu cầu.');
      fetchData();
    } catch (error: unknown) {
      showToast('error', getErrorMessage(error));
    } finally {
      setActionLoading(null);
    }
  };

  const totalPages = Math.ceil(total / LIMIT);
  const pendingCount = withdrawals.filter((w) => w.status === 'PENDING').length;
  const completedCount = withdrawals.filter((w) => w.status === 'COMPLETED').length;
  const rejectedCount = withdrawals.filter((w) => w.status === 'REJECTED').length;
  const selectedWithdrawal = withdrawals.find((w) => w.id === selectedWithdrawalId) || null;

  return (
    <div className="space-y-6">
      {toast && (
        <div className={`fixed top-6 right-6 z-50 px-5 py-3 rounded-xl shadow-2xl text-sm font-bold flex items-center gap-2 animate-bounce ${
          toast.type === 'success' ? 'bg-teal-500/20 border border-teal-500/40 text-teal-300' : 'bg-red-500/20 border border-red-500/40 text-red-300'
        }`}>
          {toast.type === 'success' ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Landmark className="w-6 h-6 text-teal-400" />
            Quản lý Rút tiền
          </h1>
          <p className="text-gray-500 text-sm mt-1">Theo dõi toàn bộ yêu cầu rút tiền, kiểm tra ngân hàng và quyết định duyệt/từ chối.</p>
        </div>
        <button onClick={() => fetchData()} className="flex items-center gap-2 px-4 py-2 bg-white/5 border border-white/10 rounded-xl text-gray-400 hover:text-white text-sm transition-all">
          <RefreshCw className="w-4 h-4" />
          Làm mới
        </button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        {[{ label: 'Tổng yêu cầu', value: total, color: 'text-blue-400' }, { label: 'Chờ duyệt', value: pendingCount, color: 'text-orange-400' }, { label: 'Đã duyệt', value: completedCount, color: 'text-teal-400' }, { label: 'Đã từ chối', value: rejectedCount, color: 'text-red-400' }].map((card, i) => (
          <div key={i} className="rounded-2xl border border-white/10 bg-[#141414] p-5">
            <p className="text-gray-400 text-xs mb-1">{card.label}</p>
            <p className={`font-bold text-2xl ${card.color}`}>{card.value}</p>
          </div>
        ))}
      </div>

      <div className="flex flex-col gap-3 md:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Tìm người dùng hoặc ngân hàng..." className="w-full rounded-xl border border-white/10 bg-[#141414] pl-10 pr-4 py-2.5 text-sm text-white" />
        </div>
        <div className="flex gap-2">
          {[
            { key: 'PENDING', label: 'Chờ duyệt' },
            { key: 'APPROVED', label: 'Chờ chuyển' },
            { key: 'COMPLETED', label: 'Hoàn tất' },
            { key: 'REJECTED', label: 'Đã từ chối' },
            { key: '', label: 'Tất cả' },
          ].map((tab) => (
            <button key={tab.key} onClick={() => { setStatusFilter(tab.key); setPage(1); }} className={`px-4 py-2 rounded-xl text-xs font-bold transition-all ${statusFilter === tab.key ? 'bg-teal-500/10 border border-teal-500/30 text-teal-400' : 'bg-[#141414] border border-white/5 text-gray-400 hover:text-white'}`}>
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      <div className="bg-[#141414] border border-white/5 rounded-2xl overflow-hidden">
        <div className="grid grid-cols-12 gap-3 px-5 py-3 border-b border-white/5 text-xs text-gray-500 font-bold uppercase tracking-wider">
          <div className="col-span-3">Người dùng</div>
          <div className="col-span-3">Thông tin ngân hàng</div>
          <div className="col-span-2 text-right">Số tiền</div>
          <div className="col-span-2">Ngày yêu cầu</div>
          <div className="col-span-2 text-center">Hành động</div>
        </div>

        {loading ? (
          <div>{[1,2,3,4,5].map((i) => <div key={i} className="grid grid-cols-12 gap-3 px-5 py-5 border-b border-white/5"><div className="col-span-3 h-10 rounded-xl bg-white/5 animate-pulse" /><div className="col-span-3 h-10 rounded-xl bg-white/5 animate-pulse" /><div className="col-span-2 h-10 rounded-xl bg-white/5 animate-pulse" /><div className="col-span-2 h-10 rounded-xl bg-white/5 animate-pulse" /><div className="col-span-2 h-10 rounded-xl bg-white/5 animate-pulse" /></div>)}</div>
        ) : withdrawals.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-gray-500"><Landmark className="w-16 h-16 mb-4 opacity-10" /><p className="font-medium">Không có yêu cầu rút tiền nào</p></div>
        ) : (
          withdrawals.map((w) => {
            const statusInfo = STATUS_CONFIG[w.status] || { label: w.status, color: 'gray', icon: Clock };
            const Icon = statusInfo.icon;
            const isApproving = actionLoading === w.id + '_approve';
            const isRejecting = actionLoading === w.id + '_reject';
            const isBusy = isApproving || isRejecting;

            return (
              <div key={w.id} className="grid grid-cols-12 gap-3 px-5 py-4 border-b border-white/5 last:border-0 hover:bg-white/[0.02] transition-colors items-center">
                <div className="col-span-3 flex items-center gap-3 min-w-0">
                  <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-teal-500/20 to-blue-500/20 border border-white/10 flex items-center justify-center shrink-0"><User className="w-4 h-4 text-teal-400" /></div>
                  <div className="min-w-0">
                    <p className="text-white text-sm font-semibold truncate">{w.seller?.name || 'Ẩn danh'}</p>
                    <p className="text-gray-500 text-xs truncate">{w.seller?.email || '—'}</p>
                  </div>
                </div>
                <div className="col-span-3 min-w-0">
                  {w.bankName ? (
                    <div>
                      <div className="flex items-center gap-1.5 mb-0.5"><Building2 className="w-3 h-3 text-blue-400 shrink-0" /><p className="text-white text-sm font-semibold truncate">{w.bankName}</p></div>
                      <div className="flex items-center gap-1.5"><CreditCard className="w-3 h-3 text-gray-500 shrink-0" /><p className="text-gray-400 text-xs font-mono">{w.bankAccount}</p></div>
                      <p className="text-gray-500 text-xs truncate mt-0.5">{w.accountName}</p>
                      {w.note && <p className="text-gray-600 text-[10px] italic truncate">{w.note}</p>}
                    </div>
                  ) : <p className="text-gray-600 text-xs italic">Không có thông tin</p>}
                </div>
                <div className="col-span-2 text-right">
                  <p className="text-white font-bold text-base">{Number(w.amount).toLocaleString('vi-VN')}đ</p>
                  <span className={`inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full mt-1 ${w.status === 'PENDING' ? 'bg-orange-500/10 text-orange-400 border border-orange-500/20' : w.status === 'APPROVED' ? 'bg-blue-500/10 text-blue-400 border border-blue-500/20' : w.status === 'COMPLETED' ? 'bg-teal-500/10 text-teal-400 border border-teal-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'}`}><Icon className="w-2.5 h-2.5" />{statusInfo.label}</span>
                </div>
                <div className="col-span-2">
                  <p className="text-gray-400 text-xs">{new Date(w.createdAt).toLocaleDateString('vi-VN')}</p>
                  <p className="text-gray-600 text-[10px]">{new Date(w.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })}</p>
                  <p className="text-gray-700 text-[10px] font-mono mt-0.5">#{w.id.slice(0, 8).toUpperCase()}</p>
                </div>
                <div className="col-span-2 flex flex-col gap-1.5 items-center">
                  <button onClick={() => setSelectedWithdrawalId(w.id)} className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-white/5 border border-white/10 text-gray-300 hover:text-white rounded-lg text-xs font-bold transition-all">
                    <Eye className="w-3 h-3" />Chi tiết
                  </button>
                  {w.status === 'PENDING' ? <><button onClick={() => handleApprove(w.id)} disabled={isBusy} className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-teal-500/10 border border-teal-500/30 text-teal-400 hover:bg-teal-500/20 rounded-lg text-xs font-bold transition-all disabled:opacity-50">{isApproving ? <Loader2 className="w-3 h-3 animate-spin" /> : <CheckCircle2 className="w-3 h-3" />}Duyệt</button><button onClick={() => handleReject(w.id)} disabled={isBusy} className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-red-500/10 border border-red-500/30 text-red-400 hover:bg-red-500/20 rounded-lg text-xs font-bold transition-all disabled:opacity-50">{isRejecting ? <Loader2 className="w-3 h-3 animate-spin" /> : <XCircle className="w-3 h-3" />}Từ chối</button></> : w.status === 'APPROVED' ? <><button onClick={() => handleComplete(w.id)} disabled={actionLoading === w.id + '_complete'} className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-blue-500/10 border border-blue-500/30 text-blue-300 hover:bg-blue-500/20 rounded-lg text-xs font-bold transition-all disabled:opacity-50">{actionLoading === w.id + '_complete' ? <Loader2 className="w-3 h-3 animate-spin" /> : <CheckCircle2 className="w-3 h-3" />}Đã chuyển tiền</button><button onClick={() => handleReject(w.id)} disabled={isBusy} className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-red-500/10 border border-red-500/30 text-red-400 hover:bg-red-500/20 rounded-lg text-xs font-bold transition-all disabled:opacity-50"><XCircle className="w-3 h-3" />Từ chối</button></> : <span className={`text-xs font-semibold ${w.status === 'COMPLETED' ? 'text-teal-400' : 'text-red-400'}`}>{statusInfo.label}</span>}
                </div>
              </div>
            );
          })
        )}
      </div>

      {selectedWithdrawal && (
        <div className="rounded-2xl border border-white/10 bg-[#101010] p-5">
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div>
              <p className="text-xs uppercase tracking-[0.2em] text-gray-500">Chi tiết luồng xử lý</p>
              <h2 className="text-lg font-bold text-white">#{selectedWithdrawal.id.slice(0, 8).toUpperCase()}</h2>
            </div>
            <button onClick={() => setSelectedWithdrawalId(null)} className="text-sm text-gray-400 hover:text-white">Đóng</button>
          </div>

          <div className="mt-4 grid gap-4 md:grid-cols-3">
            <div className="rounded-xl border border-white/10 bg-[#141414] p-4">
              <div className="flex items-center gap-2 text-sm text-gray-400"><Wallet className="w-4 h-4 text-teal-400" />Số tiền</div>
              <p className="mt-2 text-xl font-bold text-white">{Number(selectedWithdrawal.amount).toLocaleString('vi-VN')}đ</p>
            </div>
            <div className="rounded-xl border border-white/10 bg-[#141414] p-4">
              <div className="flex items-center gap-2 text-sm text-gray-400"><Building2 className="w-4 h-4 text-blue-400" />Ngân hàng</div>
              <p className="mt-2 text-sm font-semibold text-white">{selectedWithdrawal.bankName || '—'}</p>
              <p className="text-xs text-gray-500">{selectedWithdrawal.bankAccount || '—'}</p>
            </div>
            <div className="rounded-xl border border-white/10 bg-[#141414] p-4">
              <div className="flex items-center gap-2 text-sm text-gray-400"><User className="w-4 h-4 text-orange-400" />Người bán</div>
              <p className="mt-2 text-sm font-semibold text-white">{selectedWithdrawal.seller?.name || 'Ẩn danh'}</p>
              <p className="text-xs text-gray-500">{selectedWithdrawal.seller?.email || '—'}</p>
            </div>
          </div>

          <div className="mt-4 rounded-xl border border-white/10 bg-[#141414] p-4">
            <div className="flex items-center gap-2 text-sm font-semibold text-white"><ArrowRightLeft className="w-4 h-4 text-teal-400" />Chu trình xử lý</div>
            <div className="mt-4 space-y-3">
              {[
                { label: 'Yêu cầu được tạo', detail: new Date(selectedWithdrawal.createdAt).toLocaleString('vi-VN'), done: true },
                { label: selectedWithdrawal.status === 'PENDING' ? 'Đang chờ duyệt' : selectedWithdrawal.status === 'COMPLETED' ? 'Đã duyệt và chuyển tiền' : 'Đã từ chối', detail: selectedWithdrawal.note || 'Không có ghi chú bổ sung', done: true },
                { label: selectedWithdrawal.status === 'COMPLETED' ? 'Hoàn tất giao dịch' : selectedWithdrawal.status === 'REJECTED' ? 'Đóng yêu cầu và hoàn tiền' : 'Đợi bước xác nhận cuối cùng', detail: 'Có thể xem thêm trong audit log hoặc ghi chú điều hành.', done: selectedWithdrawal.status !== 'PENDING' },
              ].map((step, index) => (
                <div key={step.label} className="flex gap-3">
                  <div className={`mt-0.5 h-2.5 w-2.5 rounded-full ${step.done ? 'bg-teal-400' : 'bg-white/10'}`} />
                  <div className="flex-1 rounded-lg border border-white/10 bg-black/20 p-3">
                    <p className="text-sm font-semibold text-white">{index + 1}. {step.label}</p>
                    <p className="text-xs text-gray-500 mt-1">{step.detail}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {totalPages > 1 && <div className="flex items-center justify-between text-sm text-gray-500"><span>Hiển thị {withdrawals.length} / {total} yêu cầu</span><div className="flex gap-2"><button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1} className="px-3 py-2 bg-white/5 border border-white/10 rounded-xl hover:text-white disabled:opacity-40 transition-all"><ChevronLeft className="w-4 h-4" /></button><span className="px-4 py-2 bg-teal-500/10 border border-teal-500/20 rounded-xl text-teal-400 font-bold">{page} / {totalPages}</span><button onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={page === totalPages} className="px-3 py-2 bg-white/5 border border-white/10 rounded-xl hover:text-white disabled:opacity-40 transition-all"><ChevronRight className="w-4 h-4" /></button></div></div>}
    </div>
  );
}
