import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { requestGetProductById } from '../config/product';
import { requestBuyAccount } from '../config/order';
import { requestApplyDiscount } from '../config/discount';
import { CheckCircle, Shield, ChevronRight, Home, Copy, Image as ImageIcon, ShoppingCart, Tag } from 'lucide-react';
import { toast } from 'react-toastify';
import { Modal, Button, Result, Input } from 'antd';
import { useStore } from '../hooks/useStore';
import { Helmet } from 'react-helmet';

function DetailProduct() {
    const { id } = useParams();
    const { dataWebsite } = useStore();
    const [product, setProduct] = useState(null);
    const [loading, setLoading] = useState(true);
    const [selectedImage, setSelectedImage] = useState('');
    const [isBuyModalOpen, setIsBuyModalOpen] = useState(false);
    const [isProcessing, setIsProcessing] = useState(false);
    const [purchasedAccount, setPurchasedAccount] = useState(null);
    // Discount states
    const [discountCode, setDiscountCode] = useState('');
    const [discountInfo, setDiscountInfo] = useState(null);
    const [isApplyingDiscount, setIsApplyingDiscount] = useState(false);

    useEffect(() => {
        const fetchProduct = async () => {
            try {
                const res = await requestGetProductById(id);
                setProduct(res.metadata);
                if (res.metadata.images && res.metadata.images.length > 0) {
                    setSelectedImage(res.metadata.images[0]);
                }
            } catch (error) {
                console.error(error);
                toast.error('Không thể tải thông tin sản phẩm!');
            } finally {
                setLoading(false);
            }
        };

        if (id) {
            fetchProduct();
        }
    }, [id]);

    const handleCopyId = () => {
        if (product) {
            navigator.clipboard.writeText(product.title);
            toast.success('Đã sao chép mã số!');
        }
    };

    const handleApplyDiscount = async () => {
        if (!discountCode.trim()) {
            toast.error('Vui lòng nhập mã giảm giá!');
            return;
        }
        setIsApplyingDiscount(true);
        try {
            const res = await requestApplyDiscount(discountCode, product.price);
            setDiscountInfo(res.metadata);
            toast.success('Áp dụng mã giảm giá thành công!');
        } catch (error) {
            const msg = error.response?.data?.message || 'Mã giảm giá không hợp lệ!';
            toast.error(msg);
            setDiscountInfo(null);
        } finally {
            setIsApplyingDiscount(false);
        }
    };

    const handleRemoveDiscount = () => {
        setDiscountCode('');
        setDiscountInfo(null);
    };

    const handleBuy = async () => {
        setIsProcessing(true);
        try {
            const res = await requestBuyAccount(product._id, discountInfo ? discountCode : null);
            setPurchasedAccount(res.metadata.account);
            setProduct((prev) => ({ ...prev, status: 'sold' }));
            toast.success('Mua tài khoản thành công!');
            // Reset discount
            setDiscountCode('');
            setDiscountInfo(null);
        } catch (error) {
            console.error(error);
            const msg = error.response?.data?.message || 'Có lỗi xảy ra khi mua hàng';
            toast.error(msg);
        } finally {
            setIsProcessing(false);
            setIsBuyModalOpen(false);
        }
    };

    if (loading) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col">
                <Header />
                <div className="flex-1 flex items-center justify-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-orange-500"></div>
                </div>
                <Footer />
            </div>
        );
    }

    if (!product) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col">
                <Header />
                <div className="flex-1 flex flex-col items-center justify-center text-gray-500">
                    <p className="text-xl font-semibold">Sản phẩm không tồn tại!</p>
                    <Link to="/" className="mt-4 text-orange-500 hover:underline">
                        Về trang chủ
                    </Link>
                </div>
                <Footer />
            </div>
        );
    }

    const imageUrl = (img) => `${img}`;

    return (
        <div className="min-h-screen bg-gray-50 font-sans">
            <Helmet>
                <title>
                    {product.title
                        ? `Tài khoản #${product.title} | ${dataWebsite?.nameWebsite || 'Website'}`
                        : dataWebsite?.nameWebsite || 'Website'}
                </title>
                <meta name="description" content={`Chi tiết tài khoản game #${product.title}`} />
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="container mx-auto px-4 py-8">
                {/* Breadcrumb */}
                <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6 overflow-x-auto whitespace-nowrap pb-2">
                    <Link to="/" className="flex items-center hover:text-orange-500 transition-colors">
                        <Home size={16} className="mr-1" />
                        Trang chủ
                    </Link>
                    <ChevronRight size={14} />
                    <Link to={`/category/${product.categoryId}`} className="hover:text-orange-500 transition-colors">
                        Danh mục
                    </Link>
                    <ChevronRight size={14} />
                    <span className="text-gray-800 font-medium truncate max-w-[200px]">Mã số #{product.title}</span>
                </nav>

                <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                    {/* Left Column: Images */}
                    <div className="lg:col-span-7 space-y-4">
                        <div className="relative aspect-video bg-gray-200 rounded-2xl overflow-hidden shadow-lg border border-gray-100 group">
                            {selectedImage ? (
                                <img
                                    src={imageUrl(selectedImage)}
                                    alt={product.title}
                                    className="w-full h-full object-contain bg-black/5"
                                />
                            ) : (
                                <div className="w-full h-full flex items-center justify-center text-gray-400">
                                    <ImageIcon size={48} />
                                </div>
                            )}

                            {/* Status Badge */}
                            <div
                                className={`absolute top-4 left-4 px-4 py-1.5 rounded-full text-sm font-bold shadow-md ${
                                    product.status === 'available' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
                                }`}
                            >
                                {product.status === 'available' ? 'Đang bán' : 'Đã bán'}
                            </div>
                        </div>

                        {/* Thumbnails */}
                        {product.images && product.images.length > 1 && (
                            <div className="grid grid-cols-5 gap-2 sm:gap-4 select-none">
                                {product.images.map((img, index) => (
                                    <div
                                        key={index}
                                        onClick={() => setSelectedImage(img)}
                                        className={`cursor-pointer aspect-square rounded-lg overflow-hidden border-2 transition-all ${
                                            selectedImage === img
                                                ? 'border-orange-500 shadow-md ring-2 ring-orange-200'
                                                : 'border-transparent hover:border-gray-300'
                                        }`}
                                    >
                                        <img
                                            src={imageUrl(img)}
                                            alt={`Thumbnail ${index}`}
                                            className="w-full h-full object-cover"
                                        />
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Right Column: Info & Action */}
                    <div className="lg:col-span-5 space-y-6">
                        {purchasedAccount ? (
                            <div className="bg-white rounded-2xl shadow-sm border border-green-200 p-6">
                                <Result
                                    status="success"
                                    title="Mua hàng thành công!"
                                    subTitle="Vui lòng lưu lại thông tin tài khoản bên dưới."
                                />

                                <Link to="/history/purchased">
                                    <Button
                                        type="primary"
                                        className="w-full h-12 mt-6 rounded-lg bg-emerald-500 border-none font-bold"
                                    >
                                        LỊCH SỬ MUA HÀNG
                                    </Button>
                                </Link>
                            </div>
                        ) : (
                            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
                                <h1 className="text-2xl font-bold text-gray-800 mb-2 truncate" title={product.title}>
                                    Tài khoản mã số #{product.title}
                                </h1>

                                <div className="flex items-center gap-2 text-sm text-gray-500 mb-6">
                                    <span>Mã số:</span>
                                    <span className="font-mono bg-gray-100 px-2 py-0.5 rounded text-gray-700 font-bold flex items-center gap-1">
                                        {product.title}
                                        <button
                                            onClick={handleCopyId}
                                            className="hover:text-orange-500 transition-colors"
                                            title="Sao chép"
                                        >
                                            <Copy size={12} />
                                        </button>
                                    </span>
                                </div>

                                <div className="text-4xl font-black text-red-600 mb-6">
                                    {product.price?.toLocaleString('vi-VN')} đ
                                </div>

                                <div className="space-y-4 mb-8">
                                    {product.info &&
                                        Object.entries(product.info).map(([key, value]) => (
                                            <div
                                                key={key}
                                                className="flex items-center justify-between border-b border-dashed border-gray-100 pb-3 last:border-0 last:pb-0"
                                            >
                                                <span className="text-gray-600 font-medium flex items-center gap-2">
                                                    <CheckCircle size={16} className="text-green-500" />
                                                    {key}
                                                </span>
                                                <span className="font-bold text-gray-800">{value}</span>
                                            </div>
                                        ))}
                                </div>

                                {/* Action Buttons */}
                                <div className="space-y-3">
                                    {product.status === 'available' ? (
                                        <button
                                            className="w-full bg-gradient-to-r from-orange-500 to-red-600 text-white font-bold text-lg py-4 rounded-xl shadow-lg hover:shadow-xl hover:from-orange-600 hover:to-red-700 transition-all transform active:scale-[0.98] flex items-center justify-center gap-2"
                                            onClick={() => setIsBuyModalOpen(true)}
                                        >
                                            <ShoppingCart size={24} />
                                            MUA NGAY
                                        </button>
                                    ) : (
                                        <button
                                            disabled
                                            className="w-full bg-gray-300 text-gray-500 font-bold text-lg py-4 rounded-xl cursor-not-allowed flex items-center justify-center gap-2"
                                        >
                                            <Shield size={24} />
                                            ĐÃ BÁN
                                        </button>
                                    )}
                                    <Link to="/deposit/bank">
                                        <button className="w-full bg-blue-50 text-blue-600 font-bold py-3 rounded-xl hover:bg-blue-100 transition-colors">
                                            Nạp tiền vào tài khoản
                                        </button>
                                    </Link>
                                </div>
                            </div>
                        )}

                        {/* Security Badge */}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="bg-green-50 rounded-xl p-4 flex flex-col items-center text-center gap-2 border border-green-100">
                                <Shield className="text-green-600" size={32} />
                                <span className="text-sm font-bold text-green-800">Bảo mật tuyệt đối</span>
                            </div>
                            <div className="bg-blue-50 rounded-xl p-4 flex flex-col items-center text-center gap-2 border border-blue-100">
                                <CheckCircle className="text-blue-600" size={32} />
                                <span className="text-sm font-bold text-blue-800">Đúng như mô tả</span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Buy Confirmation Modal */}
                <Modal
                    title={<span className="text-xl font-bold">Xác nhận mua tài khoản</span>}
                    open={isBuyModalOpen}
                    onOk={handleBuy}
                    onCancel={() => {
                        setIsBuyModalOpen(false);
                        setDiscountCode('');
                        setDiscountInfo(null);
                    }}
                    confirmLoading={isProcessing}
                    okText="Xác nhận mua"
                    cancelText="Hủy bỏ"
                    okButtonProps={{
                        className: 'bg-orange-600 hover:bg-orange-700 font-bold h-10 border-none',
                        size: 'large',
                    }}
                    cancelButtonProps={{ className: 'font-bold h-10', size: 'large' }}
                >
                    <div className="py-4">
                        <p className="text-gray-600 mb-4">
                            Bạn có chắc chắn muốn mua tài khoản này không? Số tiền sẽ được trừ trực tiếp vào tài khoản
                            của bạn.
                        </p>

                        {/* Discount Code Input */}
                        <div className="mb-4 p-4 bg-gray-50 rounded-xl border border-gray-200">
                            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                                <Tag size={16} />
                                Mã giảm giá (nếu có)
                            </label>
                            <div className="flex gap-2">
                                <Input
                                    placeholder="Nhập mã giảm giá"
                                    value={discountCode}
                                    onChange={(e) => setDiscountCode(e.target.value.toUpperCase())}
                                    disabled={!!discountInfo}
                                    className="flex-1"
                                    style={{ textTransform: 'uppercase' }}
                                />
                                {!discountInfo ? (
                                    <Button
                                        type="primary"
                                        onClick={handleApplyDiscount}
                                        loading={isApplyingDiscount}
                                        className="bg-blue-500"
                                    >
                                        Áp dụng
                                    </Button>
                                ) : (
                                    <Button onClick={handleRemoveDiscount} danger>
                                        Hủy mã
                                    </Button>
                                )}
                            </div>
                            {discountInfo && (
                                <div className="mt-2 text-sm text-green-600 font-medium">
                                    ✓ Đã áp dụng mã {discountInfo.code} - Giảm{' '}
                                    {discountInfo.discountAmount.toLocaleString('vi-VN')}đ
                                </div>
                            )}
                        </div>

                        {/* Price Breakdown */}
                        <div className="p-4 bg-orange-50 rounded-xl border border-orange-100">
                            <div className="flex justify-between items-center mb-2">
                                <span className="text-gray-600">Sản phẩm:</span>
                                <span className="font-bold text-gray-800">#{product.title}</span>
                            </div>
                            <div className="flex justify-between items-center mb-2">
                                <span className="text-gray-600">Giá gốc:</span>
                                <span
                                    className={`font-bold ${discountInfo ? 'line-through text-gray-400' : 'text-gray-800'}`}
                                >
                                    {product.price?.toLocaleString('vi-VN')} đ
                                </span>
                            </div>
                            {discountInfo && (
                                <div className="flex justify-between items-center mb-2">
                                    <span className="text-green-600">Giảm giá:</span>
                                    <span className="font-bold text-green-600">
                                        -{discountInfo.discountAmount.toLocaleString('vi-VN')} đ
                                    </span>
                                </div>
                            )}
                            <div className="border-t border-orange-200 pt-2 mt-2">
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-700 font-medium">Thanh toán:</span>
                                    <span className="text-xl font-black text-red-600">
                                        {(discountInfo ? discountInfo.finalPrice : product.price)?.toLocaleString(
                                            'vi-VN',
                                        )}{' '}
                                        đ
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </Modal>

                {/* Description Section */}
                {product.description && (
                    <div className="mt-8 bg-white rounded-2xl shadow-sm border border-gray-100 p-6 md:p-8">
                        <h2 className="text-xl font-bold text-gray-800 mb-4 border-b pb-4">Mô tả sản phẩm</h2>
                        <div
                            className="prose max-w-none text-gray-600"
                            dangerouslySetInnerHTML={{ __html: product.description.replace(/\n/g, '<br />') }}
                        />
                    </div>
                )}
            </main>

            <footer className="mt-12">
                <Footer />
            </footer>
        </div>
    );
}

export default DetailProduct;
