'use client';

import React, { useState, useRef } from 'react';
import Link from 'next/link';
import { QRCodeSVG } from 'qrcode.react';
import {
    Bitcoin,
    Download,
    Check,
    Sparkles,
    Wallet,
} from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { cn } from '@/lib/utils';
import AdBanner from '@/components/ads/AdBanner';

// Brand Colors
const BRAND = {
    paleGrey: '#EBEBDF',
    richBlue: '#1A1265',
    richBlueLight: '#2A2275',
};

// Crypto Options
const CRYPTO_CURRENCIES = [
    { value: 'bitcoin', label: 'Bitcoin (BTC)', color: '#F7931A', prefix: 'bitcoin:' },
    { value: 'ethereum', label: 'Ethereum (ETH)', color: '#627EEA', prefix: 'ethereum:' },
    { value: 'usdt', label: 'Tether (USDT)', color: '#26A17B', prefix: '' }, // Commonly ERC20/TRC20 - keeping raw for safety
    { value: 'solana', label: 'Solana (SOL)', color: '#14F195', prefix: 'solana:' },
];


// QR Color Options
const QR_COLORS = [
    { name: 'Bitcoin Orange', value: '#F7931A' },
    { name: 'Ethereum Blue', value: '#627EEA' },
    { name: 'Tether Green', value: '#26A17B' },
    { name: 'Classic Black', value: '#000000' },
    { name: 'Dark Blue', value: '#1A1265' },
    { name: 'Emerald', value: '#10B981' },
    { name: 'Rose', value: '#F43F5E' },
];

// Frame Options
const FRAME_OPTIONS = [
    { id: 'none', label: 'No Frame' },
    { id: 'scanme', label: 'Scan Me' },
    { id: 'pay', label: 'Pay Now' },
    { id: 'donate', label: 'Donate' },
];

export default function CryptoGenerator() {
    const [currency, setCurrency] = useState('bitcoin');
    const [address, setAddress] = useState('');
    const [amount, setAmount] = useState('');
    const [qrMode, setQrMode] = useState<'universal' | 'wallet'>('universal');
    const [qrColor, setQrColor] = useState('#F7931A');
    const [frameType, setFrameType] = useState('none');

    const qrRef = useRef<HTMLDivElement>(null);

    // Generate URL based on selected mode
    const getUrl = () => {
        if (!address.trim()) return 'https://www.qrmaster.net';

        const cleanAddr = address.trim();

        if (qrMode === 'wallet') {
            // Wallet Direct Mode - Uses crypto URI scheme
            // Only works when scanning FROM a wallet app (Coinbase, Trust Wallet, etc.)
            const prefixes: Record<string, string> = {
                bitcoin: 'bitcoin:',
                ethereum: 'ethereum:',
                solana: 'solana:',
                usdt: '', // USDT doesn't have a standard URI
            };
            const prefix = prefixes[currency] || '';
            if (!prefix) return cleanAddr; // USDT fallback
            let uri = `${prefix}${cleanAddr}`;
            if (amount) uri += `?amount=${amount}`;
            return uri;
        } else {
            // Universal Mode - Blockchain explorer links
            // Works with ANY phone camera
            switch (currency) {
                case 'bitcoin':
                    return `https://blockchair.com/bitcoin/address/${cleanAddr}`;
                case 'ethereum':
                    return `https://etherscan.io/address/${cleanAddr}`;
                case 'solana':
                    return `https://solscan.io/account/${cleanAddr}`;
                case 'usdt':
                    return `https://etherscan.io/token/0xdac17f958d2ee523a2206206994597c13d831ec7?a=${cleanAddr}`;
                default:
                    return cleanAddr;
            }
        }
    };

    const handleDownload = async (format: 'png' | 'svg') => {
        if (!qrRef.current) return;
        try {
            if (format === 'png') {
                const { toPng } = await import('html-to-image');
                const dataUrl = await toPng(qrRef.current, { cacheBust: true, pixelRatio: 3 });
                const link = document.createElement('a');
                link.download = `${currency}-qr-code.png`;
                link.href = dataUrl;
                link.click();
            } else {
                const svgData = qrRef.current.querySelector('svg')?.outerHTML;
                if (svgData) {
                    const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `${currency}-qr-code.svg`;
                    link.click();
                }
            }
        } catch (err) {
            console.error('Download failed', err);
        }
    };

    const getFrameLabel = () => {
        const frame = FRAME_OPTIONS.find(f => f.id === frameType);
        return frame?.id !== 'none' ? frame?.label : null;
    };

    return (
        <div className="w-full max-w-5xl mx-auto px-4 md:px-6">

            {/* Main Generator Card */}
            <div className="bg-white rounded-3xl shadow-2xl shadow-slate-900/10 overflow-hidden border border-slate-100">
                <div className="grid lg:grid-cols-2">

                    {/* LEFT: Input Section */}
                    <div className="p-6 md:p-8 lg:p-10 space-y-8 border-r border-slate-100">

                        {/* Crypto Details */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Wallet className="w-5 h-5 text-slate-900" />
                                Wallet Details
                            </h2>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Currency</label>
                                <Select
                                    value={currency}
                                    options={CRYPTO_CURRENCIES}
                                    onChange={(e) => {
                                        const val = e.target.value;
                                        setCurrency(val);
                                        const col = CRYPTO_CURRENCIES.find(c => c.value === val)?.color;
                                        if (col) setQrColor(col);
                                    }}
                                    className="h-12 w-full rounded-xl border-slate-200"
                                    aria-label="Currency"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Wallet Address</label>
                                <Input
                                    placeholder={`Enter ${currency} address`}
                                    value={address}
                                    onChange={(e) => setAddress(e.target.value)}
                                    className="h-12 text-base rounded-xl border-slate-200 focus:border-slate-900 focus:ring-slate-900 font-mono text-sm"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">Amount (Optional)</label>
                                <Input
                                    placeholder="0.00"
                                    type="number"
                                    value={amount}
                                    onChange={(e) => setAmount(e.target.value)}
                                    className="h-12 text-base rounded-xl border-slate-200 focus:border-slate-900 focus:ring-slate-900"
                                />
                            </div>

                            {/* QR Mode Toggle */}
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-2">QR Code Mode</label>
                                <div className="grid grid-cols-2 gap-2">
                                    <button
                                        onClick={() => setQrMode('universal')}
                                        className={cn(
                                            "py-3 px-4 rounded-xl text-sm font-medium transition-all border",
                                            qrMode === 'universal'
                                                ? "bg-slate-900 text-white border-slate-900"
                                                : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                        )}
                                    >
                                        Universal (Web)
                                    </button>
                                    <button
                                        onClick={() => setQrMode('wallet')}
                                        className={cn(
                                            "py-3 px-4 rounded-xl text-sm font-medium transition-all border",
                                            qrMode === 'wallet'
                                                ? "bg-slate-900 text-white border-slate-900"
                                                : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                        )}
                                    >
                                        Wallet Direct
                                    </button>
                                </div>
                                <p className="text-xs text-slate-600 mt-2">
                                    {qrMode === 'universal'
                                        ? "Works with any phone camera. Opens blockchain explorer."
                                        : "Requires scanning from a wallet app. Enables direct payment."}
                                </p>
                            </div>
                        </div>

                        <div className="border-t border-slate-100"></div>

                        {/* Design Options */}
                        <div className="space-y-6">
                            <h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                                <Sparkles className="w-5 h-5 text-slate-900" />
                                Design Options
                            </h2>

                            {/* Color Picker */}
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-3">QR Code Color</label>
                                <div className="flex flex-wrap gap-2">
                                    {QR_COLORS.map((c) => (
                                        <button
                                            key={c.name}
                                            onClick={() => setQrColor(c.value)}
                                            className={cn(
                                                "w-9 h-9 rounded-full border-2 flex items-center justify-center transition-all hover:scale-110",
                                                qrColor === c.value ? "border-slate-900 ring-2 ring-offset-2 ring-slate-200" : "border-white shadow-md"
                                            )}
                                            style={{ backgroundColor: c.value }}
                                            aria-label={`Select ${c.name}`}
                                            title={c.name}
                                        >
                                            {qrColor === c.value && <Check className="w-4 h-4 text-white" strokeWidth={3} />}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Frame Selector */}
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-3">Frame Label</label>
                                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                                    {FRAME_OPTIONS.map((frame) => (
                                        <button
                                            key={frame.id}
                                            onClick={() => setFrameType(frame.id)}
                                            className={cn(
                                                "py-2.5 px-3 rounded-lg text-sm font-medium transition-all border",
                                                frameType === frame.id
                                                    ? "bg-slate-900 text-white border-slate-900"
                                                    : "bg-slate-50 text-slate-600 border-slate-200 hover:border-slate-300"
                                            )}
                                        >
                                            {frame.label}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* RIGHT: Preview Section */}
                    <div className="p-6 md:p-8 lg:p-10 flex flex-col items-center justify-center" style={{ backgroundColor: BRAND.paleGrey }}>

                        {/* QR Card with Frame */}
                        <div
                            ref={qrRef}
                            className="bg-white rounded-3xl shadow-xl p-6 sm:p-8 flex flex-col items-center w-full max-w-[320px]"
                        >
                            {/* Frame Label */}
                            {getFrameLabel() && (
                                <div
                                    className="mb-5 px-8 py-2.5 rounded-full text-white font-bold text-sm tracking-widest uppercase shadow-md"
                                    style={{ backgroundColor: qrColor }}
                                >
                                    {getFrameLabel()}
                                </div>
                            )}

                            {/* QR Code */}
                            <div className="bg-white">
                                {address.trim() ? (
                                    <QRCodeSVG
                                        value={getUrl()}
                                        size={240}
                                        level="Q"
                                        includeMargin={false}
                                        fgColor={qrColor}
                                    />
                                ) : (
                                    <div
                                        className="flex items-center justify-center border-2 border-dashed border-slate-200 rounded-xl"
                                        style={{ width: 240, height: 240 }}
                                    >
                                        <div className="text-center text-slate-400 p-6">
                                            <Wallet className="w-12 h-12 mx-auto mb-3 opacity-50" />
                                            <p className="text-sm font-medium">Enter wallet address</p>
                                            <p className="text-xs mt-1">to generate QR code</p>
                                        </div>
                                    </div>
                                )}
                            </div>

                            {/* Info Preview */}
                            <div className="mt-6 text-center max-w-[260px]">
                                <h3 className="font-bold text-slate-900 text-lg flex items-center justify-center gap-2 truncate">
                                    <Bitcoin className="w-4 h-4 text-slate-400 shrink-0" />
                                    <span className="truncate capitalize">{currency}</span>
                                </h3>
                                <div className="text-xs text-slate-600 mt-1 truncate px-2">
                                    {address || 'Wallet Address'}
                                </div>
                            </div>
                        </div>

                        {/* Download Buttons */}
                        <div className="flex items-center gap-3 mt-8">
                            <Button
                                onClick={() => handleDownload('png')}
                                className="bg-slate-900 hover:bg-black text-white shadow-lg"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                Download PNG
                            </Button>
                            <Button
                                onClick={() => handleDownload('svg')}
                                variant="outline"
                                className="border-slate-300 hover:bg-white"
                            >
                                <Download className="w-4 h-4 mr-2" />
                                SVG
                            </Button>
                        </div>

                        <p className="text-xs text-slate-600 mt-4 text-center">
                            Scanning copies the wallet address or opens a crypto app.
                        </p>
                    </div>
                </div>
            </div>



            {/* Upsell Banner */}
            <div className="mt-8 bg-gradient-to-r from-slate-900 to-slate-700 rounded-2xl p-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div className="text-white text-center sm:text-left">
                    <h3 className="font-bold text-lg">Accept Crypto for Business?</h3>
                    <p className="text-white/80 text-sm mt-1">
                        Create professional, branded payment pages for your store.
                    </p>
                </div>
                <Link href="/signup">
                    <Button className="bg-white text-slate-900 hover:bg-slate-100 shrink-0 shadow-lg">
                        Get Business Tools
                    </Button>
                </Link>
            </div>
        </div>
    );
}
