import { useRef, useEffect, useState } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area } from 'recharts';
import {
    Users,
    ShoppingCart,
    CreditCard,
    DollarSign,
    Package,
    ArrowUpRight,
    ArrowDownRight,
    Activity,
    Clock,
} from 'lucide-react';
import { getDashboardStats } from '../../config/dashboard';
import { formatPrice } from '../../utils/formatPrice';
import moment from 'moment';
import { Tag, Table, Skeleton } from 'antd';

const Dashboard = () => {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchStats = async () => {
            try {
                const res = await getDashboardStats();
                setStats(res.metadata);
            } catch (error) {
                console.error('Failed to fetch dashboard stats', error);
            } finally {
                setLoading(false);
            }
        };

        fetchStats();
    }, []);

    if (loading) {
        return <Skeleton active paragraph={{ rows: 10 }} />;
    }

    if (!stats) return <div>Không có dữ liệu</div>;

    const { stats: mainStats, chart, recent } = stats;

    // Stat Cards Data
    const statCards = [
        {
            title: 'Tổng Doanh Thu',
            value: formatPrice(mainStats.revenue.sales),
            icon: DollarSign,
            color: 'bg-green-500',
            trend: '+12.5%',
            trendUp: true,
            desc: 'Từ bán tài khoản',
        },
        {
            title: 'Tổng Nạp Tiền',
            value: formatPrice(mainStats.revenue.deposit),
            icon: CreditCard,
            color: 'bg-blue-500',
            trend: '+8.2%',
            trendUp: true,
            desc: 'Tổng tiền nạp vào hệ thống',
        },
        {
            title: 'Thành Viên',
            value: mainStats.users.total,
            icon: Users,
            color: 'bg-purple-500',
            trend: `+${mainStats.users.newToday} hôm nay`,
            trendUp: true,
            desc: 'Tổng số thành viên',
        },
        {
            title: 'Sản Phẩm',
            value: mainStats.products.total,
            icon: Package,
            color: 'bg-orange-500',
            desc: `${mainStats.products.available} đang bán`,
            trend: `${mainStats.products.sold} đã bán`,
            trendUp: true,
        },
    ];

    const columnsDeposits = [
        {
            title: 'Mã GD',
            dataIndex: 'code',
            key: 'code',
            render: (text) => <span className="font-mono text-xs">{text || 'N/A'}</span>,
        },
        {
            title: 'Người nạp',
            dataIndex: ['userId', 'fullName'],
            key: 'user',
        },
        {
            title: 'Số tiền',
            dataIndex: 'receivedAmount',
            key: 'amount',
            render: (amount) => <span className="text-green-600 font-bold">+{formatPrice(amount)}</span>,
        },
        {
            title: 'Thời gian',
            dataIndex: 'createdAt',
            key: 'time',
            render: (date) => <span className="text-gray-500 text-xs">{moment(date).fromNow()}</span>,
        },
        {
            title: 'Trạng thái',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={status === 'success' ? 'green' : status === 'pending' ? 'orange' : 'red'}>
                    {status.toUpperCase()}
                </Tag>
            ),
        },
    ];

    const columnsOrders = [
        {
            title: 'Khách hàng',
            dataIndex: ['userId', 'fullName'],
            key: 'user',
        },
        {
            title: 'Sản phẩm',
            dataIndex: ['productId', 'title'],
            key: 'product',
            render: (text) => (
                <span className="truncate max-w-[150px] block" title={text}>
                    {text}
                </span>
            ),
        },
        {
            title: 'Giá',
            dataIndex: 'price',
            key: 'price',
            render: (price) => <span className="font-bold">{formatPrice(price)}</span>,
        },
        {
            title: 'Thời gian',
            dataIndex: 'createdAt',
            key: 'time',
            render: (date) => <span className="text-gray-500 text-xs">{moment(date).fromNow()}</span>,
        },
    ];

    return (
        <div className="space-y-6">
            <h2 className="text-2xl font-bold text-gray-800">Dashboard Tổng Quan</h2>

            {/* Stats Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {statCards.map((stat, index) => (
                    <div
                        key={index}
                        className="bg-white rounded-xl shadow-sm p-6 border border-gray-100 transition-all hover:shadow-md"
                    >
                        <div className="flex justify-between items-start mb-4">
                            <div className={`p-3 rounded-lg ${stat.color} bg-opacity-10`}>
                                <stat.icon className={`h-6 w-6 ${stat.color.replace('bg-', 'text-')}`} />
                            </div>
                            {stat.trend && (
                                <div
                                    className={`flex items-center text-xs font-semibold ${stat.trendUp ? 'text-green-600' : 'text-red-600'} bg-green-50 px-2 py-1 rounded-full`}
                                >
                                    {stat.trendUp ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
                                    {stat.trend}
                                </div>
                            )}
                        </div>
                        <h3 className="text-gray-500 text-sm font-medium mb-1">{stat.title}</h3>
                        <p className="text-2xl font-bold text-gray-900">{stat.value}</p>
                        <p className="text-xs text-gray-400 mt-2">{stat.desc}</p>
                    </div>
                ))}
            </div>

            {/* Charts Section */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="lg:col-span-2 bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                    <h3 className="text-lg font-bold text-gray-800 mb-6 flex items-center gap-2">
                        <Activity size={20} className="text-blue-500" />
                        Doanh thu 30 ngày qua
                    </h3>
                    <div className="h-[300px] w-full">
                        <ResponsiveContainer width="100%" height="100%">
                            <AreaChart data={chart.sales}>
                                <defs>
                                    <linearGradient id="colorSales" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#10B981" stopOpacity={0.2} />
                                        <stop offset="95%" stopColor="#10B981" stopOpacity={0} />
                                    </linearGradient>
                                </defs>
                                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E5E7EB" />
                                <XAxis
                                    dataKey="_id"
                                    tick={{ fontSize: 12, fill: '#6B7280' }}
                                    axisLine={false}
                                    tickLine={false}
                                />
                                <YAxis
                                    tick={{ fontSize: 12, fill: '#6B7280' }}
                                    axisLine={false}
                                    tickLine={false}
                                    tickFormatter={(value) => `${value / 1000}k`}
                                />
                                <Tooltip
                                    formatter={(value) => formatPrice(value)}
                                    contentStyle={{
                                        borderRadius: '8px',
                                        border: 'none',
                                        boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
                                    }}
                                />
                                <Area
                                    type="monotone"
                                    dataKey="total"
                                    name="Doanh thu"
                                    stroke="#10B981"
                                    strokeWidth={3}
                                    fillOpacity={1}
                                    fill="url(#colorSales)"
                                />
                            </AreaChart>
                        </ResponsiveContainer>
                    </div>
                </div>

                <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                    <h3 className="text-lg font-bold text-gray-800 mb-6 flex items-center gap-2">
                        <Clock size={20} className="text-orange-500" />
                        Hoạt động cần xử lý
                    </h3>
                    <div className="space-y-4">
                        <div className="flex items-center justify-between p-4 bg-orange-50 rounded-lg border border-orange-100">
                            <div>
                                <p className="font-semibold text-orange-800">Duyệt nạp tiền</p>
                                <p className="text-xs text-orange-600">Yêu cầu chưa xử lý</p>
                            </div>
                            <span className="text-2xl font-bold text-orange-600">{mainStats.pending.deposits}</span>
                        </div>
                        {/* Can add more cards here like Pending Orders if applicable */}
                    </div>
                </div>
            </div>

            {/* Recent Tables */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                    <h3 className="text-lg font-bold text-gray-800 mb-4">Giao dịch mua gần đây</h3>
                    <Table
                        columns={columnsOrders}
                        dataSource={recent.orders}
                        rowKey="_id"
                        pagination={false}
                        size="small"
                        className="overflow-hidden"
                    />
                </div>
                <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                    <h3 className="text-lg font-bold text-gray-800 mb-4">Giao dịch nạp gần đây</h3>
                    <Table
                        columns={columnsDeposits}
                        dataSource={recent.deposits}
                        rowKey="_id"
                        pagination={false}
                        size="small"
                        className="overflow-hidden"
                    />
                </div>
            </div>
        </div>
    );
};

export default Dashboard;
