import { useState, useEffect } from 'react';
import { Table, Button, Tag, Space, Modal, Card, Typography, Empty, Rate, Input } from 'antd';
import {
    ShoppingBag,
    Eye,
    Copy,
    Calendar,
    CreditCard,
    ExternalLink,
    Package,
    ShieldCheck,
    Clipboard,
    Star,
} from 'lucide-react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { requestGetOrderHistory } from '../config/order';
import { requestCreatePreviewProduct } from '../config/previewProduct';
import moment from 'moment';
import { toast } from 'react-toastify';
import { useStore } from '../hooks/useStore';
import { Helmet } from 'react-helmet';

const { Title, Text } = Typography;
const { TextArea } = Input;

const PurchasedAccounts = () => {
    const { dataWebsite } = useStore();
    const [loading, setLoading] = useState(true);
    const [history, setHistory] = useState([]);
    const [selectedOrder, setSelectedOrder] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);

    // Review System State
    const [reviewedOrders, setReviewedOrders] = useState([]);
    const [isReviewModalOpen, setIsReviewModalOpen] = useState(false);
    const [reviewRating, setReviewRating] = useState(5);
    const [reviewComment, setReviewComment] = useState('');
    const [reviewingOrder, setReviewingOrder] = useState(null);
    const [submittingReview, setSubmittingReview] = useState(false);

    const handleOpenReview = (order) => {
        setReviewingOrder(order);
        setReviewRating(5);
        setReviewComment('');
        setIsReviewModalOpen(true);
    };

    const handleSubmitReview = async () => {
        if (!reviewingOrder) return;

        if (!reviewComment.trim()) {
            toast.warn('Vui lòng nhập nội dung đánh giá');
            return;
        }

        setSubmittingReview(true);
        try {
            await requestCreatePreviewProduct({
                productId: reviewingOrder.productId._id,
                rating: reviewRating,
                comment: reviewComment,
            });

            toast.success('Đánh giá sản phẩm thành công!');
            setReviewedOrders((prev) => [...prev, reviewingOrder._id]);
            setIsReviewModalOpen(false);
        } catch (error) {
            console.error('Review failed:', error);
            toast.error(error.response?.data?.message || 'Gửi đánh giá thất bại');
        } finally {
            setSubmittingReview(false);
        }
    };

    const fetchHistory = async () => {
        setLoading(true);
        try {
            const res = await requestGetOrderHistory();
            setHistory(res.metadata || []);
        } catch (error) {
            console.error('Failed to fetch history:', error);
            toast.error('Không thể tải lịch sử mua hàng');
        } finally {
            setLoading(false);
        }
    };

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

    const copyToClipboard = (text, type) => {
        navigator.clipboard.writeText(text);
        toast.success(`Đã sao chép ${type}!`);
    };

    const columns = [
        {
            title: 'Mã Đơn',
            dataIndex: '_id',
            key: 'id',
            width: 120,
            render: (id) => (
                <span className="font-mono text-gray-400 text-xs bg-gray-50 px-2 py-1 rounded border border-gray-100 uppercase">
                    #{id.slice(-6).toUpperCase()}
                </span>
            ),
        },
        {
            title: 'Tài Khoản / Mã Nick',
            key: 'product',
            render: (_, record) => (
                <div className="flex flex-col">
                    <span className="font-bold text-gray-800 text-[15px]">
                        {record.productId?.title || 'Sản phẩm đã xóa'}
                    </span>
                    <span className="text-gray-400 text-[11px] uppercase font-bold tracking-tighter">
                        MS: {record.productId?._id?.slice(-8).toUpperCase() || 'N/A'}
                    </span>
                </div>
            ),
        },
        {
            title: 'Giá Tiền',
            dataIndex: 'price',
            key: 'price',
            render: (price) => (
                <span className="font-black text-red-600 text-lg">
                    {price.toLocaleString()} <span className="text-sm font-medium">đ</span>
                </span>
            ),
        },
        {
            title: 'Ngày Mua',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (date) => (
                <div className="flex items-center gap-2 text-gray-500">
                    <Calendar size={14} className="opacity-50" />
                    <span className="text-[13px]">{moment(date).format('DD/MM/YYYY HH:mm')}</span>
                </div>
            ),
        },
        {
            title: 'Trạng Thái',
            key: 'status',
            render: () => (
                <Tag color="#10b981" className="rounded-full px-3 py-0.5 border-none font-bold text-[11px] uppercase">
                    Thành công
                </Tag>
            ),
        },
        {
            title: 'Hành Động',
            key: 'action',
            align: 'right',
            render: (_, record) => (
                <div className="flex flex-col gap-2 scale-90 origin-right">
                    <Button
                        type="primary"
                        className="bg-blue-600 hover:bg-blue-700 h-9 rounded-lg flex items-center justify-center gap-2 font-bold shadow-md shadow-blue-100 w-full"
                        onClick={() => {
                            setSelectedOrder(record);
                            setIsModalOpen(true);
                        }}
                        icon={<Eye size={16} />}
                    >
                        XEM ACC
                    </Button>

                    {!reviewedOrders.includes(record._id) && (
                        <Button
                            className="h-9 rounded-lg flex items-center justify-center gap-2 font-bold border-yellow-400 text-yellow-600 hover:text-yellow-700 hover:border-yellow-500 hover:bg-yellow-50 w-full"
                            onClick={() => handleOpenReview(record)}
                            icon={<Star size={16} />}
                        >
                            ĐÁNH GIÁ
                        </Button>
                    )}
                </div>
            ),
        },
    ];

    return (
        <div className="min-h-screen bg-gray-50/50 flex flex-col font-sans">
            <Helmet>
                <title>Lịch sử mua hàng | {dataWebsite?.nameWebsite || 'Website'}</title>
            </Helmet>
            <header className="pb-16 text-[#333]">
                <Header />
            </header>

            <main className="flex-grow container mx-auto px-4 py-8">
                <div className="max-w-6xl mx-auto">
                    {/* Header Section */}
                    <div className="flex flex-col md:flex-row md:items-end justify-between gap-4 mb-8">
                        <div className="flex items-center gap-4">
                            <div className="w-14 h-14 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center text-white shadow-xl shadow-blue-200 ring-4 ring-white">
                                <ShoppingBag size={28} />
                            </div>
                            <div>
                                <h1 className="text-2xl md:text-3xl font-black text-gray-900 uppercase tracking-tight">
                                    Lịch Sử Mua Nick
                                </h1>
                                <p className="text-gray-500 text-sm md:text-base font-medium">
                                    Quản lý và lấy thông tin các tài khoản đã mua
                                </p>
                            </div>
                        </div>

                        <Card className="bg-white border-none shadow-sm rounded-xl py-0 px-4">
                            <div className="flex items-center gap-4 py-2">
                                <div className="text-right border-r pr-4 border-gray-100">
                                    <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">
                                        Tổng Đơn
                                    </p>
                                    <p className="text-xl font-black text-blue-600 leading-none">{history.length}</p>
                                </div>
                                <div className="text-right">
                                    <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">
                                        Tổng Chi
                                    </p>
                                    <p className="text-xl font-black text-emerald-600 leading-none">
                                        {history.reduce((sum, item) => sum + item.price, 0).toLocaleString()}đ
                                    </p>
                                </div>
                            </div>
                        </Card>
                    </div>

                    {/* Table Section */}
                    <div className="bg-white rounded-3xl shadow-xl shadow-gray-200/50 border border-gray-100 overflow-hidden">
                        <Table
                            columns={columns}
                            dataSource={history}
                            loading={loading}
                            rowKey="_id"
                            pagination={{
                                pageSize: 10,
                                showTotal: (total) => `Tổng cộng ${total} đơn hàng`,
                                className: 'px-6 py-4',
                            }}
                            locale={{
                                emptyText: <Empty description="Bạn chưa mua bất kỳ tài khoản nào" className="py-12" />,
                            }}
                            className="custom-purchased-table"
                        />
                    </div>

                    {/* Security Notice */}
                    <div className="mt-8 bg-blue-50 rounded-2xl p-6 flex flex-col md:flex-row items-center gap-4 border border-blue-100 italic">
                        <div className="p-3 bg-blue-100 rounded-full text-blue-600">
                            <ShieldCheck size={24} />
                        </div>
                        <div className="text-center md:text-left">
                            <p className="text-blue-900 font-bold text-sm">Bảo mật thông tin:</p>
                            <p className="text-blue-700 text-xs">
                                Mọi thông tin tài khoản mua tại hệ thống đều được bảo mật. Chúng tôi khuyến nghị quý
                                khách nên thay đổi thông tin tài khoản (Mật khẩu, Email, SĐT) ngay sau khi nhận được
                                thông tin để đảm bảo an toàn tuyệt đối.
                            </p>
                        </div>
                    </div>
                </div>
            </main>

            <Footer />

            {/* Account Credentials Modal */}
            <Modal
                title={
                    <div className="flex items-center gap-3 pb-3 border-b border-gray-100 w-full">
                        <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center text-blue-600">
                            <Package size={20} />
                        </div>
                        <div>
                            <p className="text-[11px] text-gray-400 uppercase font-black tracking-widest leading-none mb-1">
                                Chi tiết tài khoản
                            </p>
                            <h3 className="text-lg font-bold text-gray-800 leading-none">
                                MS #{selectedOrder?.productId?.title || 'N/A'}
                            </h3>
                        </div>
                    </div>
                }
                open={isModalOpen}
                onCancel={() => setIsModalOpen(false)}
                footer={[
                    <Button
                        key="close"
                        onClick={() => setIsModalOpen(false)}
                        className="h-10 px-8 rounded-lg font-bold border-gray-200 hover:text-blue-600 hover:border-blue-600"
                    >
                        ĐÓNG
                    </Button>,
                ]}
                width={450}
                centered
                className="credential-modal"
            >
                {selectedOrder && (
                    <div className="py-6 space-y-6">
                        {/* Username Block */}
                        <div className="relative group">
                            <div className="absolute -top-2.5 left-4 px-2 bg-white text-[10px] text-gray-400 font-black uppercase tracking-widest z-10">
                                Tài khoản đăng nhập
                            </div>
                            <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-200 group-hover:border-blue-200 transition-colors">
                                <div className="flex-grow">
                                    <Text className="text-xl font-black text-blue-700 block">
                                        {selectedOrder.productId?.account?.username || 'Chưa cập nhật'}
                                    </Text>
                                </div>
                                <Button
                                    className="flex items-center gap-2 font-bold h-10 rounded-xl border-none bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white transition-all shadow-sm"
                                    onClick={() =>
                                        copyToClipboard(selectedOrder.productId?.account?.username, 'tài khoản')
                                    }
                                    icon={<Clipboard size={16} />}
                                >
                                    COPY
                                </Button>
                            </div>
                        </div>

                        {/* Password Block */}
                        <div className="relative group">
                            <div className="absolute -top-2.5 left-4 px-2 bg-white text-[10px] text-gray-400 font-black uppercase tracking-widest z-10">
                                Mật khẩu ứng dụng
                            </div>
                            <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-200 group-hover:border-red-200 transition-colors">
                                <div className="flex-grow">
                                    <Text className="text-xl font-black text-red-600 block">
                                        {selectedOrder.productId?.account?.password || 'Chưa cập nhật'}
                                    </Text>
                                </div>
                                <Button
                                    className="flex items-center gap-2 font-bold h-10 rounded-xl border-none bg-red-50 text-red-600 hover:bg-red-600 hover:text-white transition-all shadow-sm"
                                    onClick={() =>
                                        copyToClipboard(selectedOrder.productId?.account?.password, 'mật khẩu')
                                    }
                                    icon={<Clipboard size={16} />}
                                >
                                    COPY
                                </Button>
                            </div>
                        </div>

                        <div className="p-4 bg-orange-50 rounded-2xl border border-orange-100 flex gap-3">
                            <div className="flex-shrink-0 w-8 h-8 bg-orange-100 rounded-full flex items-center justify-center text-orange-600 font-bold">
                                !
                            </div>
                            <p className="text-orange-800 text-xs font-medium leading-relaxed">
                                Lưu ý: Để bảo vệ quyền lợi, vui lòng tiến hành thay đổi thông tin bảo mật của tài khoản
                                ngay tại trang chủ của nhà phát hành game.
                            </p>
                        </div>
                    </div>
                )}
            </Modal>

            <ReviewModal
                open={isReviewModalOpen}
                onCancel={() => setIsReviewModalOpen(false)}
                onSubmit={handleSubmitReview}
                loading={submittingReview}
                rating={reviewRating}
                setRating={setReviewRating}
                comment={reviewComment}
                setComment={setReviewComment}
                order={reviewingOrder}
            />

            <style>{`
                .custom-purchased-table .ant-table-thead > tr > th {
                    background: #fff !important;
                    font-weight: 800 !important;
                    text-transform: uppercase !important;
                    font-size: 11px !important;
                    letter-spacing: 0.1em !important;
                    color: #94a3b8 !important;
                    padding: 24px 20px !important;
                    border-bottom: 2px solid #f1f5f9 !important;
                }
                .custom-purchased-table .ant-table-tbody > tr > td {
                    padding: 20px !important;
                    border-bottom: 1px solid #f1f5f9 !important;
                }
                .custom-purchased-table .ant-table-row:hover > td {
                    background: #f8fafc !important;
                }
                .credential-modal .ant-modal-content {
                    border-radius: 28px !important;
                    overflow: hidden;
                }
                .credential-modal .ant-modal-header {
                    margin-bottom: 0;
                    padding: 24px 24px 0;
                    border: none;
                }
                .credential-modal .ant-modal-body {
                    padding: 0 24px;
                }
                .credential-modal .ant-modal-footer {
                    padding: 0 24px 24px;
                    border-top: none;
                    text-align: center;
                }
            `}</style>
        </div>
    );
};

// Review Modal Component
const ReviewModal = ({ open, onCancel, onSubmit, loading, rating, setRating, comment, setComment, order }) => {
    return (
        <Modal
            title={
                <div className="flex items-center gap-3 pb-3 border-b border-gray-100 w-full">
                    <div className="w-10 h-10 bg-yellow-100 rounded-xl flex items-center justify-center text-yellow-600">
                        <Star size={20} fill="currentColor" />
                    </div>
                    <div>
                        <p className="text-[11px] text-gray-400 uppercase font-black tracking-widest leading-none mb-1">
                            Đánh giá sản phẩm
                        </p>
                        <h3 className="text-lg font-bold text-gray-800 leading-none">
                            {order?.productId?.title || 'Sản phẩm'}
                        </h3>
                    </div>
                </div>
            }
            open={open}
            onCancel={onCancel}
            footer={null}
            centered
            width={500}
            className="review-modal"
        >
            <div className="py-6 space-y-6">
                <div className="flex flex-col items-center justify-center gap-3">
                    <p className="text-gray-500 font-medium">Bạn cảm thấy sản phẩm thế nào?</p>
                    <Rate className="text-4xl text-yellow-400" value={rating} onChange={setRating} />
                    <span className="text-sm font-bold text-yellow-600 bg-yellow-50 px-3 py-1 rounded-full">
                        {rating === 5
                            ? 'Tuyệt vời'
                            : rating === 4
                              ? 'Hài lòng'
                              : rating === 3
                                ? 'Bình thường'
                                : rating === 2
                                  ? 'Không hài lòng'
                                  : 'Tệ'}
                    </span>
                </div>

                <div className="space-y-2">
                    <label className="text-sm font-bold text-gray-700 ml-1">Nội dung đánh giá</label>
                    <TextArea
                        rows={4}
                        placeholder="Chia sẻ trải nghiệm của bạn về sản phẩm này..."
                        value={comment}
                        onChange={(e) => setComment(e.target.value)}
                        className="rounded-xl border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 hover:border-blue-300 transition-all p-4 text-gray-700 font-medium bg-gray-50"
                        maxLength={200}
                        showCount
                    />
                </div>

                <div className="pt-2 flex gap-3">
                    <Button
                        className="flex-1 h-11 rounded-xl font-bold border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 hover:border-gray-300"
                        onClick={onCancel}
                        disabled={loading}
                    >
                        HỦY BỎ
                    </Button>
                    <Button
                        type="primary"
                        className="flex-1 h-11 rounded-xl font-bold bg-yellow-500 hover:bg-yellow-600 shadow-lg shadow-yellow-200 border-none"
                        onClick={onSubmit}
                        loading={loading}
                    >
                        GỬI ĐÁNH GIÁ
                    </Button>
                </div>
            </div>
        </Modal>
    );
};

export default PurchasedAccounts;
