<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Unipay</title>
    <link href="assets/css/daisyui@3.5.0-full.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/font-awesome@5.15.1-min.css" rel="stylesheet" type="text/css" />
    <script src="assets/js/tailwindcss-3.3.3.js"></script>
</head>

<body class="bg-gray-100">

    <!-- Error modal -->
    <div id="error-modal" class="modal">
        <div class="modal-box">
            <h2 class="text-xl">Error</h2>
            <p id="error-message"></p>
            <div class="modal-action">
                <button onclick="closeModal()" class="btn">Okay</button>
            </div>
        </div>
    </div>

    <!-- QR Selection Modal -->
    <div id="qr-selection-modal" class="modal">
        <div class="modal-box">
            <h2 class="text-xl">Select QR Code</h2>
            <p class="text-sm text-gray-600" id="payment-type-subtitle"></p>
            <div id="qr-list" class="max-h-48 overflow-y-auto space-y-2"></div>
            <div class="modal-action">
                <button onclick="closeQRSelectionModal(true)" class="btn">Select</button>
                <button onclick="closeQRSelectionModal()" class="btn">Cancel</button>
            </div>
        </div>
    </div>

    <!-- Success modal -->
    <div id="success-modal" class="modal">
        <div class="modal-box">
            <h2 class="text-xl">Success</h2>
            <p id="success-message">Unipay has been successfully created!</p>
            <div class="modal-action">
                <button onclick="closeSuccessModal()" class="btn">Okay</button>
            </div>
        </div>
    </div>

    <div class="min-h-screen flex justify-center items-center">
        <div class="bg-white p-8 rounded-xl shadow-md space-y-6" style="width: 26rem;">
            <h1 class="text-2xl font-bold text-center flex items-center justify-center">
                Upload Payment QR Code
                <a href="https://github.com/djkcyl/unipay" target="_blank" title="View on Github">
                    <i class="fab fa-github pl-2"></i>
                </a>
            </h1>

            <form id="unipay-form" onsubmit="handleSubmit(event)">
                <div class="space-y-4">
                    <!-- Alipay upload section -->
                    <div class="relative space-y-4">
                        <div class="relative">
                            <button
                                class="btn btn-primary absolute top-0 left-0 w-full h-full opacity-0 cursor-pointer">
                                Upload Alipay QR Code
                            </button>
                            <input type="file" id="alipay-file" name="alipay-file"
                                class="absolute top-0 left-0 w-full h-full opacity-0 cursor-pointer"
                                onchange="decodeQR('alipay')">
                            <input type="text" id="alipay" name="alipay" readonly
                                placeholder="Decoded Alipay QR Code..." class="input input-bordered w-full">
                        </div>
                    </div>
                    <!-- WeChat upload section -->
                    <div class="relative space-y-4">
                        <div class="relative">
                            <button
                                class="btn btn-primary absolute top-0 left-0 w-full h-full opacity-0 cursor-pointer">
                                Upload WeChat QR Code
                            </button>
                            <input type="file" id="wechat-file" name="wechat-file"
                                class="absolute top-0 left-0 w-full h-full opacity-0 cursor-pointer"
                                onchange="decodeQR('wechat')">
                            <input type="text" id="wechat" name="wechat" readonly
                                placeholder="Decoded WeChat QR Code..." class="input input-bordered w-full">
                        </div>
                    </div>
                    <!-- ShortID input section -->
                    <div class="space-y-4">
                        <input type="text" id="shortid" name="shortid" placeholder="Short ID (optional)"
                            class="input input-bordered w-full">
                    </div>
                </div>
                <!-- Submit button -->
                <div class="mt-4">
                    <button type="submit" class="btn btn-primary w-full">Create Unipay</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentPaymentType = null;

        async function decodeQR(paymentType) {
            const fileInput = document.getElementById(`${paymentType}-file`);
            const file = fileInput.files[0];

            if (!file) return;

            const maxFileSize = 10 * 1024 * 1024; // 10MB
            if (file.size > maxFileSize) {
                showErrorModal("File size must be under 10MB.");
                return;
            }

            const validFileTypes = ['image/png', 'image/jpeg'];
            if (!validFileTypes.includes(file.type)) {
                showErrorModal("Please upload a PNG or JPG image.");
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('/decode', {
                    method: 'POST',
                    body: formData,
                });

                if (response.status === 400) {
                    const data = await response.json();
                    showErrorModal(data.detail);
                    return;
                }

                const data = await response.json();
                if (data.data.length === 1) {
                    document.getElementById(paymentType).value = data.data[0];
                } else {
                    populateQRSelection(data.data, paymentType);
                }
            } catch (error) {
                showErrorModal('Failed to decode QR code.');
            }
        }

        function populateQRSelection(qrs, paymentType) {
            currentPaymentType = paymentType;
            const qrList = document.getElementById('qr-list');
            qrList.innerHTML = '';

            const subtitle = document.getElementById('payment-type-subtitle');
            if (paymentType === 'alipay') {
                subtitle.textContent = 'You are selecting a QR Code for Alipay.';
            } else if (paymentType === 'wechat') {
                subtitle.textContent = 'You are selecting a QR Code for WeChat.';
            }

            qrs.forEach((qr, index) => {
                const radioId = `qr-${index}`;

                const label = document.createElement('label');
                label.setAttribute('class', 'btn btn-radio btn-block');

                const input = document.createElement('input');
                input.type = 'radio';
                input.name = 'qr-selection';
                input.value = qr;
                input.id = radioId;

                const span = document.createElement('span');
                span.textContent = qr.length > 100 ? `${qr.substring(0, 100)}...` : qr;

                label.appendChild(input);
                label.appendChild(span);
                qrList.appendChild(label);
            });

            const modal = document.getElementById('qr-selection-modal');
            modal.classList.add('modal-open');
        }

        function closeQRSelectionModal(applySelection = false) {
            const modal = document.getElementById('qr-selection-modal');
            if (applySelection) {
                const selectedQR = document.querySelector('input[name="qr-selection"]:checked');
                if (selectedQR) {
                    document.getElementById(currentPaymentType).value = selectedQR.value;
                }
            }
            // 重置文件输入的值
            document.getElementById(`${currentPaymentType}-file`).value = '';
            modal.classList.remove('modal-open');
        }


        function showErrorModal(message) {
            const modal = document.getElementById('error-modal');
            const errorMessage = document.getElementById('error-message');

            if (Array.isArray(message) && message.every(item => typeof item === 'object')) {
                message = message.map(item => JSON.stringify(item)).join(', ');
            }

            errorMessage.textContent = message;
            modal.classList.add('modal-open');
        }

        function closeModal() {
            const modal = document.getElementById('error-modal');
            modal.classList.remove('modal-open');
        }

        async function handleSubmit(event) {
            event.preventDefault();

            const alipayValue = document.getElementById('alipay').value;
            const wechatValue = document.getElementById('wechat').value;
            const shortidValue = document.getElementById('shortid').value;

            if (!alipayValue || !wechatValue) {
                showErrorModal("Both WeChat and Alipay QR codes must be provided.");
                return;
            }

            if (shortidValue) {
                if (shortidValue.length < 2 || shortidValue.length > 8) {
                    showErrorModal("Short ID must be between 2 and 8 characters.");
                    return;
                }

                const regex = /^[A-Za-z0-9]+$/;
                if (!regex.test(shortidValue)) {
                    showErrorModal("Short ID can only contain alphanumeric characters.");
                    return;
                }
            }

            const formData = new FormData();
            formData.append('alipay', alipayValue);
            formData.append('wechatpay', wechatValue);

            try {
                const response = await fetch('/create', {
                    method: 'POST',
                    body: formData,
                });

                if (response.status !== 200) {
                    const data = await response.json();
                    showErrorModal(data.detail || 'Unknown error occurred.');
                    return;
                }

                const unipayData = await response.json();
                showSuccessModal(unipayData.short_id);

            } catch (error) {
                showErrorModal('Failed to create Unipay.');
            }
        }

        function showSuccessModal(message) {
            const modal = document.getElementById('success-modal');
            const successMessage = document.getElementById('success-message');

            // 获取当前的 host 并与 short_id 拼接
            const fullUrl = `${window.location.origin}/${message}`;
            successMessage.innerHTML = `Unipay created successfully.<br>Access it at: <a href="${fullUrl}" target="_blank">${fullUrl}</a>`;

            modal.classList.add('modal-open');
        }


        function closeSuccessModal() {
            const modal = document.getElementById('success-modal');
            modal.classList.remove('modal-open');
        }
    </script>
</body>

</html>