function CouponPrintModal({ isOpen, onClose, data = [] }) {
    const [printing, setPrinting] = React.useState(false);
    const SETTINGS_COUPON_KEY = 'coupon_settings';

    const buildDefaultConfig = () => {
        const now = new Date();
        const currentHours = String(now.getHours()).padStart(2, '0');
        const currentMinutes = String(now.getMinutes()).padStart(2, '0');
        const currentTime = `${currentHours}:${currentMinutes}`;
        
        return {
            year: now.getFullYear().toString(),
            date: now.toISOString().split('T')[0],
            startTime: currentTime,
            endTime: currentTime,
            location: 'Aula KH. Abd. Rahman Sy.',
            note: 'Panitia tidak melayani, di luar waktu yang ditetapkan'
        };
    };

    const [config, setConfig] = React.useState(() => buildDefaultConfig());

    const loadCouponSettings = async () => {
        try {
            const client = window.SupabaseUtils.getClient();
            if (!client) return;

            const { data, error } = await client
                .from('app_settings')
                .select('value')
                .eq('key', SETTINGS_COUPON_KEY)
                .maybeSingle();

            if (error) throw error;

            if (data && data.value) {
                const parsed = JSON.parse(data.value);
                setConfig(prev => ({ ...prev, ...parsed }));
            }
        } catch (err) {
            console.error("Load coupon settings error:", err);
        }
    };

    const saveCouponSettings = async (nextConfig) => {
        try {
            const client = window.SupabaseUtils.getClient();
            if (!client) return;

            const { error } = await client
                .from('app_settings')
                .upsert({ key: SETTINGS_COUPON_KEY, value: JSON.stringify(nextConfig) });

            if (error) throw error;
        } catch (err) {
            console.error("Save coupon settings error:", err);
        }
    };

    React.useEffect(() => {
        if (isOpen) {
            loadCouponSettings();
        }
    }, [isOpen]);

    React.useEffect(() => {
        if (!isOpen) return;
        const timer = setTimeout(() => {
            saveCouponSettings(config);
        }, 500);

        return () => clearTimeout(timer);
    }, [config, isOpen]);

    if (!isOpen) return null;

    const handlePrint = async () => {
        setPrinting(true);
        try {
            await saveCouponSettings(config);
            if (!window.CouponPrinter) {
                throw new Error("Utility CouponPrinter tidak ditemukan.");
            }
            await window.CouponPrinter.generate(data, config);
            Swal.fire({
                icon: 'success',
                title: 'Selesai',
                text: 'Kupon berhasil diunduh.',
                timer: 1500,
                showConfirmButton: false
            });
            onClose();
        } catch (error) {
            Swal.fire("Gagal", "Terjadi kesalahan: " + error.message, "error");
        } finally {
            setPrinting(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100] p-4 animate-fade-in">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-md overflow-hidden">
                <div className="bg-indigo-600 p-4 text-white flex justify-between items-center">
                    <h3 className="font-bold flex items-center gap-2">
                        <div className="icon-printer"></div>
                        Cetak Kupon ({data.length} Data)
                    </h3>
                    <button onClick={onClose} className="hover:text-indigo-200">
                        <div className="icon-x text-xl"></div>
                    </button>
                </div>
                
                <div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-1">Tahun Parsel</label>
                        <input 
                            type="number" 
                            className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none"
                            value={config.year}
                            onChange={e => setConfig({...config, year: e.target.value})}
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-1">Hari / Tanggal Pengambilan</label>
                        <input 
                            type="date" 
                            className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none"
                            value={config.date}
                            onChange={e => setConfig({...config, date: e.target.value})}
                        />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-bold text-gray-700 mb-1">Mulai (WIB)</label>
                            <input 
                                type="time" 
                                className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none"
                                value={config.startTime}
                                onChange={e => setConfig({...config, startTime: e.target.value})}
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-bold text-gray-700 mb-1">Selesai (WIB)</label>
                            <input 
                                type="time" 
                                className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none"
                                value={config.endTime}
                                onChange={e => setConfig({...config, endTime: e.target.value})}
                            />
                        </div>
                    </div>
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-1">Tempat Pengambilan</label>
                        <input 
                            type="text" 
                            className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none"
                            placeholder="Contoh: Aula KH. Abd. Rahman Sy."
                            value={config.location}
                            onChange={e => setConfig({...config, location: e.target.value})}
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-bold text-gray-700 mb-1">Keterangan Tambahan</label>
                        <textarea 
                            className="w-full p-2 border rounded focus:ring-2 focus:ring-indigo-500 outline-none text-sm"
                            placeholder="Contoh: Panitia tidak melayani..."
                            rows="2"
                            value={config.note}
                            onChange={e => setConfig({...config, note: e.target.value})}
                        />
                    </div>
                </div>

                <div className="p-4 bg-gray-50 border-t flex justify-end gap-2">
                    <button 
                        onClick={onClose}
                        className="px-4 py-2 border rounded text-gray-600 hover:bg-gray-100"
                        disabled={printing}
                    >
                        Batal
                    </button>
                    <button 
                        onClick={handlePrint}
                        disabled={printing}
                        className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 flex items-center gap-2 shadow disabled:opacity-50"
                    >
                        {printing ? (
                            <>
                                <div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"></div>
                                Memproses...
                            </>
                        ) : (
                            <>
                                <div className="icon-printer"></div>
                                Cetak PDF
                            </>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}
