import { useState, useEffect } from 'react';
import { Table, Tag, Input, Space, Button } from 'antd';
import { Search, Wallet, CreditCard, History, ArrowUpRight, ArrowDownLeft } from 'lucide-react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { requestGetUserHistory } from '../config/deposits';
import moment from 'moment';
import { Link } from 'react-router-dom';
import { useStore } from '../hooks/useStore';
import { Helmet } from 'react-helmet';

const TransactionHistory = () => {
    const { dataWebsite } = useStore();
    const [loading, setLoading] = useState(true);
    const [deposits, setDeposits] = useState([]);
    const [transactions, setTransactions] = useState([]);
    const [stats, setStats] = useState({
        balance: 0,
        totalDeposited: 0,
        totalSpent: 0,
        totalDepositedMonth: 0,
    });
    const [searchText, setSearchText] = useState('');

    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await requestGetUserHistory();
            setDeposits(data.metadata.deposits);
            setTransactions(data.metadata.transactions);
            setStats(data.metadata.stats);
        } catch (error) {
            console.error('Failed to fetch history:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const depositColumns = [
        {
            title: 'ID',
            dataIndex: '_id',
            key: 'id',
            render: (id) => <span className="text-gray-400 text-xs">#{id.slice(-4)}</span>,
        },
        {
            title: 'Mã Giao Dịch',
            dataIndex: 'code',
            key: 'code',
            render: (code) => <span className="font-semibold text-blue-600">{code || 'N/A'}</span>,
        },
        {
            title: 'Số Serial',
            dataIndex: 'serial',
            key: 'serial',
        },
        {
            title: 'Mã Thẻ',
            dataIndex: 'code',
            key: 'cardCode',
        },
        {
            title: 'Thực Nhận',
            dataIndex: 'receivedAmount',
            key: 'receivedAmount',
            render: (val) => <span className="font-bold text-green-600">{val.toLocaleString()} đ</span>,
        },
        {
            title: 'Mệnh Giá',
            dataIndex: 'amount',
            key: 'amount',
            render: (val) => <span>{val.toLocaleString()} đ</span>,
        },
        {
            title: 'Trạng Thái',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = status === 'success' ? 'success' : status === 'pending' ? 'processing' : 'error';
                let text = status === 'success' ? 'Thành công' : status === 'pending' ? 'Chờ duyệt' : 'Thất bại';
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: 'Thời Gian',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (date) => moment(date).format('HH:mm:ss - DD/MM/YYYY'),
        },
    ];

    const transactionColumns = [
        {
            title: 'ID',
            dataIndex: '_id',
            key: 'id',
            render: (id) => <span className="text-gray-400 text-xs">#{id.slice(-4)}</span>,
        },
        {
            title: 'Mã Giao Dịch',
            dataIndex: 'transCode',
            key: 'transCode',
            render: (code) => <span className="font-bold text-blue-700">{code}</span>,
        },
        {
            title: 'Số Dư Trước',
            dataIndex: 'balanceBefore',
            key: 'balanceBefore',
            render: (val) => <span>{val.toLocaleString()} đ</span>,
        },
        {
            title: 'Số Tiền',
            dataIndex: 'amount',
            key: 'amount',
            render: (val, record) => (
                <span className={`font-bold ${record.type === 'DEPOSIT' ? 'text-green-600' : 'text-red-600'}`}>
                    {record.type === 'DEPOSIT' ? '+' : '-'}
                    {val.toLocaleString()} đ
                </span>
            ),
        },
        {
            title: 'Số Dư Sau',
            dataIndex: 'balanceAfter',
            key: 'balanceAfter',
            render: (val) => <span>{val.toLocaleString()} đ</span>,
        },
        {
            title: 'Nội Dung',
            dataIndex: 'content',
            key: 'content',
            width: '30%',
        },
        {
            title: 'Thời Gian',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (date) => moment(date).format('HH:mm:ss - DD/MM/YYYY'),
        },
    ];

    const StatCard = ({ title, value, gradient, icon: Icon, unit = 'đ' }) => (
        <div
            className={`p-6 rounded-xl shadow-lg border border-opacity-20 border-white text-white ${gradient} relative overflow-hidden group hover:scale-[1.02] transition-transform duration-300`}
        >
            <div className="absolute right-[-20px] top-[-20px] opacity-10 group-hover:scale-110 transition-transform">
                <Icon size={120} />
            </div>
            <div className="relative z-10 flex flex-col h-full justify-between">
                <div>
                    <h3 className="text-sm font-medium opacity-80 uppercase tracking-wider">{title}</h3>
                    <div className="mt-2 flex items-baseline gap-1">
                        <span className="text-3xl font-black">{value.toLocaleString()}</span>
                        <span className="text-lg font-bold">{unit}</span>
                    </div>
                </div>
                <Link to="/deposit/bank">
                    <button className="mt-6 w-fit h-9 px-6 rounded-lg bg-white bg-opacity-90 text-gray-800 text-xs font-bold hover:bg-opacity-100 transition-all uppercase tracking-tight">
                        Nạp Thêm
                    </button>
                </Link>
            </div>
        </div>
    );

    return (
        <div className="min-h-screen bg-[#f8fafc] flex flex-col">
            <Helmet>
                <title>Lịch sử giao dịch | {dataWebsite?.nameWebsite || 'Website'}</title>
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="flex-grow container mx-auto px-4 py-8">
                {/* Stats Cards Section */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
                    <StatCard
                        title="Số Tiền Hiện Có"
                        value={stats.balance}
                        gradient="bg-gradient-to-br from-emerald-400 to-teal-500"
                        icon={Wallet}
                    />
                    <StatCard
                        title="Số Tiền Đã Nạp"
                        value={stats.totalDeposited}
                        gradient="bg-gradient-to-br from-blue-500 to-indigo-600"
                        icon={ArrowUpRight}
                    />
                    <StatCard
                        title="Số Tiền Đã Tiêu"
                        value={stats.totalSpent}
                        gradient="bg-gradient-to-br from-gray-800 to-gray-950"
                        icon={ArrowDownLeft}
                    />
                    <StatCard
                        title={`Tổng Nạp Tháng ${moment().format('MM/YYYY')}`}
                        value={stats.totalDepositedMonth}
                        gradient="bg-gradient-to-br from-sky-400 to-blue-500"
                        icon={History}
                    />
                </div>

                {/* Card Deposit History Table */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-8">
                    <div className="p-6 border-b border-gray-50 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <h2 className="text-xl font-black text-gray-800 uppercase tracking-tight">Lịch Sử Nạp Thẻ</h2>
                        <div className="flex items-center gap-2">
                            <Input
                                placeholder="Tìm kiếm..."
                                prefix={<Search size={16} className="text-gray-400" />}
                                className="w-full sm:w-64 h-10 rounded-lg"
                                onChange={(e) => setSearchText(e.target.value)}
                            />
                            {/* <Button type="primary" className="h-10 px-4 bg-orange-600">
                                <Search size={18} />
                            </Button> */}
                        </div>
                    </div>
                    <div className="overflow-x-auto">
                        <Table
                            columns={depositColumns}
                            dataSource={deposits}
                            loading={loading}
                            rowKey="_id"
                            pagination={{ pageSize: 10, showSizeChanger: false }}
                            className="custom-table"
                        />
                    </div>
                </div>

                {/* Transaction History Table */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                    <div className="p-6 border-b border-gray-50 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <h2 className="text-xl font-black text-gray-800 uppercase tracking-tight">Lịch Sử Giao Dịch</h2>
                        <div className="flex items-center gap-2">
                            <Input
                                placeholder="Tìm kiếm..."
                                prefix={<Search size={16} className="text-gray-400" />}
                                className="w-full sm:w-64 h-10 rounded-lg"
                                onChange={(e) => setSearchText(e.target.value)}
                            />
                        </div>
                    </div>
                    <div className="overflow-x-auto">
                        <Table
                            columns={transactionColumns}
                            dataSource={transactions}
                            loading={loading}
                            rowKey="_id"
                            pagination={{ pageSize: 10, showSizeChanger: false }}
                            className="custom-table"
                        />
                    </div>
                </div>
            </main>

            <Footer />

            <style jsx="true">{`
                .custom-table .ant-table-thead > tr > th {
                    background: #f8fafc;
                    font-weight: 800;
                    text-transform: uppercase;
                    font-size: 11px;
                    letter-spacing: 0.05em;
                    color: #64748b;
                    padding: 16px;
                }
                .custom-table .ant-table-tbody > tr > td {
                    padding: 16px;
                    font-weight: 500;
                    color: #1e293b;
                }
                .custom-table .ant-pagination {
                    margin: 16px !important;
                }
            `}</style>
        </div>
    );
};

export default TransactionHistory;
