import { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import { InputNumber } from 'antd';
import { CreditCard, Wallet } from 'lucide-react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { apiClient } from '../config/axiosClient';
import { requestGetCardType } from '../config/cardType';
import { requestCreateQRBank } from '../config/deposits';
import { useStore } from '../hooks/useStore';
import { Helmet } from 'react-helmet';

function Deposits() {
    const { dataWebsite } = useStore();
    const [cardTypes, setCardTypes] = useState([]);
    const [uniqueNetworks, setUniqueNetworks] = useState([]);
    const [availableAmounts, setAvailableAmounts] = useState([]);
    const [cardData, setCardData] = useState({
        network: '',
        amount: '',
        serial: '',
        code: '',
    });

    const [bankAmount, setBankAmount] = useState('');

    useEffect(() => {
        const fetchCardTypes = async () => {
            try {
                const response = await requestGetCardType();
                setCardTypes(response.metadata);

                // Extract unique networks (telcos)
                const networks = [...new Set(response.metadata.map((item) => item.telco))];
                setUniqueNetworks(networks);
            } catch (error) {
                console.error('Failed to fetch card types:', error);
                toast.error('Không thể tải danh sách loại thẻ');
            }
        };
        fetchCardTypes();
    }, []);

    const handleCardChange = (e) => {
        const { name, value } = e.target;

        if (name === 'network') {
            // When network changes, reset amount and update available amounts
            const amounts = cardTypes.filter((type) => type.telco === value).sort((a, b) => a.value - b.value);

            setAvailableAmounts(amounts);
            setCardData((prev) => ({
                ...prev,
                network: value,
                amount: '', // Reset amount
            }));
        } else {
            setCardData((prev) => ({ ...prev, [name]: value }));
        }
    };

    const handleCardSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await apiClient.post('/api/deposit/create', {
                type: 'CARD',
                ...cardData,
                amount: parseInt(cardData.amount),
            });
            toast.success('Gửi thẻ thành công! Vui lòng chờ duyệt.');
            // Reset crucial fields
            setCardData((prev) => ({ ...prev, serial: '', code: '' }));
        } catch (error) {
            console.error('Deposit error:', error);
            const msg = error.response?.data?.message || 'Có lỗi xảy ra khi gửi thẻ';
            toast.error(msg);
        }
    };

    const handleBankSubmit = async (e) => {
        e.preventDefault();
        if (!bankAmount || bankAmount < 10000) {
            toast.error('Vui lòng nhập số tiền hợp lệ (tối thiểu 10.000đ)');
            return;
        }
        try {
            const res = await requestCreateQRBank(bankAmount);

            // Nếu interceptor chưa decrypt, thực hiện thủ công
            let metaData = res.metadata;
            if (typeof metaData === 'string') {
                try {
                    const CryptoJS = (await import('crypto-js')).default;
                    const bytes = CryptoJS.AES.decrypt(metaData, import.meta.env.VITE_SECRET_CRYPTO);
                    metaData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
                } catch {
                    toast.error('Không thể giải mã dữ liệu thanh toán!');
                    return;
                }
            }

            const { checkoutURL, checkoutFormfields } = metaData;

            if (!checkoutURL || !checkoutFormfields) {
                toast.error('Không thể tạo link thanh toán. Vui lòng thử lại!');
                return;
            }

            // SePay yêu cầu form POST
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = checkoutURL;
            Object.keys(checkoutFormfields).forEach((field) => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = field;
                input.value = checkoutFormfields[field];
                form.appendChild(input);
            });
            document.body.appendChild(form);
            form.submit();
        } catch (error) {
            console.error('Deposit error:', error);
            const msg = error.response?.data?.message || 'Có lỗi xảy ra khi tạo mã QR';
            toast.error(msg);
        }
    };

    // Calculate actual received amount
    const selectedCard = cardTypes.find(
        (c) => c.telco === cardData.network && c.value.toString() === cardData.amount.toString(),
    );
    const fee = selectedCard ? selectedCard.fees : 0;
    const receivedAmount = cardData.amount ? parseInt(cardData.amount) * (1 - fee / 100) : 0;

    return (
        <div className="min-h-screen bg-gray-50 flex flex-col">
            <Helmet>
                <title>Nạp tiền | {dataWebsite?.nameWebsite || 'Website'}</title>
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="flex-grow container mx-auto px-4 py-8">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-6xl mx-auto">
                    {/* Card Deposit Section */}
                    <div className="bg-[#0b4e5a] rounded-xl overflow-hidden shadow-xl">
                        <div className="p-6">
                            <h2 className="text-2xl font-bold text-white mb-6 flex items-center gap-2">
                                <CreditCard className="w-6 h-6" />
                                Nạp Thẻ Cào
                            </h2>

                            <form onSubmit={handleCardSubmit} className="space-y-4">
                                {/* Network Selection */}
                                <div>
                                    <label className="block text-white font-bold mb-2">Loại Thẻ</label>
                                    <select
                                        name="network"
                                        value={cardData.network}
                                        onChange={handleCardChange}
                                        className="w-full h-12 px-4 rounded-lg bg-white text-gray-800 font-medium focus:outline-none focus:ring-2 focus:ring-emerald-400"
                                    >
                                        <option value="">Chọn loại thẻ</option>
                                        {uniqueNetworks.map((telco) => (
                                            <option key={telco} value={telco}>
                                                {telco}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                {/* Amount Selection */}
                                <div>
                                    <label className="block text-white font-bold mb-2">Mệnh Giá</label>
                                    <select
                                        name="amount"
                                        value={cardData.amount}
                                        onChange={handleCardChange}
                                        disabled={!cardData.network}
                                        className="w-full h-12 px-4 rounded-lg bg-white text-gray-800 font-medium focus:outline-none focus:ring-2 focus:ring-emerald-400 disabled:opacity-60"
                                    >
                                        <option value="">Chọn mệnh giá</option>
                                        {availableAmounts.map((type) => (
                                            <option key={type._id || `${type.telco}-${type.value}`} value={type.value}>
                                                {type.value.toLocaleString()}đ (Phí {type.fees}%)
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                {/* Serial Input */}
                                <div>
                                    <label className="block text-white font-bold mb-2">Số Serial</label>
                                    <input
                                        type="text"
                                        name="serial"
                                        value={cardData.serial}
                                        onChange={handleCardChange}
                                        placeholder="Nhập số serial"
                                        className="w-full h-12 px-4 rounded-lg bg-white text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-emerald-400"
                                        required
                                    />
                                </div>

                                {/* Code Input */}
                                <div>
                                    <label className="block text-white font-bold mb-2">Mã Thẻ</label>
                                    <input
                                        type="text"
                                        name="code"
                                        value={cardData.code}
                                        onChange={handleCardChange}
                                        placeholder="Nhập mã thẻ"
                                        className="w-full h-12 px-4 rounded-lg bg-white text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-emerald-400"
                                        required
                                    />
                                </div>

                                {/* Warning */}
                                <div className="text-center py-2">
                                    <p className="text-yellow-400 font-bold italic text-lg shadow-black drop-shadow-md">
                                        Nếu Chọn Sai Mệnh Giá Sẽ Bị Mất Thẻ!
                                    </p>
                                </div>

                                {/* Submit Button */}
                                <button
                                    type="submit"
                                    disabled={!cardData.network}
                                    className="w-full h-12 bg-emerald-500 hover:bg-emerald-600 disabled:bg-gray-400 text-white font-bold text-sm rounded-lg transition-colors uppercase shadow-lg"
                                >
                                    Gửi Để Nhận {receivedAmount.toLocaleString('vi-VN')} đ
                                </button>
                            </form>
                        </div>
                    </div>

                    {/* Auto Deposit Section */}
                    <div className="space-y-6">
                        <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
                            <div className="bg-gradient-to-r from-orange-500 to-red-500 p-6 text-white">
                                <h2 className="text-xl font-bold flex items-center gap-2">
                                    <Wallet className="w-6 h-6" />
                                    Nạp Tiền Tự Động
                                </h2>
                                <p className="text-orange-100 text-sm mt-1">
                                    Chuyển khoản chính xác nội dung để được cộng tiền tự động
                                </p>
                            </div>

                            <div className="p-6">
                                <form onSubmit={handleBankSubmit} className="space-y-4">
                                    <div>
                                        <label className="block text-gray-700 font-semibold mb-2">
                                            Nhập số tiền cần nạp
                                        </label>
                                        <div className="relative">
                                            <InputNumber
                                                value={bankAmount}
                                                style={{ width: '100%', height: '48px' }}
                                                onChange={(value) => setBankAmount(value)}
                                                placeholder="Ví dụ: 50,000"
                                                min={10000}
                                                formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                                parser={(value) => value.replace(/\$\s?|(,*)/g, '')}
                                                controls={false}
                                            />
                                            <span className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 font-bold z-10 pointer-events-none">
                                                VNĐ
                                            </span>
                                        </div>
                                        <p className="text-xs text-gray-500 mt-1">* Số tiền tối thiểu: 10.000 VNĐ</p>
                                    </div>

                                    <button
                                        type="submit"
                                        className="w-full h-12 bg-gradient-to-r from-orange-500 to-red-500 text-white font-bold rounded-lg shadow-md hover:shadow-lg hover:from-orange-600 hover:to-red-600 transition-all transform active:scale-[0.98]"
                                    >
                                        Tạo Lệnh Nạp Tiền
                                    </button>
                                </form>

                                {/* Instruction */}
                                <div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-100">
                                    <h3 className="font-bold text-blue-800 mb-2">Lưu ý khi nạp tiền:</h3>
                                    <ul className="list-disc list-inside text-sm text-blue-700 space-y-1">
                                        <li>Vui lòng chuyển khoản đúng nội dung bên dưới.</li>
                                        <li>Hệ thống sẽ tự động cộng tiền trong vòng 1-5 phút.</li>
                                        <li>Nếu quá 15 phút chưa nhận được, vui lòng liên hệ hỗ trợ.</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>

            <Footer />
        </div>
    );
}

export default Deposits;
