import { useState, useEffect, useRef } from 'react';
import { message, Modal, Spin } from 'antd';
import { useStore } from '../hooks/useStore';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { getWheelConfig, spinWheel, getSpinHistory } from '../config/luckyWheel';
import { useNavigate } from 'react-router-dom';

const LuckyWheel = () => {
    const { dataUser, setDataUser } = useStore();
    const navigate = useNavigate();
    const [config, setConfig] = useState(null);
    const [loading, setLoading] = useState(true);
    const [spinning, setSpinning] = useState(false);
    const [rotation, setRotation] = useState(0);
    const [history, setHistory] = useState([]);
    const [showResult, setShowResult] = useState(false);
    const [result, setResult] = useState(null);
    const canvasRef = useRef(null);

    useEffect(() => {
        fetchConfig();
        if (dataUser?._id) {
            fetchHistory();
        }
    }, [dataUser]);

    useEffect(() => {
        if (config?.prizes && canvasRef.current) {
            drawWheel();
        }
    }, [config, rotation]);

    const fetchConfig = async () => {
        try {
            const res = await getWheelConfig();
            setConfig(res.metadata);
        } catch (error) {
            message.error('Không thể tải cấu hình vòng quay');
        } finally {
            setLoading(false);
        }
    };

    const fetchHistory = async () => {
        try {
            const res = await getSpinHistory();
            setHistory(res.metadata);
        } catch (error) {
            console.error('Error fetching history:', error);
        }
    };

    const drawWheel = () => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const radius = Math.min(centerX, centerY) - 10;
        const prizes = config.prizes || [];
        const sliceAngle = (2 * Math.PI) / prizes.length;

        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(centerX, centerY);
        // Canvas is rotated via CSS, no need to rotate context
        // ctx.rotate((rotation * Math.PI) / 180);

        // Draw slices
        prizes.forEach((prize, index) => {
            const startAngle = index * sliceAngle - Math.PI / 2;
            const endAngle = startAngle + sliceAngle;

            // Slice background
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.arc(0, 0, radius, startAngle, endAngle);
            ctx.closePath();

            // Gradient fill
            const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, radius);
            gradient.addColorStop(0, lightenColor(prize.color, 30));
            gradient.addColorStop(1, prize.color);
            ctx.fillStyle = gradient;
            ctx.fill();

            // Slice border
            ctx.strokeStyle = 'rgba(255,255,255,0.3)';
            ctx.lineWidth = 2;
            ctx.stroke();

            // Prize text
            ctx.save();
            ctx.rotate(startAngle + sliceAngle / 2);
            ctx.textAlign = 'right';
            ctx.fillStyle = '#fff';
            ctx.font = 'bold 14px Arial';
            ctx.shadowColor = 'rgba(0,0,0,0.5)';
            ctx.shadowBlur = 4;
            ctx.fillText(prize.label, radius - 20, 5);
            ctx.restore();
        });

        // Center circle decoration
        const innerRadius = 50;
        const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, innerRadius);
        gradient.addColorStop(0, '#FFD700');
        gradient.addColorStop(0.5, '#FFA500');
        gradient.addColorStop(1, '#FF6B00');

        ctx.beginPath();
        ctx.arc(0, 0, innerRadius, 0, 2 * Math.PI);
        ctx.fillStyle = gradient;
        ctx.fill();
        ctx.strokeStyle = '#fff';
        ctx.lineWidth = 4;
        ctx.stroke();

        // Outer ring
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, 2 * Math.PI);
        ctx.strokeStyle = 'rgba(255,215,0,0.8)';
        ctx.lineWidth = 8;
        ctx.stroke();

        ctx.restore();
    };

    const lightenColor = (color, percent) => {
        const num = parseInt(color.replace('#', ''), 16);
        const amt = Math.round(2.55 * percent);
        const R = Math.min(255, (num >> 16) + amt);
        const G = Math.min(255, ((num >> 8) & 0x00ff) + amt);
        const B = Math.min(255, (num & 0x0000ff) + amt);
        return `rgb(${R},${G},${B})`;
    };

    const handleSpin = async () => {
        if (!dataUser?._id) {
            message.warning('Vui lòng đăng nhập để quay');
            navigate('/login');
            return;
        }

        if (spinning) return;

        try {
            setSpinning(true);
            const res = await spinWheel();
            const { prizeIndex, prize, balanceAfter } = res.metadata;

            const prizeCount = config.prizes.length;
            const prizeAngle = 360 / prizeCount;
            // Angle to position the prize at top (12 o'clock)
            // Initial pos of prize center = index * angle + angle/2
            // We want (Initial + Rotation) % 360 = 0 (top)
            // => Rotation = -Initial = 360 - Initial
            const targetAngle = 360 - (prizeIndex * prizeAngle + prizeAngle / 2);

            setRotation((prev) => {
                const currentRotation = prev % 360; // Normalize current to 0-360
                let spinAngle = targetAngle - currentRotation;

                // Ensure positive spin (clockwise)
                if (spinAngle <= 0) {
                    spinAngle += 360;
                }

                // Add 5 full spins + needed angle
                // Note: We add to 'prev' (drawing value) to keep continuous rotation
                return prev + spinAngle + 360 * 5;
            });

            setTimeout(() => {
                setResult(prize);
                setShowResult(true);
                setSpinning(false);
                setDataUser({ ...dataUser, balance: balanceAfter });
                fetchHistory();
            }, 5000);
        } catch (error) {
            message.error(error.response?.data?.message || 'Có lỗi xảy ra khi quay');
            setSpinning(false);
        }
    };

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
                <Spin size="large" />
            </div>
        );
    }

    if (!config || !config.isActive) {
        return (
            <div className="min-h-screen flex flex-col bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
                <Header />
                <div className="flex-1 flex items-center justify-center pt-16">
                    <div className="text-center">
                        <div className="text-6xl mb-4">🎰</div>
                        <h1 className="text-3xl font-bold text-white mb-2">Vòng quay đang tạm đóng</h1>
                        <p className="text-gray-400">Vui lòng quay lại sau!</p>
                    </div>
                </div>
                <Footer />
            </div>
        );
    }

    const prizes = config.prizes || [];

    return (
        <div className="min-h-screen flex flex-col bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 overflow-hidden">
            <Header />

            {/* Animated background particles */}
            <div className="fixed inset-0 overflow-hidden pointer-events-none">
                {[...Array(20)].map((_, i) => (
                    <div
                        key={i}
                        className="absolute rounded-full bg-yellow-400/20 animate-pulse"
                        style={{
                            width: Math.random() * 10 + 5,
                            height: Math.random() * 10 + 5,
                            left: `${Math.random() * 100}%`,
                            top: `${Math.random() * 100}%`,
                            animationDelay: `${Math.random() * 2}s`,
                            animationDuration: `${Math.random() * 3 + 2}s`,
                        }}
                    />
                ))}
            </div>

            <main className="flex-1 pt-24 pb-12 relative z-10">
                <div className="container mx-auto px-4 max-w-6xl">
                    {/* Header */}
                    <div className="text-center mb-10">
                        <div className="inline-block">
                            <h1 className="text-5xl md:text-6xl font-black text-transparent bg-clip-text bg-gradient-to-r from-yellow-300 via-orange-400 to-pink-500 mb-3 tracking-tight">
                                VÒNG QUAY MAY MẮN
                            </h1>
                            <div className="h-1 w-32 mx-auto bg-gradient-to-r from-yellow-400 to-pink-500 rounded-full" />
                        </div>
                        <p className="text-gray-300 mt-4 text-lg">✨ Thử vận may - Nhận thưởng khủng ✨</p>
                    </div>

                    <div className="flex flex-col lg:flex-row gap-10 items-center justify-center">
                        {/* Wheel Section */}
                        <div className="flex flex-col items-center">
                            {/* Balance Card */}
                            <div className="mb-8 bg-gradient-to-r from-amber-500/20 to-orange-500/20 backdrop-blur-xl border border-amber-400/30 rounded-2xl px-8 py-4 shadow-2xl">
                                <div className="flex items-center gap-3">
                                    <div className="w-12 h-12 rounded-full bg-gradient-to-br from-yellow-400 to-orange-500 flex items-center justify-center shadow-lg">
                                        <span className="text-2xl">💰</span>
                                    </div>
                                    <div>
                                        <p className="text-amber-200/70 text-sm font-medium">Số dư của bạn</p>
                                        <p className="text-2xl font-bold text-white">
                                            {(dataUser?.balance || 0).toLocaleString()}
                                            <span className="text-amber-400 ml-1">đ</span>
                                        </p>
                                    </div>
                                </div>
                            </div>

                            {/* Wheel Container */}
                            <div className="relative">
                                {/* Glow effect */}
                                <div className="absolute inset-0 bg-gradient-to-r from-yellow-400 via-orange-500 to-pink-500 rounded-full blur-3xl opacity-30 animate-pulse" />

                                {/* Outer decorative ring */}
                                <div className="relative p-3 bg-gradient-to-br from-yellow-400 via-orange-500 to-pink-500 rounded-full shadow-2xl">
                                    <div className="p-2 bg-slate-800 rounded-full">
                                        {/* Arrow/Pointer */}
                                        <div className="absolute -top-2 left-1/2 transform -translate-x-1/2 z-20">
                                            <div className="relative">
                                                <div className="w-0 h-0 border-l-[18px] border-l-transparent border-r-[18px] border-r-transparent border-t-[35px] border-t-yellow-400 drop-shadow-2xl" />
                                                <div className="absolute top-[2px] left-1/2 -translate-x-1/2 w-0 h-0 border-l-[12px] border-l-transparent border-r-[12px] border-r-transparent border-t-[24px] border-t-yellow-200" />
                                            </div>
                                        </div>

                                        {/* Canvas Wheel */}
                                        <canvas
                                            ref={canvasRef}
                                            width={340}
                                            height={340}
                                            className="rounded-full"
                                            style={{
                                                transform: `rotate(${rotation}deg)`,
                                                transition: spinning
                                                    ? 'transform 5s cubic-bezier(0.17, 0.67, 0.12, 0.99)'
                                                    : 'none',
                                            }}
                                        />

                                        {/* Center Spin Button */}
                                        <button
                                            onClick={handleSpin}
                                            disabled={spinning}
                                            className={`absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-24 h-24 rounded-full shadow-2xl transition-all duration-300 ${
                                                spinning
                                                    ? 'cursor-not-allowed scale-90'
                                                    : 'hover:scale-110 active:scale-95 cursor-pointer'
                                            }`}
                                            style={{
                                                background: spinning
                                                    ? 'linear-gradient(135deg, #6B7280, #4B5563)'
                                                    : 'linear-gradient(135deg, #FFD700, #FFA500, #FF6B00)',
                                                boxShadow: spinning
                                                    ? 'none'
                                                    : '0 0 30px rgba(255, 165, 0, 0.6), inset 0 2px 10px rgba(255,255,255,0.3)',
                                            }}
                                        >
                                            <span className="text-white font-black text-lg drop-shadow-lg">
                                                {spinning ? '...' : 'QUAY'}
                                            </span>
                                        </button>
                                    </div>
                                </div>

                                {/* Decorative dots around wheel */}
                                {[...Array(12)].map((_, i) => (
                                    <div
                                        key={i}
                                        className="absolute w-4 h-4 rounded-full bg-yellow-400 shadow-lg animate-pulse"
                                        style={{
                                            top: `${50 + 48 * Math.sin((i * 30 * Math.PI) / 180)}%`,
                                            left: `${50 + 48 * Math.cos((i * 30 * Math.PI) / 180)}%`,
                                            transform: 'translate(-50%, -50%)',
                                            animationDelay: `${i * 0.1}s`,
                                        }}
                                    />
                                ))}
                            </div>

                            {/* Spin Info */}
                            <div className="mt-8 text-center">
                                <div className="inline-flex items-center gap-2 bg-gradient-to-r from-pink-500/20 to-purple-500/20 backdrop-blur-xl border border-pink-400/30 rounded-full px-6 py-3">
                                    <span className="text-2xl">💎</span>
                                    <span className="text-white font-bold text-xl">
                                        Phí quay:{' '}
                                        <span className="text-pink-400">{config.spinCost.toLocaleString()}đ</span>
                                    </span>
                                </div>
                                {config.maxSpinsPerDay > 0 && (
                                    <p className="text-gray-400 text-sm mt-2">
                                        ⏰ Giới hạn: {config.maxSpinsPerDay} lượt/ngày
                                    </p>
                                )}
                            </div>

                            {/* Main Spin Button */}
                            <button
                                onClick={handleSpin}
                                disabled={spinning}
                                className={`mt-6 group relative overflow-hidden rounded-2xl transition-all duration-300 ${
                                    spinning ? 'opacity-60 cursor-not-allowed' : 'hover:scale-105 active:scale-95'
                                }`}
                            >
                                <div className="absolute inset-0 bg-gradient-to-r from-green-400 via-emerald-500 to-teal-500 animate-gradient-x" />
                                <div className="relative px-12 py-4 flex items-center gap-3">
                                    <span className="text-2xl">{spinning ? '🎰' : '🎯'}</span>
                                    <span className="text-white font-black text-xl tracking-wide">
                                        {spinning ? 'ĐANG QUAY...' : `QUAY NGAY`}
                                    </span>
                                </div>
                            </button>
                        </div>

                        {/* Right Panel */}
                        <div className="w-full lg:w-96 space-y-6">
                            {/* History Card */}
                            <div className="bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl p-6 shadow-2xl">
                                <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
                                    <span className="text-2xl">📜</span> Lịch sử quay
                                </h2>
                                {dataUser?._id ? (
                                    history.length > 0 ? (
                                        <div className="space-y-2 max-h-64 overflow-y-auto custom-scrollbar">
                                            {history.slice(0, 8).map((item, index) => (
                                                <div
                                                    key={item._id || index}
                                                    className="flex items-center justify-between p-3 rounded-xl bg-white/5"
                                                >
                                                    <div>
                                                        <p
                                                            className={`font-bold ${
                                                                item.reward > 0 ? 'text-green-400' : 'text-gray-400'
                                                            }`}
                                                        >
                                                            {item.rewardLabel}
                                                        </p>
                                                        <p className="text-gray-500 text-xs">
                                                            {new Date(item.createdAt).toLocaleString('vi-VN')}
                                                        </p>
                                                    </div>
                                                    <span className="text-gray-400 text-sm">
                                                        -{item.spinCost.toLocaleString()}đ
                                                    </span>
                                                </div>
                                            ))}
                                        </div>
                                    ) : (
                                        <p className="text-gray-500 text-center py-8">Chưa có lượt quay nào</p>
                                    )
                                ) : (
                                    <div className="text-center py-8">
                                        <p className="text-gray-400 mb-3">Đăng nhập để xem lịch sử</p>
                                        <button
                                            onClick={() => navigate('/login')}
                                            className="px-6 py-2 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-full font-medium hover:opacity-90 transition-opacity"
                                        >
                                            Đăng nhập
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </main>

            <Footer />

            {/* Result Modal */}
            <Modal
                open={showResult}
                onCancel={() => setShowResult(false)}
                footer={null}
                centered
                width={420}
                className="lucky-modal"
            >
                <div className="text-center py-6">
                    {result?.value > 0 ? (
                        <>
                            <div className="relative inline-block">
                                <div className="text-8xl animate-bounce">🎉</div>
                                <div className="absolute -top-2 -right-2 text-4xl animate-ping">✨</div>
                            </div>
                            <h2 className="text-3xl font-black text-transparent bg-clip-text bg-gradient-to-r from-green-400 to-emerald-500 mt-4 mb-2">
                                CHÚC MỪNG!
                            </h2>
                            <p className="text-gray-600 mb-4">Bạn đã trúng thưởng:</p>
                            <div className="inline-block px-8 py-4 bg-gradient-to-r from-orange-400 to-pink-500 rounded-2xl">
                                <span className="text-3xl font-black text-white">{result.label}</span>
                            </div>
                        </>
                    ) : (
                        <>
                            <div className="text-8xl mb-4">😢</div>
                            <h2 className="text-2xl font-bold text-gray-700 mb-2">Tiếc quá!</h2>
                            <p className="text-gray-500">Chúc bạn may mắn lần sau nhé!</p>
                        </>
                    )}
                    <button
                        onClick={() => setShowResult(false)}
                        className="mt-8 px-10 py-3 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-full font-bold text-lg hover:opacity-90 transition-opacity shadow-xl"
                    >
                        Đóng
                    </button>
                </div>
            </Modal>

            <style>{`
                @keyframes gradient-x {
                    0%, 100% { background-position: 0% 50%; }
                    50% { background-position: 100% 50%; }
                }
                .animate-gradient-x {
                    background-size: 200% 200%;
                    animation: gradient-x 3s ease infinite;
                }
                .custom-scrollbar::-webkit-scrollbar {
                    width: 4px;
                }
                .custom-scrollbar::-webkit-scrollbar-track {
                    background: rgba(255,255,255,0.05);
                    border-radius: 10px;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb {
                    background: rgba(255,255,255,0.2);
                    border-radius: 10px;
                }
                .lucky-modal .ant-modal-content {
                    border-radius: 24px;
                    overflow: hidden;
                }
                .lucky-modal .ant-modal-close {
                    top: 16px;
                    right: 16px;
                }
            `}</style>
        </div>
    );
};

export default LuckyWheel;
