'use client';

import { useState, useEffect } from 'react';
import { api } from '@/lib/api';
import {
  ArrowUpRight, ArrowDownLeft, Clock, CheckCircle2, XCircle,
  TrendingUp, Wallet, BarChart3, Download, Filter, Search, Loader2,
  ShoppingBag, BanknoteIcon, RefreshCw, ArrowRightLeft
} from 'lucide-react';

const TYPE_CONFIG: Record<string, { label: string; color: string; bg: string; icon: any; sign: '+' | '-' }> = {
  DEPOSIT:         { label: 'Nạp tiền',        color: 'text-green-400',  bg: 'bg-green-500/10',  icon: ArrowDownLeft,  sign: '+' },
  ESCROW_RELEASE:  { label: 'Nhận từ đơn hàng', color: 'text-emerald-400',bg: 'bg-emerald-500/10',icon: ShoppingBag,    sign: '+' },
  REFUND:          { label: 'Hoàn tiền',        color: 'text-blue-400',   bg: 'bg-blue-500/10',   icon: RefreshCw,     sign: '+' },
  WITHDRAWAL:      { label: 'Rút tiền',         color: 'text-orange-400', bg: 'bg-orange-500/10', icon: BanknoteIcon,  sign: '-' },
  PAYMENT:         { label: 'Thanh toán đơn',   color: 'text-red-400',    bg: 'bg-red-500/10',    icon: ArrowUpRight,  sign: '-' },
};

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: any }> = {
  COMPLETED: { label: 'Hoàn thành', color: 'text-green-400',  icon: CheckCircle2 },
  PENDING:   { label: 'Chờ duyệt',  color: 'text-yellow-400', icon: Clock },
  REJECTED:  { label: 'Bị từ chối', color: 'text-red-400',    icon: XCircle },
};

export default function SellerLedgerPage() {
  const [loading, setLoading] = useState(true);
  const [transactions, setTransactions] = useState<any[]>([]);
  const [sellerBalance, setSellerBalance] = useState(0);
  const [filter, setFilter] = useState('ALL');
  const [search, setSearch] = useState('');

  useEffect(() => {
    Promise.all([
      api.get('/wallet/summary'),
      api.get('/wallet/history'),
    ])
      .then(([summaryRes, histRes]) => {
        setSellerBalance(Number(summaryRes.data.sellerBalance || 0));
        setTransactions(histRes.data || []);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const filtered = transactions.filter(tx => {
    const matchType = filter === 'ALL' || tx.type === filter;
    const matchSearch = search === '' || tx.reference?.toLowerCase().includes(search.toLowerCase());
    return matchType && matchSearch;
  });

  const totalIn = transactions
    .filter(tx => ['DEPOSIT', 'ESCROW_RELEASE', 'REFUND'].includes(tx.type) && tx.status === 'COMPLETED')
    .reduce((sum, tx) => sum + Number(tx.amount), 0);

  const totalOut = transactions
    .filter(tx => ['WITHDRAWAL', 'PAYMENT'].includes(tx.type) && tx.status === 'COMPLETED')
    .reduce((sum, tx) => sum + Number(tx.amount), 0);

  const pendingWithdrawals = transactions
    .filter(tx => tx.type === 'WITHDRAWAL' && tx.status === 'PENDING')
    .reduce((sum, tx) => sum + Number(tx.amount), 0);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Sổ Cái Tài Chính</h1>
        <p className="text-sm text-gray-500 mt-1">Toàn bộ lịch sử dòng tiền của tài khoản bạn.</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-blue-500/10 flex items-center justify-center">
              <Wallet className="w-4 h-4 text-blue-400" />
            </div>
            <span className="text-xs text-gray-400">Số dư hiện tại</span>
          </div>
          <p className="text-xl font-bold text-white">{sellerBalance.toLocaleString('vi-VN')}₫</p>
        </div>
        <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-green-500/10 flex items-center justify-center">
              <TrendingUp className="w-4 h-4 text-green-400" />
            </div>
            <span className="text-xs text-gray-400">Tổng tiền vào</span>
          </div>
          <p className="text-xl font-bold text-green-400">+{totalIn.toLocaleString('vi-VN')}₫</p>
        </div>
        <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-8 h-8 rounded-lg bg-red-500/10 flex items-center justify-center">
              <ArrowUpRight className="w-4 h-4 text-red-400" />
            </div>
            <span className="text-xs text-gray-400">Tổng tiền ra</span>
          </div>
          <p className="text-xl font-bold text-red-400">-{totalOut.toLocaleString('vi-VN')}₫</p>
        </div>
        <div className="bg-[#15161a] border border-white/5 rounded-2xl p-5">
          <div className="flex items-center gap-2 mb-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>
            <span className="text-xs text-gray-400">Đang chờ duyệt</span>
          </div>
          <p className="text-xl font-bold text-yellow-400">{pendingWithdrawals.toLocaleString('vi-VN')}₫</p>
        </div>
      </div>

      {/* Filter & Search Bar */}
      <div className="bg-[#15161a] border border-white/5 rounded-2xl p-4">
        <div className="flex flex-col sm:flex-row gap-3">
          <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
              type="text"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Tìm theo mã tham chiếu..."
              className="w-full pl-10 pr-4 py-2.5 bg-[#0a0b0d] border border-white/10 rounded-xl text-sm text-white focus:outline-none focus:border-primary transition-colors"
            />
          </div>
          <div className="flex gap-2 flex-wrap">
            {['ALL', 'ESCROW_RELEASE', 'WITHDRAWAL', 'DEPOSIT', 'PAYMENT', 'REFUND'].map(type => (
              <button
                key={type}
                onClick={() => setFilter(type)}
                className={`px-3 py-2 text-xs font-medium rounded-lg transition-colors border ${
                  filter === type
                    ? 'bg-primary/20 text-primary border-primary/30'
                    : 'bg-white/5 text-gray-400 border-white/10 hover:bg-white/10'
                }`}
              >
                {type === 'ALL' ? 'Tất cả' : TYPE_CONFIG[type]?.label || type}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Transaction List */}
      <div className="bg-[#15161a] border border-white/5 rounded-2xl overflow-hidden">
        <div className="flex justify-between items-center px-6 py-4 border-b border-white/5">
          <h3 className="text-sm font-semibold text-white">
            Lịch sử giao dịch <span className="text-gray-500 font-normal">({filtered.length} giao dịch)</span>
          </h3>
          <button className="text-xs text-gray-400 hover:text-white flex items-center gap-1 transition-colors">
            <Download className="w-3.5 h-3.5" /> Xuất CSV
          </button>
        </div>

        {filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center px-4">
            <BarChart3 className="w-12 h-12 text-gray-600 mb-4" />
            <p className="text-sm text-gray-400">Chưa có giao dịch nào</p>
            <p className="text-xs text-gray-600 mt-1">Các giao dịch sẽ xuất hiện sau khi bạn nạp tiền hoặc bán hàng</p>
          </div>
        ) : (
          <div className="divide-y divide-white/5">
            {filtered.map((tx, idx) => {
              const config = TYPE_CONFIG[tx.type] || { label: tx.type, color: 'text-gray-400', bg: 'bg-white/5', icon: ArrowRightLeft, sign: '+' };
              const statusConfig = STATUS_CONFIG[tx.status] || { label: tx.status, color: 'text-gray-400', icon: Clock };
              const StatusIcon = statusConfig.icon;
              const TxIcon = config.icon;
              const isIncoming = config.sign === '+';

              return (
                <div key={idx} className="flex items-center gap-4 px-6 py-4 hover:bg-white/[0.02] transition-colors">
                  {/* Icon */}
                  <div className={`w-10 h-10 rounded-xl ${config.bg} flex items-center justify-center shrink-0`}>
                    <TxIcon className={`w-5 h-5 ${config.color}`} />
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-white">{config.label}</p>
                    <p className="text-xs text-gray-500 truncate mt-0.5">
                      {tx.reference || 'Không có mã tham chiếu'}
                    </p>
                  </div>

                  {/* Date */}
                  <div className="text-right shrink-0 hidden sm:block">
                    <p className="text-xs text-gray-500">
                      {new Date(tx.createdAt).toLocaleDateString('vi-VN')}
                    </p>
                    <p className="text-xs text-gray-600">
                      {new Date(tx.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })}
                    </p>
                  </div>

                  {/* Status */}
                  <div className={`flex items-center gap-1.5 text-xs font-medium ${statusConfig.color} shrink-0 hidden md:flex`}>
                    <StatusIcon className="w-3.5 h-3.5" />
                    {statusConfig.label}
                  </div>

                  {/* Amount */}
                  <div className={`text-right shrink-0 font-bold text-sm ${isIncoming ? 'text-green-400' : 'text-red-400'}`}>
                    {isIncoming ? '+' : '-'}{Number(tx.amount).toLocaleString('vi-VN')}₫
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
